• Home
  • Raw
  • Download

Lines Matching +full:source +full:- +full:pristine

2 ** This file is an amalgamation of many separate C source files from SQLite
17 ** language. The code for the "sqlite3" command-line shell is also in a
21 ** 2019.09.02-Complete codec logic for encryption and decryption.
33 ** The author disclaims copyright to this source code. In place of
52 ** NO_TEST - The branches on this line are not
57 ** OPTIMIZATION-IF-TRUE - This branch is allowed to alway be false
61 ** OPTIMIZATION-IF-FALSE - This branch is allowed to alway be true
65 ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
70 ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
93 ** The author disclaims copyright to this source code. In place of
141 ** 2015-03-02
143 ** The author disclaims copyright to this source code. In place of
179 ** large file support, or if the OS is windows, these should be no-ops.
183 ** code in all source files.
185 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
194 ** on 2008-11-28.) These days, all Linux kernels support large files, so
211 ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
218 ** so the GCC_VERSION macro will be set to a correct non-zero value even
271 ** some MinGW-specific macros). When compiling for MinGW, either the
294 /* Optionally #include a user-defined header, whereby compilation options
312 ** 2001-09-15
314 ** The author disclaims copyright to this source code. In place of
323 ** presents to client programs. If a C-function, structure, datatype,
334 ** The official C-language API documentation for SQLite is derived
335 ** from comments in this file. This file is the authoritative source
379 ** that require non-default calling conventions.
404 ** These no-op macros are used in front of interfaces to mark those
406 ** should not use deprecated interfaces - they are supported for backwards
430 ** CAPI3REF: Compile-Time Library Version Numbers
445 ** SQLite source code has been stored in the
446 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
448 ** a string which identifies a particular check-in of SQLite
450 ** string contains the date and time of the check-in (UTC) and a SHA1
451 ** or SHA3-256 hash of the entire source tree. If the source code has
461 #define SQLITE_SOURCE_ID "2022-12-28 14:03:47 df5c253c0b3dd24916e4ec7cf77d3db5294cc9fd45ae7b9c…
464 ** CAPI3REF: Run-Time Library Version Numbers
501 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
510 ** returning the N-th compile time option string. ^If N is out of range,
535 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
553 ** This interface only reports on the compile-time mutex setting
559 ** sqlite3_threadsafe() function shows only the compile-time setting of
560 ** thread safety, not any run-time changes to that setting made by
585 ** CAPI3REF: 64-Bit Integer Types
588 ** Because there is no cross-platform way to specify 64-bit integer types
589 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
596 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
619 ** substitute integer for floating-point.
661 ** argument is a harmless no-op.
674 ** CAPI3REF: One-Step Query Execution Interface
682 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
683 ** semicolon-separate SQL statements passed into its 2nd argument,
705 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
755 /* beginning-of-error-codes */
786 /* end-of-error-codes */
794 ** these result codes are too coarse-grained. They do not provide as
898 ** [sqlite3_open_v2()] has historically be a no-op and might become an
954 ** read-only media and cannot be changed even by processes with
1016 ** (Third-party VFS implementations might also make the distinction
1051 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1075 ** requested lock, then the call to xLock() is a no-op.
1078 ** to xUnlock() is a no-op.
1091 ** locking strategy (for example to use dot-file locks), to inquire
1138 ** fails to zero-fill short reads might seem to work. However,
1139 ** failure to zero-fill short reads will eventually lead to
1195 ** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
1197 ** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
1207 ** point to an integer (type int) containing the new chunk-size to use
1209 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1220 ** the [rollback journal] or the [write-ahead log]) for a particular database
1233 ** this file-control is NULL. However, if the database file is being synced
1234 ** as part of a multi-database commit, the argument points to a nul-terminated
1235 ** string containing the transactions super-journal file name. VFSes that
1252 ** anti-virus programs. By default, the windows VFS will retry file read,
1278 ** WAL mode. If the integer is -1, then it is overwritten with the current
1283 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1287 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1288 ** mode. If the integer is -1, then it is overwritten with the current
1289 ** zero-damage mode setting.
1300 ** final bottom-level VFS are written into memory obtained from
1304 ** all file-control actions, there is no guarantee that this will actually
1306 ** pointer in case this file-control is not implemented. This file-control
1310 ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1314 ** to a pointer to the top-level VFS.)^
1316 ** upper-most shim only.
1333 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1335 ** of the result string if the string is non-NULL.
1341 ** it is able to override built-in [PRAGMA] statements.
1345 ** file-control may be invoked by SQLite on the database file handle
1347 ** to the connection's busy-handler callback. The argument is of type (void**)
1348 ** - an array of two (void *) values. The first (void *) actually points
1350 ** busy-handler, this function should be invoked with the second (void *) in
1351 ** the array as the only argument. If it returns non-zero, then the operation
1356 ** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1366 ** maximum number of bytes that will be used for memory-mapped I/O.
1372 ** file-control is used internally to implement [PRAGMA mmap_size].
1378 ** The argument is a zero-terminated string. Higher layers in the
1380 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1405 ** Applications should <em>not</em> use this file-control.
1454 ** The parameter is a pointer to a 32-bit signed integer that contains
1455 ** the value that M is to be set to. Before returning, the 32-bit signed
1460 ** a database file. The argument is a pointer to a 32-bit unsigned integer.
1486 ** file to the database file, but before the *-shm file is updated to
1492 ** whether or not there is a database client in another process with a wal-mode
1494 ** (void*) argument passed with this file-control should be a pointer to a
1498 ** the database is not a wal-mode db, or if there is no such connection in any
1508 ** database is not a temp db, then this file-control purges the contents
1509 ** of the in-memory page cache. If there is an open transaction, or if
1510 ** the db is a temp-db, it is a no-op, not an error.
1588 ** as a normal, nul-terminated, UTF-8 buffer containing the filename, but
1631 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1649 ** consist of a single "-" character followed by no more than
1650 ** 11 alphanumeric and/or "-" characters.
1665 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1685 ** the open of a journal file a no-op. Writes to this journal would
1686 ** also be no-ops, and any attempt to read the journal would return
1688 ** file will be doing page-aligned sector reads and writes in a random
1727 ** flag is never actually used and is not implemented in the built-in
1730 ** non-zero error code if there is an I/O error or if the name of
1732 ** is returned, then non-zero or zero is written into *pResOut to indicate
1746 ** of good-quality randomness into zOut. The return value is
1754 ** a 24-hour day).
1780 void *pAppData; /* Pointer to application-specific data */
1890 ** are harmless no-ops.)^
1895 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1918 ** compile-time option, then the automatic calls to sqlite3_initialize()
1927 ** The sqlite3_os_init() routine does operating-system specific
1943 ** (using the [SQLITE_OS_OTHER=1] compile-time
1945 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1974 ** implementation of an application-defined [sqlite3_os_init()].
1984 ** then this routine returns a non-zero [error code].
1998 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
2011 ** and low-level memory allocation routines.
2023 ** Note that SQLite comes with several [built-in memory allocators]
2028 ** memory allocator that simulates memory out-of-memory conditions in
2093 ** non-zero [error code] if a discontinued or unsupported configuration option
2099 ** [threading mode] to Single-thread. In other words, it disables
2102 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2104 ** value of Single-thread and so [sqlite3_config()] will return
2110 ** [threading mode] to Multi-thread. In other words, it disables
2114 ** are enabled so that SQLite will be safe to use in a multi-threaded
2117 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2118 ** it is not possible to set the Multi-thread [threading mode] and
2133 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2142 ** alternative low-level memory allocation routines to be used in place of
2170 ** disabled, the following SQLite interfaces become non-operational:
2191 ** This configuration option is a no-op if an application-defined page
2194 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
2202 ** argument must be either a NULL pointer or a pointer to an 8-byte
2209 ** ^If pMem is NULL and N is non-zero, then each database connection
2212 ** of -1024*N bytes if N is negative, . ^If additional
2225 ** An 8-byte aligned pointer to the memory,
2232 ** The first pointer (the memory pointer) must be aligned to an 8-byte
2240 ** The argument specifies alternative low-level mutex routines to be used
2244 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2257 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2290 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2292 ** passed through as the first parameter to the application-defined logger
2300 ** In a multi-threaded application, the application-defined logger
2305 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2322 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2323 ** if that compile-time option is omitted.
2333 ** They are retained for backwards compatibility but are now no-ops.
2339 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2350 ** configuration option can be seen in the "test_sqllog.c" source file in
2351 ** the canonical SQLite source tree.</dd>
2355 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2362 ** compile-time maximum mmap size set by the
2363 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2365 ** changed to its compile-time default.
2370 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2371 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2387 ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
2396 ** becomes the [statement journal] spill-to-disk threshold.
2399 ** Or if the threshold is -1, statement journals are always held
2405 ** [SQLITE_STMTJRNL_SPILL] compile-time option.
2410 ** of type (int) - the new value of the sorter-reference size threshold.
2414 ** of a table column that its values are likely to be very large - larger
2415 ** than the configured sorter-reference size threshold - then a reference
2421 ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
2426 ** [sqlite3_int64] parameter which is the default maximum size for an in-memory
2429 ** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this
2431 ** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that
2432 ** compile-time option is not set, then the default maximum is 1073741824.
2448 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
2449 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
2475 ** non-zero [error code] if a discontinued or unsupported configuration option
2491 ** must be aligned to an 8-byte boundary. ^If the second argument to
2527 ** triggers in the main database schema or in the schemas of ATTACH-ed
2544 ** views in the main database schema or in the schemas of ATTACH-ed
2551 ** [FTS3] full-text search engine extension.
2566 ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2568 ** When the first argument to this interface is 1, then only the C-API is
2570 ** this interface is 0, then both the C-API and the SQL function are disabled.
2571 ** If the first argument is -1, then no changes are made to state of either the
2572 ** C-API or the SQL function.
2595 ** is an integer - positive to disable checkpoints-on-close, or zero (the
2598 ** into which is written 0 or 1 to indicate whether checkpoints-on-close
2599 ** have been disabled - 0 if they are not disabled, 1 if they are.
2622 ** behavior. The first parameter passed to this operation is an integer -
2626 ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
2680 ** behaves as it did prior to [version 3.24.0] (2018-06-04). See the
2689 ** the legacy [double-quoted string literal] misfeature for DML statements
2691 ** default value of this setting is determined by the [-DSQLITE_DQS]
2692 ** compile-time option.
2698 ** the legacy [double-quoted string literal] misfeature for DDL statements,
2700 ** default value of this setting is determined by the [-DSQLITE_DQS]
2701 ** compile-time option.
2728 ** created database file to have a schema format version number (the 4-byte
2785 ** has a unique 64-bit signed
2866 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2888 ** any changes performed by sub-triggers, as the sqlite3_changes()
2889 ** value will be saved and restored after each sub-trigger has run.)^
2957 ** CAPI3REF: Interrupt A Long-Running Query
2963 ** or Ctrl-C where the user wants a long query operation to halt
2988 ** SQL statements is a no-op and has no effect on SQL statements
2996 ** These routines are useful during command-line input to determine if the
3002 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
3017 ** then the return value from sqlite3_complete16() will be non-zero
3020 ** The input to [sqlite3_complete()] must be a zero-terminated
3021 ** UTF-8 string.
3023 ** The input to [sqlite3_complete16()] must be a zero-terminated
3024 ** UTF-16 string in native byte order.
3031 ** KEYWORDS: {busy-handler callback} {busy handler}
3053 ** ^If the callback returns non-zero, then another attempt
3129 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
3131 ** to zero-terminated strings that contain the names of the columns.
3133 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
3145 ** -----------------------
3167 ** semicolon-separated SQL statements in the zero-terminated UTF-8
3199 ** These routines are work-alikes of the "printf()" family of functions
3203 ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
3204 ** See the [built-in printf()] documentation for details.
3227 ** guarantees that the buffer is always zero-terminated. ^The first
3230 ** written will be n-1 characters.
3234 ** See also: [built-in printf()], [printf() SQL function]
3246 ** does not include operating-system specific [VFS] implementation. The
3257 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
3258 ** of a signed 32-bit integer.
3263 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
3268 ** might result if sqlite3_free() is called with a non-NULL pointer that
3288 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
3289 ** of a 32-bit signed integer.
3304 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
3328 ** routines, which form the built-in memory allocation subsystem.
3333 ** value of [sqlite3_memory_used()] since the high-water mark
3340 ** ^The memory high-water mark is reset to the current value of
3343 ** by [sqlite3_memory_highwater(1)] is the high-water mark
3350 ** CAPI3REF: Pseudo-Random Number Generator
3352 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
3355 ** the built-in random() and randomblob() SQL functions. This interface allows
3366 ** non-NULL P then the pseudo-randomness is generated
3373 ** CAPI3REF: Compile-Time Authorization Callbacks
3404 ** to the callback are either NULL pointers or zero-terminated strings
3425 ** SQL statements from an untrusted source, to ensure that the SQL statements
3432 ** user-entered SQL is being [sqlite3_prepare | prepared] that
3451 ** statement might be re-prepared during [sqlite3_step()] due to a
3497 ** is the name of the inner-most trigger or view that is responsible for
3499 ** top-level SQL code.
3549 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3553 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3555 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3560 ** the original statement text and an estimate of wall-clock time
3580 ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
3602 ** interface by using the X argument when X begins with "--" and invoking
3609 ** X argument points to a 64-bit integer which is the estimated of
3639 ** M argument should be the bitwise OR-ed combination of
3689 ** ^If the progress callback returns non-zero, the operation is
3706 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3707 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3718 ** ^The default encoding will be UTF-8 for databases created using
3720 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
3734 ** <dd>The database is opened in read-only mode. If the database does not
3756 ** <dd>The database will be opened as an in-memory database. The database
3757 ** is named by the "filename" argument for the purposes of cache-sharing,
3762 ** <dd>The new database connection will use the "multi-thread"
3780 ** this option is a no-op.
3806 ** upon it. Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op
3817 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3818 ** is created for the connection. ^This in-memory database will vanish when
3826 ** on-disk database will be created. ^This private database will be
3836 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3859 ** SQLite and its built-in [VFSes] interpret the
3874 ** ^If "ro" is specified, then the database is opened for read-only
3877 ** "rw", then the database is opened for read-write (but not create)
3881 ** set to "memory" then a pure [in-memory database] that never reads
3908 ** read-only media. ^When immutable is set, SQLite assumes that the
3910 ** privilege, and so the database is opened read-only and all locking
3935 ** <tr><td style="white-space:nowrap">
3939 ** necessary - space characters can be used literally
3942 ** Open file "data.db" in the current directory for read-only access.
3943 ** Regardless of whether or not shared-cache mode is enabled by
3945 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3946 ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3947 ** that uses dot-files in place of posix advisory locking.
3955 ** percent sign - "%" - followed by exactly two hexadecimal digits
3957 ** URI filename are interpreted, they are encoded using UTF-8 and all
3959 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3963 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3965 ** characters must be converted to UTF-8 prior to passing them into
3975 const char *filename, /* Database filename (UTF-8) */
3979 const void *filename, /* Database filename (UTF-16) */
3983 const char *filename, /* Database filename (UTF-8) */
4020 ** case or if the value begins with a non-zero number. The
4028 ** 64-bit signed integer and returns that integer, or D if P does not
4033 ** the value) of the N-th query parameter for filename F, or a NULL
4035 ** parameters minus 1. The N value is zero-based so N should be 0 to obtain
4094 ** ^If X is the name of a rollback or WAL-mode journal file that is
4100 ** only. It is not a general-purpose interface.
4144 ** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.
4180 ** change the value of the error code. The error-code preserving
4191 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
4192 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
4198 ** ^The sqlite3_errstr() interface returns the English-language text
4199 ** that describes the [result code], as UTF-8.
4208 ** SQL, then the sqlite3_error_offset() function returns -1.
4239 ** original SQL text is source code. A prepared statement object
4243 ** The life-cycle of a prepared statement object usually goes like this:
4258 ** CAPI3REF: Run-time Limits
4271 ** set at compile-time by a C preprocessor macro called
4280 ** simply invoke this interface with the third parameter set to -1.
4282 ** Run-time limits are intended for use in applications that manage
4295 ** New run-time limit categories may be added in future releases.
4300 ** CAPI3REF: Run-Time Limit Categories
4304 ** that can be lowered at run-time using [sqlite3_limit()].
4390 ** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
4413 ** To execute an SQL statement, it must first be compiled into a byte-code
4422 ** The use of the UTF-8 interfaces is preferred, as SQLite currently
4423 ** does all parsing using UTF-8. The UTF-16 interfaces are provided
4424 ** as a convenience. The UTF-16 interfaces work by converting the
4425 ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
4432 ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
4434 ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
4435 ** and sqlite3_prepare16_v3() use UTF-16.
4441 ** If the caller knows that the supplied string is nul-terminated, then
4444 ** the nul-terminator.
4494 ** ^The specific value of a WHERE-clause [parameter] might influence the
4495 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
4497 ** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.
4509 const char *zSql, /* SQL statement, UTF-8 encoded */
4516 const char *zSql, /* SQL statement, UTF-8 encoded */
4523 const char *zSql, /* SQL statement, UTF-8 encoded */
4531 const void *zSql, /* SQL statement, UTF-16 encoded */
4538 const void *zSql, /* SQL statement, UTF-16 encoded */
4545 const void *zSql, /* SQL statement, UTF-16 encoded */
4556 ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
4560 ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
4563 ** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
4579 ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
4580 ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
4591 ** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined.
4603 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
4607 ** Note that [application-defined SQL functions] or
4611 ** change the database file through side-effects:
4637 ** makes it a no-op, but the sqlite3_stmt_readonly() result would still
4639 ** read-only no-op if the table already exists, but
4664 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
4701 ** sqlite3_value object. If SQLite is compiled to be single-threaded
4712 ** implementation of [application-defined SQL functions] are protected.
4730 ** is always first parameter to [application-defined SQL functions].
4731 ** The application-defined SQL function implementation will pass this
4781 ** it should be a pointer to well-formed UTF8 text.
4783 ** it should be a pointer to well-formed UTF16 text.
4785 ** it should be a pointer to a well-formed unicode string that is
4789 ** [[byte-order determination rules]] ^The byte-order of
4790 ** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
4807 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
4847 ** ^A negative value for the zeroblob results in a zero-length BLOB.
4849 ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
4921 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
4932 ** ^If the value N is out of range or if the N-th parameter is
4934 ** always in UTF-8 encoding even if the named parameter was
4935 ** originally specified as UTF-16 in [sqlite3_prepare16()],
4952 ** name must be given in UTF-8 even if the original statement
4953 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
4994 ** interface returns a pointer to a zero-terminated UTF-8 string
4995 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
4996 ** UTF-16 string. ^The first parameter is the [prepared statement]
5007 ** (for example during a conversion from UTF-8 to UTF-16) then a
5019 ** CAPI3REF: Source Of Data In A Query Result
5026 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
5035 ** ^The names returned are the original un-aliased names of the
5041 ** ^The left-most column is column 0 for these routines.
5050 ** UTF-16 encoded strings and the other functions return UTF-8.
5053 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
5077 ** ^The returned string is always UTF-8 encoded.
5090 ** ^SQLite uses dynamic run-time typing. ^So just because a column
5140 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
5166 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
5199 ** will return non-zero if previous call to [sqlite3_step](P) returned
5201 ** where it always returns zero since each step of that multi-step
5215 ** <li> 64-bit signed integer
5216 ** <li> 64-bit IEEE floating point number
5249 ** <tr><td><b>sqlite3_column_int</b><td>&rarr;<td>32-bit INTEGER result
5250 ** <tr><td><b>sqlite3_column_int64</b><td>&rarr;<td>64-bit INTEGER result
5251 ** <tr><td><b>sqlite3_column_text</b><td>&rarr;<td>UTF-8 TEXT result
5252 ** <tr><td><b>sqlite3_column_text16</b><td>&rarr;<td>UTF-16 TEXT result
5257 ** or a UTF-8 TEXT result in bytes
5259 ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5311 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
5313 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
5314 ** the string to UTF-8 and then returns the number of bytes.
5316 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
5320 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
5322 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
5323 ** the string to UTF-16 and then returns the number of bytes.
5325 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
5336 ** even empty strings, are always zero-terminated. ^The return
5337 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
5353 ** [application-defined SQL functions] or [virtual tables], not within
5354 ** top-level application code.
5372 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
5393 ** sqlite3_column_text16() is called. A zero-terminator might
5395 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
5397 ** to UTF-16.</li>
5398 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
5400 ** to UTF-8.</li>
5403 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
5434 ** fail if an out-of-memory error occurs during a format conversion.
5435 ** Only the following subset of interfaces are subject to out-of-memory
5446 ** If an out-of-memory error occurs, then the return value from these
5448 ** Valid SQL NULL returns can be distinguished from out-of-memory errors
5482 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
5497 ** object back to its initial state, ready to be re-executed.
5536 ** connection then application-defined SQL functions must be added
5540 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
5541 ** representation, exclusive of the zero-terminator. ^Note that the name
5542 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
5548 ** aggregate takes. ^If this parameter is -1, then the SQL function or
5551 ** parameter is less than -1 or greater than 127 then the behavior is
5570 ** deterministic. The built-in [random()] SQL function is an example of a
5581 ** all application-defined SQL functions that do not need to be
5595 ** pointers to C-language functions that implement the SQL function or
5605 ** C-language callbacks that implement the new function. xStep and xFinal
5606 ** must both be non-NULL. xValue and xInverse may either both be NULL, in
5608 ** non-NULL, in which case the new function may be used as either an aggregate
5611 ** [user-defined window functions|available here].
5626 ** SQL function is used. ^A function implementation with a non-negative
5635 ** ^Built-in functions may be overloaded by new application-defined functions.
5637 ** ^An application-defined function is permitted to call other
5692 #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
5693 #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
5694 #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
5721 ** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in
5725 ** for all [application-defined SQL functions], and especially for functions
5726 ** that have side-effects or that could potentially leak sensitive
5746 ** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions
5748 ** SQLITE_INNOCUOUS flag for application-defined functions unless the
5750 ** security-adverse side-effects and information-leaks.
5755 ** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
5757 ** functions. However, if it is not specified for a user-defined window
5758 ** function, then any sub-types belonging to arguments passed to the window
5797 ** <tr><td><b>sqlite3_value_int</b><td>&rarr;<td>32-bit INTEGER value
5798 ** <tr><td><b>sqlite3_value_int64</b><td>&rarr;<td>64-bit INTEGER value
5800 ** <tr><td><b>sqlite3_value_text</b><td>&rarr;<td>UTF-8 TEXT value
5801 ** <tr><td><b>sqlite3_value_text16</b><td>&rarr;<td>UTF-16 TEXT value in
5803 ** <tr><td><b>sqlite3_value_text16be</b><td>&rarr;<td>UTF-16be TEXT value
5804 ** <tr><td><b>sqlite3_value_text16le</b><td>&rarr;<td>UTF-16le TEXT value
5807 ** or a UTF-8 TEXT in bytes
5809 ** <td>&rarr;&nbsp;&nbsp;<td>Size of UTF-16
5827 ** implement [application-defined SQL functions] and [virtual tables].
5837 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
5838 ** in the native byte-order of the host machine. ^The
5840 ** extract UTF-16 strings as big-endian and little-endian respectively.
5891 ** ^The sqlite3_value_frombind(X) interface returns non-zero if the
5906 ** fail if an out-of-memory error occurs during a format conversion.
5907 ** Only the following subset of interfaces are subject to out-of-memory
5920 ** If an out-of-memory error occurs, then the return value from these
5922 ** Valid SQL NULL returns can be distinguished from out-of-memory errors
5949 ** an [application-defined SQL function] argument V. The subtype
5969 ** then sqlite3_value_free(V) is a harmless no-op.
6030 ** the application-defined function is running.
6050 ** These functions may be used by (non-aggregate) SQL functions to
6054 ** of where this might be useful is in a regular-expression matching
6063 ** value to the application-defined function. ^N is zero for the left-most
6068 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
6069 ** argument of the application-defined function. ^Subsequent
6093 ** function parameters that are compile-time constants, including literal
6096 ** The value of the N parameter to these interfaces should be non-negative.
6123 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
6139 ** an application-defined function to be the BLOB whose content is pointed
6144 ** interfaces set the result of the application-defined function to be
6148 ** an application-defined function to be a floating point value specified
6156 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
6157 ** interprets the string from sqlite3_result_error16() as UTF-16 using
6158 ** the same [byte-order determination rules] as [sqlite3_bind_text16()].
6163 ** sqlite3_result_error16() is non-negative then SQLite takes that many
6181 ** of the application-defined function to be the 32-bit signed integer
6184 ** of the application-defined function to be the 64-bit signed integer
6188 ** of the application-defined function to be NULL.
6192 ** set the return value of the application-defined function to be
6193 ** a text string which is represented as UTF-8, UTF-16 native byte order,
6194 ** UTF-16 little endian, or UTF-16 big endian, respectively.
6196 ** application-defined function to be a text string in an encoding
6206 ** is non-negative, then as many bytes (not characters) of the text
6207 ** pointed to by the 2nd parameter are taken as the application-defined
6208 ** function result. If the 3rd parameter is non-negative, then it
6215 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
6231 ** byte-order mark (BOM, U+FEFF) then the BOM is removed from the
6233 ** byte-order specified by the BOM. ^The byte-order specified by
6234 ** the BOM at the beginning of the text overrides the byte-order
6237 ** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the
6248 ** the application-defined function to be a copy of the
6259 ** also associates the host-language pointer P or type T with that
6261 ** [application-defined SQL function] using [sqlite3_value_pointer()].
6269 ** than the one containing the application-defined function that received
6301 ** the result from the [application-defined SQL function] with
6317 ** ^The name of the collation is a UTF-8 string
6319 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
6382 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
6425 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
6426 ** the names are passed as UTF-16 in machine native byte order.
6427 ** ^A call to either function replaces the existing collation-needed callback.
6524 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
6566 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
6567 ** &nbsp; TemporaryFolder->Path->Data();
6570 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
6583 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
6622 ** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
6627 ** the current directory on the sub-platforms of Win32 where that concept is
6631 ** UTF-8 or UTF-16, respectively.
6650 ** CAPI3REF: Test For Auto-Commit Mode
6654 ** ^The sqlite3_get_autocommit() interface returns non-zero or
6658 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
6660 ** If certain kinds of errors occur on a statement within a multi-statement
6691 ** for the N-th database on database connection D, or a NULL pointer of N is
6693 ** the "temp" schema. Larger values of N correspond to various ATTACH-ed
6701 ** remember the string long-term should make their own copy. Applications that
6703 ** threads should mutex-protect calls to this API and should make their own
6715 ** connection D, or if database N is a temporary or in-memory database, then
6720 ** is [DETACH]-ed or until the database connection closes.
6741 ** CAPI3REF: Determine if a database is read-only
6745 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
6764 ** a valid schema, then -1 is returned.
6830 ** ^If the callback on a commit hook function returns non-zero,
6852 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
6854 ** hook returning non-zero, just as it would be with any other rollback.
6874 ** the schema-name of the attached database that is being autovacuumed,
6882 ** <p>^If there are multiple ATTACH-ed database files that are being
6997 ** [-DSQLITE_OMIT_SHARED_CACHE]. The [-DSQLITE_OMIT_SHARED_CACHE]
6998 ** compile-time option is recommended because the
7024 ** shared cache mode should be enabled per-database connection via
7028 ** 32-bit integer is atomic.
7030 ** See Also: [SQLite Shared-Cache Mode]
7038 ** of heap memory by deallocating non-essential memory allocations
7040 ** pages to improve performance is an example of non-essential memory.
7043 ** ^The sqlite3_release_memory() routine is a no-op returning zero
7057 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
7092 ** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).
7116 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
7117 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
7150 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
7154 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
7221 int *pAutoinc /* OUTPUT: True if column is auto-increment */
7233 ** with various operating-system specific extensions added.
7242 ** X is consists of the lower-case equivalent of all ASCII alphabetic
7281 ** [extension loading] while evaluating user-entered SQL, the following API
7289 ** ^This interface enables or disables both the C-API
7292 ** to enable or disable only the C-API.)^
7332 ** on the list of automatic extensions is a harmless no-op. ^No entry point
7361 ** The interface to the virtual-table mechanism is currently considered
7365 ** When the virtual-table mechanism stabilizes, we will declare the
7439 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
7451 ** expr on the right-hand side can be evaluated (and thus the constraint
7466 ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
7472 ** non-zero.
7476 ** the right-hand side of the corresponding aConstraint[] is evaluated
7477 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
7506 ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
7537 int iColumn; /* Column constrained. -1 for ROWID */
7540 int iTermOffset; /* Used internally - xBestIndex should ignore */
7582 ** ^The left-hand operand of the operator is given by the corresponding
7583 ** aConstraint[].iColumn field. ^An iColumn of -1 indicates the left-hand
7586 ** operators have no left-hand operand, and so for those operators the
7595 ** The right-hand operands for each constraint might be accessible using
7596 ** the [sqlite3_vtab_rhs_value()] interface. Usually the right-hand
7598 ** in the input SQL. If the right-hand operand is another column or an
7602 ** SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand
7607 ** the [sqlite3_vtab_collation()] interface. For most real-world virtual
7770 ** The interface to the virtual-table mechanism defined above (back up
7775 ** When the virtual-table mechanism stabilizes, we will declare the
7812 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
7814 ** read-only access.
7850 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
7866 ** and the built-in [zeroblob] SQL function may be used to create a
7867 ** zero-filled blob to read or write using the incremental-blob interface.
7897 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
7919 ** ^If the blob handle being closed was opened for read-write access, and if
7920 ** the database is in auto-commit mode and there are no other open read-write
7928 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
7955 ** caller-supplied buffer. N bytes of data are copied into buffer Z
7984 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
8033 ** ^Names are zero-terminated UTF-8 strings.
8062 ** The SQLite source code contains multiple implementations
8064 ** is selected automatically at compile-time. The following
8075 ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
8080 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
8117 ** cases where it really needs one. If a faster non-recursive mutex
8164 ** behave as no-ops.
8177 ** An instance of this structure defines the low-level routines
8227 ** xMutexInit() must be no-ops.
8273 ** the routine should return 1. This seems counter-intuitive since
8277 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
8293 ** next. Applications that override the built-in mutex logic must be
8309 #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
8324 ** ^If the [threading mode] is Single-thread or Multi-thread then this
8330 ** CAPI3REF: Low-Level Control Of Database Files
8442 ** by enclosing in double-quotes) so as not to confuse the parser.
8447 ** The sqlite3_keyword_name(N,Z,L) interface finds the N-th keyword and
8450 ** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
8456 ** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
8468 ** <li> Put all identifier names inside double-quotes. This is the official
8479 ** compile-time options. For example, "VACUUM" is not a keyword if
8480 ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
8491 ** An instance of the sqlite3_str object contains a dynamically-sized
8515 ** valid [sqlite3_str] object, though in the event of an out-of-memory
8555 ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
8560 ** onto the end of the [sqlite3_str] object X. N must be non-negative.
8561 ** S must contain at least N non-zero bytes of content. To append a
8562 ** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
8566 ** zero-terminated string S onto the end of [sqlite3_str] object X.
8569 ** single-byte character C onto the end of [sqlite3_str] object X.
8595 ** [SQLITE_NOMEM] following any out-of-memory error, or
8602 ** zero-termination byte.
8637 ** SQLITE_OK on success and a non-zero [error code] on failure.
8640 ** be represented by a 32-bit integer, then the values returned by
8658 ** These integer constants designate various run-time status parameters
8666 ** and internal memory usage by the SQLite library. Auxiliary page-cache
8751 ** non-zero [error code] on failure.
8767 ** The [sqlite3_db_status()] interface will return a non-zero error code
8777 ** satisfied using lookaside memory. Only the high-water value is meaningful;
8785 ** Only the high-water value is meaningful;
8793 ** Only the high-water value is meaningful;
8816 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
8856 ** to disk all at once. When pages spill mid-transaction, that introduces
8927 ** A non-zero value in this counter may indicate an opportunity to
8933 ** A non-zero value in this counter may indicate an opportunity to
8962 ** step was bypassed because a Bloom filter returned not-found. The
9032 ** The built-in page cache is recommended for most uses.
9047 ** built-in default page cache is used instead of the application defined
9079 ** false if it is used for an in-memory database. The cache implementation
9090 ** suggested maximum cache-size (number of pages stored by) the cache
9136 ** as its second argument. If the third parameter, discard, is non-zero,
9170 ** is not obligated to free any memory, but well-behaved implementations should
9229 ** for copying in-memory databases to or from persistent files.
9235 ** ^The source database is read-locked only while it is being read;
9237 ** ^Thus, the backup may be performed on a live source database without
9239 ** reading or writing to the source database while the backup is underway.
9263 ** and database name of the source database, respectively.
9264 ** ^The source and destination [database connections] (parameters S and D)
9269 ** there is already a read or read-write transaction open on the
9287 ** the source and destination databases specified by [sqlite3_backup] object B.
9288 ** ^If N is negative, all remaining source pages are copied.
9292 ** from source to destination, then it returns [SQLITE_DONE].
9301 ** <li> the destination database was opened read-only, or
9302 ** <li> the destination database is using write-ahead-log journaling
9303 ** and the destination and source page sizes differ, or
9304 ** <li> the destination database is an in-memory database and the
9305 ** destination and source page sizes differ.
9308 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
9309 ** the [sqlite3_busy_handler | busy-handler function]
9311 ** busy-handler returns non-zero before the lock is available, then
9313 ** sqlite3_backup_step() can be retried later. ^If the source
9315 ** is being used to write to the source database when sqlite3_backup_step()
9329 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
9331 ** ^Because the source database is not locked between calls to
9332 ** sqlite3_backup_step(), the source database may be modified mid-way
9333 ** through the backup process. ^If the source database is modified by an
9336 ** restarted by the next call to sqlite3_backup_step(). ^If the source
9349 ** active write-transaction on the destination database is rolled back.
9356 ** ^If an out-of-memory condition or IO error occurred during any prior
9370 ** in the source database at the conclusion of the most recent
9373 ** sqlite3_backup_step(). If the source database is modified in a way that
9374 ** changes the size of the source database or the number of pages remaining,
9381 ** ^The source [database connection] may be used by the application for other
9384 ** connections, then the source database connection may be used concurrently
9413 sqlite3 *pSource, /* Source database handle */
9414 const char *zSourceName /* Source database name */
9425 ** ^When running in shared-cache mode, a database operation may fail with
9426 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
9427 ** individual tables within the shared-cache cannot be obtained. See
9428 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
9432 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
9436 ** ^Shared-cache locks are released when a database connection concludes
9440 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
9450 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
9456 ** ^If the blocked connection is attempting to obtain a write-lock on a
9457 ** shared-cache table, and more than one other connection currently holds
9458 ** a read-lock on the same table, then SQLite arbitrarily selects one of
9461 ** ^(There may be at most one unlock-notify callback registered by a
9463 ** blocked connection already has a registered unlock-notify callback,
9466 ** unlock-notify callback is canceled. ^The blocked connections
9467 ** unlock-notify callback may also be canceled by closing the blocked
9470 ** The unlock-notify callback is not reentrant. If an application invokes
9471 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
9479 ** When an unlock-notify callback is registered, the application provides a
9483 ** an unlock-notify callback is a pointer to an array of void* pointers,
9487 ** more than one blocked connection that has registered for an unlock-notify
9497 ** Assuming that after registering for an unlock-notify callback a
9508 ** unlock-notify callback is registered. The system is said to be in
9509 ** a deadlocked state if connection A has registered for an unlock-notify
9511 ** B has itself registered for an unlock-notify callback when connection
9514 ** registered for an unlock-notify callback on the conclusion of connection
9526 ** sqlite3_unlock_notify() results in the unlock-notify callback being
9527 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
9547 ** and extensions to compare the contents of two buffers containing UTF-8
9548 ** strings in a case-independent fashion, using the same definition of "case
9564 ** Note that this routine returns zero on a match and non-zero if the strings
9581 ** insensitive - equivalent upper and lower case ASCII characters match
9587 ** Note that this routine returns zero on a match and non-zero if the strings
9611 ** a fixed-length buffer on the stack. If the log message is longer than
9618 ** CAPI3REF: Write-Ahead Log Commit Hook
9625 ** the associated write-lock on the database released)^, so the implementation
9631 ** ^The third parameter is the name of the database that was written to -
9632 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
9633 ** is the number of pages currently in the write-ahead log file,
9644 ** A single database handle may have at most a single write-ahead log callback
9646 ** previously registered write-ahead log callback. ^The return value is
9659 ** CAPI3REF: Configure an auto-checkpoint
9666 ** more frames in the [write-ahead log] file. ^Passing zero or
9681 ** ^Every new [database connection] defaults to having the auto-checkpoint
9697 ** [write-ahead log] for database X on [database connection] D to be
9698 ** transferred into the database file and for the write-ahead log to
9724 ** in the log were checkpointed. ^The [busy-handler callback]
9731 ** [sqlite3_busy_handler|busy-handler callback]) until there is no
9740 ** [busy-handler callback])
9753 ** the log file or to -1 if the checkpoint could not run because
9757 ** was called) or to -1 if the checkpoint could not run due to an error or
9765 ** busy-handler configured, it will not be invoked in this case.
9769 ** obtained immediately, and a busy-handler is configured, it is invoked and
9770 ** the writer lock retried until either the busy-handler returns 0 or the lock
9771 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
9772 ** database readers as described above. ^If the busy-handler returns 0 before
9775 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
9791 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
9867 ** If X is non-zero, then the virtual table implementation guarantees
9953 ** [xUpdate] method understands as a "no-change" value.
10094 ** on the right-hand side of the IN operator.)^ Thus the virtual table
10095 ** only sees a single value from the right-hand side of the IN operator
10099 ** table to see all values on the right-hand of the IN operator all at
10104 ** ^A call to sqlite3_vtab_in(P,N,-1) will return true (non-zero)
10105 ** if and only if the [sqlite3_index_info|P->aConstraint][N] constraint
10107 ** sqlite3_vtab_in() with -1 in the third argument is a mechanism
10108 ** by which the virtual table can ask SQLite if all-at-once processing
10114 ** the IN operator all-at-once, respectively. ^Thus when the third
10115 ** parameter (F) is non-negative, this interface is the mechanism by
10124 ** (non-zero), that means that the constraint is an IN operator
10125 ** that can be processed all-at-once. ^If the constraint is not an IN
10126 ** operator or cannot be processed all-at-once, then the interface returns
10129 ** ^(All-at-once processing of the IN operator is selected if both of the
10133 ** <li><p> The P->aConstraintUsage[N].argvIndex value is set to a positive
10135 ** use the N-th constraint.
10138 ** non-negative had F>=1.
10142 ** the traditional one-at-a-time processing strategy for the IN constraint.
10143 ** ^If both conditions are true, then the argvIndex-th parameter to the
10146 ** [sqlite3_vtab_in_next()] to find all values on the right-hand side
10152 ** CAPI3REF: Find all elements on the right-hand side of an IN constraint.
10162 ** a parameter that was previously selected for all-at-once IN constraint
10165 ** an xFilter argument that was selected for all-at-once IN constraint
10169 ** ^(Use these routines to access all values on the right-hand side
10211 ** J being a 0-based index into P->aConstraint[], then this routine
10212 ** attempts to set *V to the value of the right-hand operand of
10213 ** that constraint if the right-hand operand is known. ^If the
10214 ** right-hand operand is not known, then *V is set to a NULL pointer.
10217 ** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th
10223 ** the right-hand operand of a constraint is a literal value in the original
10224 ** SQL statement. If the right-hand operand is an expression or a reference
10229 ** [SQLITE_INDEX_CONSTRAINT_ISNOTNULL], have no right-hand operand. For such
10238 ** "Right-Hand Side".
10275 ** set to the total number of times that the X-th loop has run.</dd>
10279 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
10284 ** iteration of the X-th loop. If the query planner's estimates was accurate,
10291 ** to a zero-terminated UTF-8 string containing the name of the index or table
10292 ** used for the X-th loop.
10296 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
10297 ** description for the X-th loop.
10301 ** "select-id" for the X-th loop. The select-id identifies which query or
10302 ** subquery the loop is part of. The main query has a select-id of zero.
10303 ** The select-id is the same value as is output in the first column
10325 ** compile-time option.
10333 ** Loops are numbered starting from zero. ^If idx is out of range - less than
10335 ** the statement - a non-zero value is returned and the variable that pOut
10340 ** as if the loop did not exist - it returns non-zero and leave the variable
10353 ** CAPI3REF: Zero Scan-Status Counters
10358 ** This API is only available if the library is built with pre-processor
10364 ** CAPI3REF: Flush caches to disk mid-transaction
10367 ** ^If a write-transaction is open on [database connection] D when the
10369 ** pages in the pager-cache that are not currently in use are written out
10373 ** interface flushes caches for all schemas - "main", "temp", and
10378 ** immediately and there is a busy-handler callback configured, it is invoked
10386 ** example an IO error or out-of-memory condition), then processing is
10397 ** CAPI3REF: The pre-update hook.
10401 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
10473 ** operation; or 1 for inserts, updates, or deletes invoked by top-level
10474 ** triggers; or 2 for changes resulting from triggers called by top-level
10478 ** the pre-update hook is invoked with SQLITE_DELETE. This is because the
10483 ** pre-update hook is being invoked for some other reason, including a
10484 ** regular DELETE, sqlite3_preupdate_blobwrite() returns -1.
10510 ** CAPI3REF: Low-level system error code
10515 ** The return value is OS-dependent. For example, on unix systems, after
10555 ** If there is not already a read-transaction open on schema S when
10587 ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
10621 ** is returned. If another error code - for example SQLITE_PROTOCOL or an
10622 ** SQLITE_IOERR error code - is returned, then the final state of the
10636 ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
10653 ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
10720 ** For an ordinary on-disk database file, the serialization is just a
10721 ** copy of the disk file. For an in-memory database or a "TEMP" database,
10758 ** Zero or more of the following constants can be OR-ed together for
10762 ** a pointer to contiguous in-memory database that it is currently using,
10764 ** a contiguous in-memory database, then this option causes
10766 ** using a contiguous in-memory database if it has been initialized by a
10776 ** reopen S as an in-memory database based on the serialization contained
10780 ** permitted to add content to the in-memory database as long as the total
10832 ** should be treated as read-only.
10836 #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
10855 ** The author disclaims copyright to this source code. In place of
10876 /* The double-precision datatype used by RTree depends on the
10877 ** SQLITE_RTREE_INT_ONLY compile-time option.
10887 ** R-Tree geometry query as follows:
10912 ** Register a 2nd-generation geometry callback named zScore that can be
10913 ** used as part of an R-Tree geometry query as follows:
11019 ** is not possible for an application to register a pre-update hook on a
11022 ** which a pre-update hook is already defined. The results of attempting
11090 ** disabled - it does not. A newly created session object is enabled.
11097 ** no-op, and may be used to query the current state of the session.
11174 ** rows a zero-length blob (SQL value X'') is stored in the changeset or
11180 ** zero-length blob back to a NULL value when updating the sqlite_stat1
11184 ** conflict-handler callback) then the X'' value is returned. The application
11232 ** database row along with the updated values for each updated non-primary-key
11241 ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
11243 ** with non-NULL PRIMARY KEY values is updated so that one or more of its
11256 ** are sorted in the same order in which they were attached (or auto-attached)
11270 ** recorded once - the first time a row with said primary key is inserted,
11277 ** The session object therefore accumulates two types of records - those
11295 ** found and one or more of the non-primary key fields have been
11312 ** This may appear to have some counter-intuitive effects if a single row
11328 ** CAPI3REF: Return An Upper-limit For The Size Of The Changeset
11350 ** does not have a primary key, this function is a no-op (but does not return
11370 ** used to update the table in database zFrom (call this the "from-table")
11372 ** object (call this the "to-table"). Specifically:
11375 ** <li> For each row (primary key) that exists in the to-table but not in
11376 ** the from-table, an INSERT record is added to the session object.
11378 ** <li> For each row (primary key) that exists in the to-table but not in
11379 ** the from-table, a DELETE record is added to the session object.
11382 ** different non-PK values in each, an UPDATE record is added to the
11427 ** Because the non-primary key "old.*" fields are omitted, no
11446 ** Return non-zero if no changes to attached tables have been recorded by
11454 ** are restored. However, if this function returns non-zero, then it is
11541 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
11565 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
11578 ** *pzTab is set to point to a nul-terminated utf-8 encoded string containing
11581 ** or until the conflict-handler function returns.
11628 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
11637 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
11668 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
11702 ** conflict-handler callback by [sqlite3changeset_apply()] with either
11713 ** "conflicting row" associated with the current conflict-handler callback
11751 ** function with an iterator passed to a conflict-handler by
11759 ** returned. This is to allow the following pattern (pseudo-code):
11912 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
11913 ** <tr><th style="white-space:pre">Existing Change </th>
11914 ** <th style="white-space:pre">New Change </th>
11959 ** returned. Or, if an out-of-memory condition occurs during processing, this
12017 ** Otherwise, if the return value is non-zero or the xFilter argument to
12053 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
12057 ** returned by each invocation of the conflict-handler function. Refer to
12066 ** stored in all non-primary key columns also match the values stored in
12070 ** the non-primary key fields contains a value different from the original
12071 ** row value stored in the changeset, the conflict-handler function is
12074 ** only the values of those non-primary key fields are compared against
12075 ** the current database contents - any trailing database table columns
12079 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
12084 ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
12103 ** This includes the case where the INSERT operation is re-attempted because
12111 ** stored in all modified non-primary key columns also match the values
12115 ** the modified non-primary key fields contains a value different from an
12116 ** original row value stored in the changeset, the conflict-handler function
12118 ** UPDATE changes only contain values for non-primary key fields that are
12120 ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
12123 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
12127 ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
12145 ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
12222 ** Values that may be passed as the second argument to a conflict-handler.
12229 ** (non primary-key) fields modified by the update do not contain the
12390 ** combined on a per-field basis, not per-row. This means that in the
12474 ** corresponding non-streaming API functions:
12476 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
12477 ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
12487 ** Non-streaming functions that accept changesets (or patchsets) as input
12492 ** low-memory environment is required to handle very large changesets, the
12697 ** The author disclaims copyright to this source code. In place of
12756 ** non-negative but less than the number of columns in the table, return
12771 ** non-negative but less than the number of columns in the table, set
12785 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
12883 ** If the bClear argument is non-zero, then the auxiliary data is cleared
12905 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
12907 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
12913 ** modify this structure directly - it should only be used as shown above
12921 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
12935 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
12937 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
12946 ** xPhraseFirstColumn() set iCol to -1).
13015 ** The second and third arguments are an array of nul-terminated strings
13033 ** by argument pText. pText may or may not be nul-terminated. The first
13041 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
13046 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
13050 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
13055 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
13088 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
13122 ** still appears to contain just two phrases - "(first OR 1st)"
13133 ** when tokenizing query text (it should not - to do so would be
13180 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
13281 ** autoconf-based build
13293 ** The author disclaims copyright to this source code. In place of
13309 ** The hard limit is the ability of a 32-bit signed integer
13310 ** to count the size: 2^31-1 or 2147483647.
13328 ** tell you that in a well-normalized database, you usually should
13386 ** The suggested maximum number of in-memory pages to use for
13389 ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
13391 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
13392 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
13395 # define SQLITE_DEFAULT_CACHE_SIZE -2000
13409 ** counted using a signed 8-bit integer which has a maximum value of 127
13421 ** as a signed 32-bit integer can hold.
13428 ** imposed by the use of 16-bit offsets within each page.
13434 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
13435 ** compiled with the default page-size limit will not be able to rollback
13458 ** device characteristics (sector-size and atomic write() support),
13475 ** This value can be lowered (or raised) at run-time using that the
13506 #pragma warn -rch /* unreachable code */
13507 #pragma warn -ccc /* Condition is always true or false */
13508 #pragma warn -aus /* Assigned value is never used */
13509 #pragma warn -csu /* Comparing signed and unsigned */
13510 #pragma warn -spa /* Suspicious pointer arithmetic */
13514 ** WAL mode depends on atomic aligned 32-bit loads and stores in a few
13518 # define __has_extension(x) 0 /* compatibility with non-clang compilers */
13551 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
13564 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
13565 #else /* Generates a warning - but it always works */
13605 ** level of threadsafety. 2 means the library is multithreaded - multiple
13613 ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
13621 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
13627 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
13634 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
13663 # error "Two or more of the following compile-time configuration options\
13701 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
13766 ** Disable ALWAYS() and NEVER() (make them pass-throughs) for coverage
13778 ** of SQLite to unexpected behavior - to make the code "self-healing"
13784 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
13870 ** Return true (non-zero) if the input is an integer that is too large
13871 ** to fit in 32-bits. This macro is used inside of various testcase()
13872 ** macros to verify that we have tested SQLite for large-file support.
13891 ** The author disclaims copyright to this source code. In place of
13899 ** This is the header file for the generic hash-table implementation
13910 ** The internals of this structure are intended to be opaque -- client
13917 ** All elements of the hash table are on a single doubly-linked list.
13921 ** the global doubly-linked list. The contents of the bucket are the
13922 ** element pointed to plus the next _ht.count-1 elements in the list.
13941 ** structure. All elements are stored on a single doubly-linked list.
13972 #define sqliteHashFirst(H) ((H)->first)
13973 #define sqliteHashNext(E) ((E)->next)
13974 #define sqliteHashData(E) ((E)->data)
13975 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
13976 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
13981 #define sqliteHashCount(H) ((H)->count)
14191 int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
14196 ** substitute integer for floating-point
14227 ** the VDBE-level file format changes. The following macros define the
14238 ** changed at run-time using a pragma.
14246 ** on the command-line
14276 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
14278 ** The default value of "20" was chosen to minimize the run-time of the
14279 ** speedtest1 test program with options: --shrink-memory --reprepare
14293 ** The compile-time options SQLITE_MMAP_READWRITE and
14306 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
14337 ** types can be conveniently redefined at compile-type. Like this:
14339 ** cc '-DUINTPTR_TYPE=long long int' ...
14379 typedef sqlite_int64 i64; /* 8-byte signed integer */
14380 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
14381 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
14382 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
14383 typedef INT16_TYPE i16; /* 2-byte signed integer */
14384 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
14385 typedef INT8_TYPE i8; /* 1-byte signed integer */
14393 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
14398 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
14399 ** can be used at compile-time if desired.
14402 typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
14404 typedef u32 tRowcnt; /* 32-bit is the default */
14408 ** Estimated quantities used for query planning are stored as 16-bit
14410 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
14419 ** 1 -> 0 20 -> 43 10000 -> 132
14420 ** 2 -> 10 25 -> 46 25000 -> 146
14421 ** 3 -> 16 100 -> 66 1000000 -> 199
14422 ** 4 -> 20 1000 -> 99 1048576 -> 200
14423 ** 10 -> 33 1024 -> 100 4294967296 -> 320
14428 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
14471 ** and whether or not that determination is run-time or compile-time.
14473 ** For best performance, an attempt is made to guess at the byte-order
14474 ** using C-preprocessor macros. If that is unsuccessful, or if
14475 ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
14476 ** at run-time.
14511 ** Constants for the largest and smallest possible 64-bit signed integers.
14512 ** These macros are designed to work correctly on both 32-bit and 64-bit
14517 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
14521 ** to force 8-byte alignment on 64-bit architectures.
14526 ** pointers in size, and so it is a no-op on systems where the pointer
14542 ** Assert that the pointer X is aligned to an 8-byte boundary. This
14547 ** underlying malloc() implementation might return us 4-byte aligned
14548 ** pointers. In that case, only verify 4-byte alignment.
14551 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
14553 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
14565 ** Default maximum size of memory used by memory-mapped I/O in the VFS
14585 ** default MMAP_SIZE is specified at compile-time, make sure that it does
14609 sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
14630 ** An instance of the following structure is used to store the busy-handler
14635 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
14669 ** The root-page of the schema table.
14688 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
14707 ** directly, we use its constant as a key to lookup the run-time allocated
14709 ** for the run-time allocated buffer.
14712 ** macros become no-ops and have zero performance impact.
14810 ** Changing this from a 64-bit to a 32-bit type limits the number of
14832 #define ALLBITS ((Bitmask)-1)
14833 #define TOPBIT (((Bitmask)1)<<(BMS-1))
14853 ** The author disclaims copyright to this source code. In place of
14862 ** This header file (together with is companion C source-code file
14866 ** This header file is #include-ed by sqliteInt.h and thus ends up
14867 ** being included by every source file.
14874 ** necessary pre-processor macros for it.
14881 ** The author disclaims copyright to this source code. In place of
14890 ** This file contains pre-processor directives related to operating system
14911 ** If SQLITE_OS_OTHER=1 is specified at compile-time, then the application
14974 ** a no-op
15000 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
15002 ** 2006-10-31: The default prefix used to be "sqlite_". But then
15003 ** Mcafee started using SQLite in their anti-virus product and it
15049 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
15157 ** sqlite3_malloc() to obtain space for the file-handle structure.
15171 ** The author disclaims copyright to this source code. In place of
15193 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
15216 ** is devoted to storing a super-journal name - there are no more pages to
15220 #define PAGER_SJ_PGNO_COMPUTED(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
15221 #define PAGER_SJ_PGNO(x) ((x)->lckPgno)
15229 #define PAGER_MEMORY 0x0002 /* In-memory database */
15234 #define PAGER_LOCKINGMODE_QUERY -1
15245 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
15250 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
15251 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
15257 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
15279 ** that make up the Pager sub-system API. See source code comments for
15426 ** The author disclaims copyright to this source code. In place of
15434 ** This header file defines the interface that the sqlite B-Tree file
15435 ** subsystem. See comments in the source code for a detailed description
15447 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
15454 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
15455 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
15468 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
15483 #define BTREE_MEMORY 2 /* This is an in-memory DB */
15484 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
15538 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
15541 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
15544 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
15545 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
15565 ** For example, the free-page-count field is located at byte offset 36 of
15566 ** the database file header. The incr-vacuum-flag field is located at
15570 ** It is a read-only number computed by the pager. But we merge it with
15583 #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
15597 ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
15598 ** column of the b-tree of the cursor. The Expr tree will not contain
15599 ** any function calls nor subqueries nor references to b-trees other than
15602 ** The design of the _RANGE hint is aid b-tree implementations that try
15603 ** to prefetch content from remote machines - to provide those
15628 #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
15633 ** For read-only cursors the wrFlag argument is always zero. For read-write
15644 ** by this, the native b-tree engine of SQLite, but it is available to
15646 ** b-tree system. For alternative storage engines in which a delete of
15650 ** and DELETE operations as no-ops, and any READ operation against a
15653 #define BTREE_WRCSR 0x00000004 /* read-write cursor */
15659 int wrFlag, /* 1 for writing. 0 for read-only */
15798 ** Enter and Leave procedures no-ops.
15845 ** The author disclaims copyright to this source code. In place of
15865 ** in the source file sqliteVdbe.c are allowed to see the insides
15885 u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
15916 u32 iSrcLine; /* Source-code line that generated this opcode
15924 ** A sub-routine used to implement a trigger program.
15927 VdbeOp *aOp; /* Array of opcodes for sub-program */
15933 SubProgram *pNext; /* Next sub-program already visited */
15953 #define P4_STATIC (-1) /* Pointer to a static string */
15954 #define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
15955 #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
15956 #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
15957 #define P4_TABLE (-5) /* P4 is a pointer to a Table structure */
15959 #define P4_FREE_IF_LE (-6)
15960 #define P4_DYNAMIC (-6) /* Pointer to memory from sqliteMalloc() */
15961 #define P4_FUNCDEF (-7) /* P4 is a pointer to a FuncDef structure */
15962 #define P4_KEYINFO (-8) /* P4 is a pointer to a KeyInfo structure */
15963 #define P4_EXPR (-9) /* P4 is a pointer to an Expr tree */
15964 #define P4_MEM (-10) /* P4 is a pointer to a Mem* structure */
15965 #define P4_VTAB (-11) /* P4 is a pointer to an sqlite3_vtab structure */
15966 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
15967 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
15968 #define P4_INTARRAY (-14) /* P4 is a vector of 32-bit integers */
15969 #define P4_FUNCCTX (-15) /* P4 is a pointer to an sqlite3_context object */
16004 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
16070 #define OP_IfPos 59 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
16071 #define OP_IfNotZero 60 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
16072 #define OP_DecrJumpZero 61 /* jump, synopsis: if (--r[P1])==0 goto P2 */
16101 #define OP_Compare 90 /* synopsis: r[P1@P3] <-> r[P2@P3] */
16118 #define OP_Subtract 107 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
16135 #define OP_SeekScan 124 /* synopsis: Scan-ahead up to P1 rows */
16171 #define OP_OffsetLimit 160 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) …
16247 ** Additional non-public SQLITE_PREPARE_* flags
16296 # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
16301 # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
16378 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
16401 ** numbers in the sqlite3.c source file. VDBE branch coverage testing
16415 ** VdbeCoverageNeverNull(v) // Previous three-way branch is only
16420 ** // in distingishing equal and not-equal.
16423 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
16424 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
16430 ** contains the sqlite3.c source line number ov the VdbeCoverage macro and
16432 ** is responsible for keeping track of this and reporting byte-code branches
16436 ** vdbe.c source file for additional information.
16483 ** The author disclaims copyright to this source code. In place of
16562 /* Modify the page-size after the cache has been created. */
16584 /* Change a page number. Used by incr-vacuum. */
16626 /* Set and get the suggested cache-size for the specified pager-cache.
16629 ** the total number of pages cached by purgeable pager-caches to the sum
16630 ** of the suggested cache-sizes.
16637 /* Set or get the suggested spill-size for the specified pager-cache.
16639 ** The spill-size is the minimum number of pages in cache before the cache
16678 ** The author disclaims copyright to this source code. In place of
16689 ** to all source files. We break it out in an effort to keep the code
16692 ** NOTE: source files should *not* #include this header file directly.
16693 ** Source files should #include the sqliteInt.h file and let that file
16703 ** at start-time.
16705 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
16708 ** start-time.
16710 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
16712 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
16729 ** If this is a no-op implementation, implement everything as macros.
16750 /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
16770 ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
16771 ** In other words, the zero-based numbers are used for all external interfaces
16772 ** and the one-based values are used internally.
16800 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
16829 ** Db.pSchema->flags field.
16831 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
16832 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
16833 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
16834 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
16837 ** Allowed values for the DB.pSchema->flags field.
16857 ** Lookaside malloc is a set of fixed-size buffers that can be used
16879 ** in a performance-critical path. sz should be set by to szTrue whenever
16884 ** come off of pFree first, then pInit as a fallback. This dual-list
16885 ** allows use to compute a high-water mark - the maximum number of allocations
16886 ** outstanding at any point in the past - by subtracting the number of
16889 ** Enhancement on 2019-12-12: Two-size-lookaside
16893 ** The two-size-lookaside enhancement breaks up the lookaside allocation
16894 ** into two pools: One of 128-byte slots and the other of the default size
16895 ** (1200-byte) slots. Allocations are filled from the small-pool first,
16896 ** failing over to the full-size pool if that does not work. Thus more
16913 void *pMiddle; /* First byte past end of full-size buffers and
16918 void *pTrueEnd; /* True value of pEnd, when db->pnBytesFreed!=0 */
16924 #define DisableLookaside db->lookaside.bDisable++;db->lookaside.sz=0
16925 #define EnableLookaside db->lookaside.bDisable--;\
16926 db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue
16928 /* Size of the smaller allocations in two-size lookside */
16936 ** A hash table for built-in function definitions. (Application-defined
17021 u32 nSchemaLock; /* Do not reset the schema when non-zero */
17029 u8 autoCommit; /* The auto-commit flag. */
17033 u8 dfltLockMode; /* Default locking-mode for attached dbs */
17039 u8 noSharedCache; /* True if no shared-cache backends */
17087 PreUpdate *pPreUpdate; /* Context for active pre-update callback */
17125 int nSavepoint; /* Number of non-transaction savepoints */
17126 int nStatement; /* Number of nested statement-transactions */
17161 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
17162 #define ENC(db) ((db)->enc)
17167 ** C-compilers still do not accept LL integer literals.
17191 #define SQLITE_ReadUncommit 0x00000400 /* READ UNCOMMITTED in shared-cache */
17210 #define SQLITE_DqsDDL 0x20000000 /* dbl-quoted strings allowed in DDL*/
17211 #define SQLITE_DqsDML 0x40000000 /* dbl-quoted strings allowed in DML*/
17232 #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
17253 #define SQLITE_CountOfView 0x00000200 /* The count-of-view optimization */
17257 #define SQLITE_PushDown 0x00001000 /* The push-down optimization */
17259 #define SQLITE_SkipScan 0x00004000 /* Skip-scans */
17267 #define SQLITE_BalancedMerge 0x00200000 /* Balance multi-way merges */
17277 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
17278 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
17284 #define ConstFactorOk(P) ((P)->okConstFactor)
17299 ** structure. For global built-in functions (ex: substr(), max(), count())
17301 ** For per-connection application-defined functions, a pointer to this
17302 ** structure is held in the db->aHash hash table.
17304 ** The u.pHash field is used by the global built-ins. The u.pDestructor
17305 ** field is used by per-connection app-def functions.
17308 i8 nArg; /* Number of arguments. -1 means unlimited */
17312 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
17315 void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
17324 ** This structure encapsulates a user-function destructor callback (as
17361 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
17364 #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
17365 #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
17366 #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
17367 /* 0x0200 -- available for reuse */
17368 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
17372 ** single query - might change over time */
17373 #define SQLITE_FUNC_TEST 0x4000 /* Built-in testing functions */
17374 /* 0x8000 -- available for reuse */
17375 #define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */
17378 #define SQLITE_FUNC_SUBTYPE 0x00100000 /* Result likely to have sub-type */
17380 #define SQLITE_FUNC_INLINE 0x00400000 /* Functions implemented in-line */
17381 #define SQLITE_FUNC_BUILTIN 0x00800000 /* This is a built-in function */
17384 /* Identifier numbers for each in-line function */
17402 ** as the user-data (sqlite3_user_data()) for the function. If
17413 ** zName is the name of a function that is implemented by in-line
17419 ** zName is the name of a test-only function implemented by in-line
17428 ** a single query. The iArg is ignored. The user-data is always set
17432 ** For math-library functions. xPtr is an arbitrary pointer.
17437 ** ignored and the user-data for these functions is set to an
17438 ** arbitrary non-NULL pointer. The bNC parameter is not used.
17456 ** available as the function user-data (sqlite3_user_data()). The
17520 char *zName; /* Savepoint name (nul-terminated) */
17581 u16 iDflt; /* 1-based index of DEFAULT. 0 means "none" */
17612 #define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
17632 char *zName; /* Name of the collating sequence, UTF-8 encoded */
17644 #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
17697 ** database connections, even when the rest of the in-memory database
17707 ** database schema are initially stored in a linked-list pointed to by
17714 ** When an in-memory Table object is deleted (for example when the
17764 LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
17795 ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
17796 ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
17806 #define TF_Readonly 0x00000001 /* Read-only system table */
17817 #define TF_NoVisibleRowid 0x00000200 /* No user-visible "rowid" column */
17818 #define TF_OOOHidden 0x00000400 /* Out-of-Order hidden columns */
17833 #define IsView(X) ((X)->eTabType==TABTYP_VIEW)
17834 #define IsOrdinaryTable(X) ((X)->eTabType==TABTYP_NORM)
17842 # define IsVirtual(X) ((X)->eTabType==TABTYP_VTAB)
17844 ((X)->op==TK_COLUMN && (X)->y.pTab->eTabType==TABTYP_VTAB)
17852 ** only works for non-virtual tables (ordinary tables and views) and is
17857 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
17858 # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
17860 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
17869 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
17870 #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
17885 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
17888 ** from-table == child-table
17889 ** to-table == parent-table
17892 ** which is attached to the from-table. The to-table need not exist when
17893 ** the from-table is created. The existence of the to-table is not checked.
17907 /* EV: R-30323-21917 */
17973 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
18001 ** pKeyInfo->nField.
18005 ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
18009 ** an equals comparison. default_rc can be -1, 0, or +1. If there are
18010 ** multiple entries in the b-tree with the same key (when only looking
18011 ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
18016 ** get and equal results when comparing this structure to a b-tree record.
18020 ** b-tree.
18023 KeyInfo *pKeyInfo; /* Collation and sort-order information */
18062 ** algorithm to employ when an attempt is made to insert a non-unique
18069 ** "colUsed & colNotIdxed" will be non-zero if the index is not a
18071 ** be true (note-20221022-a). If a column beyond the 63rd column of the
18072 ** table is used, the "colUsed & colNotIdxed" test will always be non-zero
18082 ** number (it cannot - the database page is not allocated until the VDBE
18107 unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
18118 IndexSample *aSample; /* Samples of the left-most key */
18119 tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
18120 tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
18134 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
18137 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
18142 #define XN_ROWID (-1) /* Indexed column is the rowid */
18143 #define XN_EXPR (-2) /* Indexed column is an expression */
18148 ** analyze.c source file for additional information.
18175 const char *z; /* Text of the token. Not NULL-terminated! */
18194 ** from source tables rather than from accumulators */
18196 ** than the source table */
18198 int sortingIdxPTab; /* Cursor number of pseudo-table */
18202 struct AggInfo_col { /* For each column used in source tables */
18203 Table *pTab; /* Source table */
18205 int iTable; /* Cursor number of the source table */
18207 i16 iColumn; /* Column number within the source table */
18226 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
18227 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
18228 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
18233 ** the option is available (at compile-time).
18248 ** to represent the greater-than-or-equal-to operator in the expression
18262 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
18281 ** subquery gives a constant result, then iTable is -1. If the subquery
18286 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
18317 int iValue; /* Non-negative integer value if EP_IntValue */
18342 ** TK_TRIGGER: 1 -> new, 0 -> old
18347 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
18350 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
18414 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
18415 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
18416 #define ExprSetProperty(E,P) (E)->flags|=(P)
18417 #define ExprClearProperty(E,P) (E)->flags&=~(P)
18418 #define ExprAlwaysTrue(E) (((E)->flags&(EP_OuterON|EP_IsTrue))==EP_IsTrue)
18419 #define ExprAlwaysFalse(E) (((E)->flags&(EP_OuterON|EP_IsFalse))==EP_IsFalse)
18424 #define ExprUseUToken(E) (((E)->flags&EP_IntValue)==0)
18425 #define ExprUseUValue(E) (((E)->flags&EP_IntValue)!=0)
18426 #define ExprUseXList(E) (((E)->flags&EP_xIsSelect)==0)
18427 #define ExprUseXSelect(E) (((E)->flags&EP_xIsSelect)!=0)
18428 #define ExprUseYTab(E) (((E)->flags&(EP_WinFunc|EP_Subrtn))==0)
18429 #define ExprUseYWin(E) (((E)->flags&EP_WinFunc)!=0)
18430 #define ExprUseYSub(E) (((E)->flags&EP_Subrtn)!=0)
18439 ** processes but is a no-op for delivery.
18442 # define ExprSetVVAProperty(E,P) (E)->vvaFlags|=(P)
18443 # define ExprHasVVAProperty(E,P) (((E)->vvaFlags&(P))!=0)
18444 # define ExprClearVVAProperties(E) (E)->vvaFlags = 0
18464 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
18474 ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \
18490 ** ---------- -------------------------
18549 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
18558 Expr *pExpr; /* Expr to implement a USING variable -- NOT USED */
18569 #define EU4_EXPR 2 /* Uses IdList.a.u4.pExpr -- NOT CURRENTLY USED */
18580 ** In the colUsed field, the high-order bit (bit 63) is set if the table
18581 ** contains more than 63 columns and the 64-th or later column is used.
18599 int regResult; /* Registers holding results of a co-routine */
18604 unsigned isTabFunc :1; /* True if table-valued-function syntax */
18605 unsigned isCorrelated :1; /* True if sub-query is correlated */
18607 unsigned viaCoroutine :1; /* Implemented as a co-routine */
18613 unsigned isOn :1; /* u3.pOn was once valid and non-NULL */
18625 ExprList *pFuncArg; /* Arguments to table-valued-function */
18643 ** This object represents one or more tables that are the source of
18675 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
18678 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
18681 #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
18710 ** NameContexts can be nested. When resolving names, the inner-most
18726 ExprList *pEList; /* Optional list of result-set columns */
18767 #define NC_NoSelect 0x080000 /* Do not descend into sub-selects */
18775 ** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
18776 ** conflict-target clause.) The pUpsertTargetWhere is the optional
18880 #define SF_PushDown 0x1000000 /* SELECT has be modified by push-down opt */
18886 #define IsNestedFrom(S) ((S)!=0 && ((S)->selFlags&SF_NestedFrom)!=0)
18894 ** identified by pDest->iSDParm.
18896 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
18898 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
18903 ** the side-effects of functions.
18910 ** in register pDest->iSDParm then abandon the rest
18914 ** row of result as the key in table pDest->iSDParm.
18915 ** Apply the affinity pDest->affSdst before storing
18918 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
18924 ** SRT_Coroutine Generate a co-routine that returns a new row of
18926 ** of the co-routine is stored in register pDest->iSDParm
18927 ** and the result row is stored in pDest->nDest registers
18928 ** starting with pDest->iSdst.
18930 ** SRT_Table Store results in temporary table pDest->iSDParm.
18936 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
18937 ** But also use temporary table pDest->iSDParm+1 as
18941 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
18945 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
18947 ** index at pDest->iSDParm+1 hold all prior stores.
18950 ** pDest->iSDParm. If (pDest->iSDParm<0), then the temp
18951 ** table is an intkey table - in this case the first
18953 ** key. If (pDest->iSDParm>0), then the table is an index
18954 ** table. (pDest->iSDParm) is the number of key columns in
18966 #define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue)
18972 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)
19000 ** the code generator needs. We have to keep per-table autoincrement
19019 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
19100 ** The nTableLock and aTableLock variables are only used if the shared-cache
19101 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
19102 ** used to store the set of table-locks required by the statement being
19132 ** of the base register during check-constraint eval */
19143 int nMaxArg; /* Max args passed to user function by sub-program */
19147 TableLock *aTableLock; /* Required table locks for shared-cache mode */
19192 int nHeight; /* Expression tree height of current sub-select */
19204 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
19226 #define PARSE_HDR_SZ (offsetof(Parse,aTempReg)-offsetof(Parse,zErrMsg)) /* Recursive part w/o aColC…
19228 #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
19237 #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
19243 #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)
19249 #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
19273 #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
19277 #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
19281 #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
19316 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
19317 the <column-list> is stored here */
19336 ** that is a part of a trigger-program.
19341 ** the first step of the trigger-program.
19348 ** orconf -> stores the ON CONFLICT algorithm
19349 ** pSelect -> The content to be inserted - either a SELECT statement or
19351 ** zTarget -> Dequoted name of the table to insert into.
19352 ** pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
19353 ** statement, then this stores the column-names to be
19355 ** pUpsert -> The ON CONFLICT clauses for an Upsert
19358 ** zTarget -> Dequoted name of the table to delete from.
19359 ** pWhere -> The WHERE clause of the DELETE statement if one is specified.
19363 ** zTarget -> Dequoted name of the table to update.
19364 ** pWhere -> The WHERE clause of the UPDATE statement if one is specified.
19366 ** pExprList -> A list of the columns to update and the expressions to update
19371 ** pSelect -> The SELECT statement
19374 ** pExprList -> The list of expressions that follow the RETURNING keyword.
19390 TriggerStep *pNext; /* Next in the link-list */
19391 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
19420 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
19424 #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
19450 ** on debug-builds of the CLI using ".testctrl tune ID VALUE". Tuning
19453 ** be used on trunk check-ins. They are a temporary mechanism available
19458 #define SQLITE_NTUNE 6 /* Should be zero for all trunk check-ins */
19460 # define Tuning(X) (sqlite3Config.aTune[(X)-1])
19475 u8 bUseCis; /* Use covering indices for full-scans */
19479 int neverCorrupt; /* Database is always well-formed */
19482 int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
19483 sqlite3_mem_methods m; /* Low-level memory allocation interface */
19484 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
19485 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
19495 int sharedCacheEnabled; /* true if shared-cache mode enabled */
19497 /* The above might be initialized to non-zero. The following need to always
19528 u32 szSorterRef; /* Min size in bytes to use sorter-refs */
19530 /* vvvv--- must be last ---vvv */
19538 ** the assert is only valid on a well-formed database. Instead of:
19550 ** things that are always true for well-formed databases.
19555 ** Context pointer passed down through the tree-walk.
19596 const char *zType; /* Type of the container - used for error messages */
19597 const Token *pName; /* Name of the container - used for error messages */
19624 ** Return code from the parse-tree walking primitives and their
19685 ** data structures on sqlite3DebugPrintf() using a tree-like view.
19702 ** (2) All window functions in a single SELECT form a linked-list
19772 ** Assuming zIn points to the first byte of a UTF-8 character,
19773 ** advance zIn to point to the first byte of the next UTF-8 character.
19784 ** routines that report the line-number on which the error originated
19829 ** The ctype.h header is needed for non-ASCII systems. It is also
19963 # define MAN754 ((((u64)1)<<52)-1)
20103 # define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */
20104 # define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */
20113 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
20377 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
20378 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
20440 ** Routines to read and write variable-length integers. These used to
20655 ** The interface to the LEMON-generated parser
20716 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
20795 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
20797 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
20799 ** provided (enforcement of FK constraints requires the triggers sub-system).
20850 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
20903 ** sqlite3IoTrace is a pointer to a printf-like routine used to
20936 ** passed back to non-lookaside free() routines. Asserts such as the
20937 ** example above are placed on the non-lookaside free() routines to verify
20940 ** All of this is no-op for a production build. It only comes into
20941 ** play when the SQLITE_MEMDEBUG compile-time option is used.
20948 # define sqlite3MemdebugSetType(X,Y) /* no-op */
20992 ** The author disclaims copyright to this source code. In place of
21002 ** all of the platform-specific files (os_*.c) and is #included into those
21014 ** switch. The following code should catch this problem at compile-time.
21028 ** high-performance timing routines.
21035 ** The author disclaims copyright to this source code. In place of
21044 ** This file contains inline asm code for retrieving "high-performance"
21051 ** The following routine only works on pentium-class (or newer) processors.
21053 ** processor and returns that value. This can be used for high-res
21124 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
21148 || sqlite3_io_error_pending-- == 1 ) \
21163 sqlite3_diskfull_pending--; \
21188 ** SQLite source tree at tool/mkctimec.tcl.
21197 ** The author disclaims copyright to this source code. In place of
21206 ** This file implements routines used to report what compile-time options
21209 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */
21213 ** autoconf-based build
21227 ** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
21233 ** An array of names of all compile-time options. This array should
21234 ** be sorted A-Z.
21237 ** only a handful of compile-time options, so most times this array is usually
21275 "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
21279 "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
21281 "COMPILER=gcc-" __VERSION__,
21985 ** The author disclaims copyright to this source code. In place of
21998 /* An array to map all upper-case characters into their corresponding
21999 ** lower-case character.
22001 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
22041 /* All of the upper-to-lower conversion data is above. The following
22058 ** index (here shown as [256-OP_Ne]) would be out-of-bounds and thus
22059 ** be undefined behavior. That's goofy, but the C-standards people thought
22067 SQLITE_PRIVATE const unsigned char *sqlite3aLTb = &sqlite3UpperToLower[256-OP_Ne];
22068 SQLITE_PRIVATE const unsigned char *sqlite3aEQb = &sqlite3UpperToLower[256+6-OP_Ne];
22069 SQLITE_PRIVATE const unsigned char *sqlite3aGTb = &sqlite3UpperToLower[256+12-OP_Ne];
22072 ** The following 256 byte lookup table is used to support SQLites built-in
22085 ** case. i.e. if the character is a lower-case ASCII character.
22086 ** If x is a lower-case ASCII character, then its upper-case equivalent
22087 ** is (x - 0x20). Therefore toupper() can be implemented as:
22094 ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
22096 ** non-ASCII UTF character. Hence the test for whether or not a character is
22105 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
22137 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
22141 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
22142 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
22144 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
22159 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
22160 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
22161 ** that compile-time option is omitted.
22167 # error "Compile-time disabling of covering index scan using the\
22168 -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\
22184 ** before 3.12.0). -1 means always keep the entire statement journal in
22194 ** The default lookaside-configuration, the format "SZ,N". SZ is the
22196 ** and N is the number of slots. The lookaside-configuration can be
22197 ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
22198 ** or at run-time for an individual database connection using
22201 ** With the two-size-lookaside enhancement, less lookaside is required.
22202 ** The default configuration of 1200,40 actually provides 30 1200-byte slots
22203 ** and 93 128-byte slots, which is more lookaside than is available
22204 ** using the older 1200,100 configuration without two-size-lookaside.
22215 /* The default maximum size of an in-memory database created using
22287 ** Hash table for global functions - functions common to all
22289 ** read-only.
22308 ** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
22315 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
22390 ** The author disclaims copyright to this source code. In place of
22408 ** The author disclaims copyright to this source code. In place of
22418 ** source code file "vdbe.c". When that file became too big (over
22472 ** * A b-tree cursor
22473 ** - In the main database or in an ephemeral database
22474 ** - On either an index or a table
22477 ** * A one-row "pseudotable" stored in a single register
22482 i8 iDb; /* Index of cursor database in db->aDb[] */
22491 Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
22541 /* Return true if P is a null-only cursor
22544 ((P)->eCurType==CURTYPE_PSEUDO && (P)->nullRow && (P)->seekResult==0)
22553 ** When a sub-program is executed (OP_Program), a structure of this type
22556 ** values stored in the Vdbe struct. When the sub-program is finished,
22558 ** restoring the state of the VM to as it was before the sub-program
22595 i64 nDbChange; /* Value of db->nChange */
22630 void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
22649 ** UPDATE no-change flag set
22655 ** * MEM_Null|MEM_Cleared Special SQL NULL that compares non-equal
22659 ** length Mem.n. Zero-terminated if
22715 /* Return TRUE if Mem X contains dynamically allocated content - anything
22719 (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
22725 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
22728 ** True if Mem X is a NULL-nochng type.
22731 (((X)->flags&MEM_TypeMask)==(MEM_Null|MEM_Zero) \
22732 && (X)->n==0 && (X)->u.nZero==0)
22743 #define memIsValid(M) ((M)->flags & MEM_AffMask)!=0
22800 int iSelectID; /* The "Select-ID" for this loop */
22805 /* The DblquoteStr object holds the text of a double-quoted
22809 ** list is consulted for each double-quoted identifier to see if the
22857 i64 startTime; /* Time when query started - used for profiling */
22870 bft changeCntOn:1; /* True to update the change-counter */
22874 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
22880 DblquoteStr *pDblStr; /* List of double-quoted string literals */
22887 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
22935 ** set of values on the right-hand side of an IN constraint.
22951 ** single-byte varint.
23106 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
23151 ** we have to locate the state vector at run-time. In the more common
23181 ** The value of N is added to the current status value and the high-water
23185 ** mark is unchanged. N must be non-negative for StatusDown().
23205 wsdStat.nowValue[op] -= N;
23277 p = p->pNext;
23287 u32 nInit = countLookasideSlots(db->lookaside.pInit);
23288 u32 nFree = countLookasideSlots(db->lookaside.pFree);
23290 nInit += countLookasideSlots(db->lookaside.pSmallInit);
23291 nFree += countLookasideSlots(db->lookaside.pSmallFree);
23293 if( pHighwater ) *pHighwater = db->lookaside.nSlot - nInit;
23294 return db->lookaside.nSlot - (nInit+nFree);
23304 int *pHighwater, /* Write high-water mark here */
23305 int resetFlag /* Reset high-water mark if true */
23313 sqlite3_mutex_enter(db->mutex);
23318 LookasideSlot *p = db->lookaside.pFree;
23320 while( p->pNext ) p = p->pNext;
23321 p->pNext = db->lookaside.pInit;
23322 db->lookaside.pInit = db->lookaside.pFree;
23323 db->lookaside.pFree = 0;
23326 p = db->lookaside.pSmallFree;
23328 while( p->pNext ) p = p->pNext;
23329 p->pNext = db->lookaside.pSmallInit;
23330 db->lookaside.pSmallInit = db->lookaside.pSmallFree;
23331 db->lookaside.pSmallFree = 0;
23344 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
23345 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
23347 *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
23349 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
23364 for(i=0; i<db->nDb; i++){
23365 Btree *pBt = db->aDb[i].pBt;
23391 db->pnBytesFreed = &nByte;
23392 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
23393 db->lookaside.pEnd = db->lookaside.pStart;
23394 for(i=0; i<db->nDb; i++){
23395 Schema *pSchema = db->aDb[i].pSchema;
23400 pSchema->tblHash.count
23401 + pSchema->trigHash.count
23402 + pSchema->idxHash.count
23403 + pSchema->fkeyHash.count
23405 nByte += sqlite3_msize(pSchema->tblHash.ht);
23406 nByte += sqlite3_msize(pSchema->trigHash.ht);
23407 nByte += sqlite3_msize(pSchema->idxHash.ht);
23408 nByte += sqlite3_msize(pSchema->fkeyHash.ht);
23410 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
23413 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
23418 db->pnBytesFreed = 0;
23419 db->lookaside.pEnd = db->lookaside.pTrueEnd;
23436 db->pnBytesFreed = &nByte;
23437 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
23438 db->lookaside.pEnd = db->lookaside.pStart;
23439 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pVNext){
23442 db->lookaside.pEnd = db->lookaside.pTrueEnd;
23443 db->pnBytesFreed = 0;
23445 *pHighwater = 0; /* IMP: R-64479-57858 */
23467 for(i=0; i<db->nDb; i++){
23468 if( db->aDb[i].pBt ){
23469 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
23473 *pHighwater = 0; /* IMP: R-42420-56072 */
23474 /* IMP: R-54100-20147 */
23475 /* IMP: R-29431-39229 */
23480 /* Set *pCurrent to non-zero if there are unresolved deferred foreign
23485 *pHighwater = 0; /* IMP: R-11967-56545 */
23486 *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
23494 sqlite3_mutex_leave(db->mutex);
23503 ** The author disclaims copyright to this source code. In place of
23514 ** There is only one exported symbol in this file - the function
23523 ** 1970-01-01 00:00:00 is JD 2440587.5
23524 ** 2000-01-01 00:00:00 is JD 2451544.5
23526 ** This implementation requires years to be expressed as a 4-digit number
23527 ** which means that only dates between 0000-01-01 and 9999-12-31 can
23533 ** use the julian calendar for dates prior to 1582-10-15 and for some
23541 ** ISBN 0-943396-61-1
23542 ** Willmann-Bell, Inc
23588 ** of a four-character format specifiers ABCD is:
23602 ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
23603 ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
23604 ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
23605 ** the 2-digit day which is the last integer in the set.
23618 char N = zFormat[0] - '0';
23619 char min = zFormat[1] - '0';
23624 max = aMx[zFormat[2] - 'a'];
23627 while( N-- ){
23631 val = val*10 + *zDate - '0';
23648 ** Parse a timezone extension on the end of a date-time.
23651 ** (+/-)HH:MM
23658 ** of change in p->tz and return 0. If a parser error occurs,
23659 ** return non-zero.
23668 p->tz = 0;
23670 if( c=='-' ){
23671 sgn = -1;
23685 p->tz = sgn*(nMn + nHr*60);
23688 p->tzSet = 1;
23716 ms = ms*10.0 + *zDate - '0';
23725 p->validJD = 0;
23726 p->rawS = 0;
23727 p->validHMS = 1;
23728 p->h = h;
23729 p->m = m;
23730 p->s = s + ms;
23732 p->validTZ = (p->tz!=0)?1:0;
23741 p->isError = 1;
23745 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
23746 ** that the YYYY-MM-DD is according to the Gregorian calendar.
23753 if( p->validJD ) return;
23754 if( p->validYMD ){
23755 Y = p->Y;
23756 M = p->M;
23757 D = p->D;
23759 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
23763 if( Y<-4713 || Y>9999 || p->rawS ){
23768 Y--;
23772 B = 2 - A + (A/4);
23775 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
23776 p->validJD = 1;
23777 if( p->validHMS ){
23778 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000 + 0.5);
23779 if( p->validTZ ){
23780 p->iJD -= p->tz*60000;
23781 p->validYMD = 0;
23782 p->validHMS = 0;
23783 p->validTZ = 0;
23791 ** YYYY-MM-DD HH:MM:SS.FFF
23792 ** YYYY-MM-DD HH:MM:SS
23793 ** YYYY-MM-DD HH:MM
23794 ** YYYY-MM-DD
23797 ** on success and 1 if the input string is not a well-formed
23803 if( zDate[0]=='-' ){
23809 if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
23817 p->validHMS = 0;
23821 p->validJD = 0;
23822 p->validYMD = 1;
23823 p->Y = neg ? -Y : Y;
23824 p->M = M;
23825 p->D = D;
23826 if( p->validTZ ){
23838 p->iJD = sqlite3StmtCurrentTime(context);
23839 if( p->iJD>0 ){
23840 p->validJD = 1;
23851 ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
23854 p->s = r;
23855 p->rawS = 1;
23857 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
23858 p->validJD = 1;
23868 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
23872 ** In the first form, the +/-HH:MM is always optional. The fractional
23897 /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
23920 if( p->validYMD ) return;
23921 if( !p->validJD ){
23922 p->Y = 2000;
23923 p->M = 1;
23924 p->D = 1;
23925 }else if( !validJulianDay(p->iJD) ){
23929 Z = (int)((p->iJD + 43200000)/86400000);
23930 A = (int)((Z - 1867216.25)/36524.25);
23931 A = Z + 1 + A - (A/4);
23933 C = (int)((B - 122.1)/365.25);
23935 E = (int)((B-D)/30.6001);
23937 p->D = B - D - X1;
23938 p->M = E<14 ? E-1 : E-13;
23939 p->Y = p->M>2 ? C - 4716 : C - 4715;
23941 p->validYMD = 1;
23949 if( p->validHMS ) return;
23951 s = (int)((p->iJD + 43200000) % 86400000);
23952 p->s = s/1000.0;
23953 s = (int)p->s;
23954 p->s -= s;
23955 p->h = s/3600;
23956 s -= p->h*3600;
23957 p->m = s/60;
23958 p->s += s - p->m*60;
23959 p->rawS = 0;
23960 p->validHMS = 1;
23975 p->validYMD = 0;
23976 p->validHMS = 0;
23977 p->validTZ = 0;
23987 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
24001 ** using whatever operating-system specific localtime facility that
24003 ** non-zero on any kind of error.
24005 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is non-zero then this
24008 ** invoked in place of the OS-defined localtime() function.
24010 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
24076 if( p->iJD<2108667600*(i64)100000 /* 1970-01-01 */
24077 || p->iJD>2130141456*(i64)100000 /* 2038-01-18 */
24079 /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
24086 iYearDiff = (2000 + x.Y%4) - x.Y;
24090 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
24093 t = (time_t)(p->iJD/1000 - 21086676*(i64)10000);
24096 sqlite3_result_error(pCtx, "local time unavailable", -1);
24099 p->Y = sLocal.tm_year + 1900 - iYearDiff;
24100 p->M = sLocal.tm_mon + 1;
24101 p->D = sLocal.tm_mday;
24102 p->h = sLocal.tm_hour;
24103 p->m = sLocal.tm_min;
24104 p->s = sLocal.tm_sec + (p->iJD%1000)*0.001;
24105 p->validYMD = 1;
24106 p->validHMS = 1;
24107 p->validJD = 0;
24108 p->rawS = 0;
24109 p->validTZ = 0;
24110 p->isError = 0;
24120 ** Where NNN is an arbitrary floating-point number and "days" can be one
24138 ** Process a modifier to a date-time stamp. The modifiers are
24179 if( idx>1 ) return 1; /* IMP: R-33611-57934 */
24180 if( !p->rawS || p->validJD ){
24182 p->rawS = 0;
24183 }else if( p->s>=-21086676*(i64)10000 /* -4713-11-24 12:00:00 */
24184 && p->s<=(25340230*(i64)10000)+799 /* 9999-12-31 23:59:59 */
24186 r = p->s*1000.0 + 210866760000000.0;
24188 p->iJD = (sqlite3_int64)(r + 0.5);
24189 p->validJD = 1;
24190 p->rawS = 0;
24200 ** Always interpret the prior number as a julian-day value. If this
24206 if( idx>1 ) return 1; /* IMP: R-31176-64601 */
24207 if( p->validJD && p->rawS ){
24209 p->rawS = 0;
24231 ** Treat the current value of p->s as the number of
24234 if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){
24235 if( idx>1 ) return 1; /* IMP: R-49255-55373 */
24236 r = p->s*1000.0 + 210866760000000.0;
24239 p->iJD = (sqlite3_int64)(r + 0.5);
24240 p->validJD = 1;
24241 p->rawS = 0;
24247 if( p->tzSet==0 ){
24254 iGuess = iOrigJD = p->iJD;
24259 iGuess -= iErr;
24265 iErr = new.iJD - iOrigJD;
24268 p->iJD = iGuess;
24269 p->validJD = 1;
24270 p->tzSet = 1;
24283 ** date is already on the appropriate weekday, this is a no-op.
24290 p->validTZ = 0;
24291 p->validJD = 0;
24293 Z = ((p->iJD + 129600000)/86400000) % 7;
24294 if( Z>n ) Z -= 7;
24295 p->iJD += (n - Z)*86400000;
24309 if( !p->validJD && !p->validYMD && !p->validHMS ) break;
24312 p->validHMS = 1;
24313 p->h = p->m = 0;
24314 p->s = 0.0;
24315 p->rawS = 0;
24316 p->validTZ = 0;
24317 p->validJD = 0;
24319 p->D = 1;
24322 p->M = 1;
24323 p->D = 1;
24331 case '-':
24350 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
24362 tx.iJD -= 43200000;
24364 tx.iJD -= day*86400000;
24365 if( z[0]=='-' ) tx.iJD = -tx.iJD;
24368 p->iJD += tx.iJD;
24379 if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--;
24382 rRounder = r<0 ? -0.5 : +0.5;
24386 && r>-aXformType[i].rLimit && r<aXformType[i].rLimit
24393 p->M += (int)r;
24394 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
24395 p->Y += x;
24396 p->M -= x*12;
24397 p->validJD = 0;
24398 r -= (int)r;
24405 p->Y += y;
24406 p->validJD = 0;
24407 r -= (int)r;
24412 p->iJD += (sqlite3_int64)(r*1000.0*aXformType[i].rXform + rRounder);
24428 ** Process time function arguments. argv[0] is a date-time stamp.
24465 if( p->isError || !validJulianDay(p->iJD) ) return 1;
24496 ** the unix epoch of 1970-01-01 00:00:00 GMT.
24506 sqlite3_result_int64(context, x.iJD/1000 - 21086676*(i64)10000);
24513 ** Return YYYY-MM-DD HH:MM:SS
24526 if( Y<0 ) Y = -Y;
24531 zBuf[5] = '-';
24534 zBuf[8] = '-';
24549 zBuf[0] = '-';
24589 ** Return YYYY-MM-DD
24602 if( Y<0 ) Y = -Y;
24607 zBuf[5] = '-';
24610 zBuf[8] = '-';
24615 zBuf[0] = '-';
24630 ** %H hour 00-24
24631 ** %j day of year 000-366
24633 ** %m month 01-12
24634 ** %M minute 00-59
24635 ** %s seconds since 1970-01-01
24636 ** %S seconds 00-59
24637 ** %w day of week 0-6 sunday==0
24638 ** %W week of year 00-53
24639 ** %Y year 0000-9999
24656 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
24658 sqlite3StrAccumInit(&sRes, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
24664 if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
24690 nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
24694 sqlite3_str_appendf(&sRes,"%02d",(nDay+7-wd)/7);
24713 i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000);
24740 if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j));
24789 ** If the library is compiled to omit the full-scale date and time
24795 ** This function uses the C-library functions time(), gmtime()
24797 ** as the user-data for the function.
24816 t = iT/1000 - 10000*(sqlite3_int64)21086676;
24827 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
24840 PURE_DATE(julianday, -1, 0, 0, juliandayFunc ),
24841 PURE_DATE(unixepoch, -1, 0, 0, unixepochFunc ),
24842 PURE_DATE(date, -1, 0, 0, dateFunc ),
24843 PURE_DATE(time, -1, 0, 0, timeFunc ),
24844 PURE_DATE(datetime, -1, 0, 0, datetimeFunc ),
24845 PURE_DATE(strftime, -1, 0, 0, strftimeFunc ),
24851 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
24852 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
24863 ** The author disclaims copyright to this source code. In place of
24884 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
24902 ** from within OsOpen()), but some third-party implementations may.
24942 if( pId->pMethods ){
24943 pId->pMethods->xClose(pId);
24944 pId->pMethods = 0;
24949 return id->pMethods->xRead(id, pBuf, amt, offset);
24953 return id->pMethods->xWrite(id, pBuf, amt, offset);
24956 return id->pMethods->xTruncate(id, size);
24960 return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK;
24964 return id->pMethods->xFileSize(id, pSize);
24969 return id->pMethods->xLock(id, lockType);
24973 return id->pMethods->xUnlock(id, lockType);
24977 return id->pMethods->xCheckReservedLock(id, pResOut);
24989 if( id->pMethods==0 ) return SQLITE_NOTFOUND;
24999 ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
25007 ** The CKPT_DONE and CKPT_START file-controls are write-only signals
25014 return id->pMethods->xFileControl(id, op, pArg);
25017 if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg);
25021 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
25025 if( NEVER(id->pMethods==0) ) return 0;
25026 return id->pMethods->xDeviceCharacteristics(id);
25030 return id->pMethods->xShmLock(id, offset, n, flags);
25033 id->pMethods->xShmBarrier(id);
25036 return id->pMethods->xShmUnmap(id, deleteFlag);
25046 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
25054 return id->pMethods->xFetch(id, iOff, iAmt, pp);
25057 return id->pMethods->xUnfetch(id, iOff, p);
25060 /* No-op stubs to use when memory-mapped I/O is disabled */
25088 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut);
25089 assert( rc==SQLITE_OK || pFile->pMethods==0 );
25095 return pVfs->xDelete!=0 ? pVfs->xDelete(pVfs, zPath, dirSync) : SQLITE_OK;
25104 return pVfs->xAccess(pVfs, zPath, flags, pResOut);
25114 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
25119 assert( strlen(zPath)<=SQLITE_MAX_PATHLEN ); /* tag-20210611-1 */
25120 return pVfs->xDlOpen(pVfs, zPath);
25123 pVfs->xDlError(pVfs, nByte, zBufOut);
25126 return pVfs->xDlSym(pVfs, pHdle, zSym);
25129 pVfs->xDlClose(pVfs, pHandle);
25139 return pVfs->xRandomness(pVfs, nByte, zBufOut);
25144 return pVfs->xSleep(pVfs, nMicro);
25147 return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
25151 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
25157 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
25158 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
25161 rc = pVfs->xCurrentTime(pVfs, &r);
25176 pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
25234 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
25236 if( strcmp(zVfs, pVfs->zName)==0 ) break;
25248 /* No-op */
25250 vfsList = pVfs->pNext;
25253 while( p->pNext && p->pNext!=pVfs ){
25254 p = p->pNext;
25256 if( p->pNext==pVfs ){
25257 p->pNext = pVfs->pNext;
25281 pVfs->pNext = vfsList;
25284 pVfs->pNext = vfsList->pNext;
25285 vfsList->pNext = pVfs;
25313 ** The author disclaims copyright to this source code. In place of
25327 ** Most malloc failures are non-benign. After they occur, SQLite
25351 ** we have to locate the state vector at run-time. In the more common
25381 ** indicates that subsequent malloc failures are non-benign.
25403 ** The author disclaims copyright to this source code. In place of
25412 ** This file contains a no-op memory allocation drivers for use when
25422 ** used when no other memory allocator is specified using compile-time
25428 ** No-op versions of all memory allocation routines
25441 ** Populate the low-level memory allocation function pointers in
25465 ** The author disclaims copyright to this source code. In place of
25474 ** This file contains low-level memory allocation drivers for when
25475 ** SQLite will use the standard C-library malloc/realloc/free interface
25478 ** This file contains implementations of the low-level memory allocation
25486 ** C-preprocessor macro summary:
25493 ** a different name, using a separate -D
25509 ** used when no other memory allocator is specified using compile-time
25529 (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
25534 ** Use standard C library malloc and free on non-Apple systems.
25551 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
25585 ** For this low-level routine, we are guaranteed that nByte>0 because
25619 ** For this low-level routine, we already know that pPrior!=0 since
25621 ** by higher-level routines.
25629 p--;
25646 p--;
25655 ** For this low-level interface, we know that pPrior!=0. Cases where
25656 ** pPrior==0 while have been intercepted by higher-level routine and
25658 ** cases where nByte<=0 will have been intercepted by higher-level
25674 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
25675 p--;
25735 ** Populate the low-level memory allocation function pointers in
25759 ** The author disclaims copyright to this source code. In place of
25768 ** This file contains low-level memory allocation drivers for when
25769 ** SQLite will use the standard C-library malloc/realloc/free interface
25774 ** This file contains implementations of the low-level memory allocation
25800 ** ------------------------------------------------------------------------
25802 ** ------------------------------------------------------------------------
25886 if( i>NCSIZE-1 ){
25887 i = NCSIZE - 1;
25896 mem.nCurrent[i]--;
25914 p--;
25915 assert( p->iForeGuard==(int)FOREGUARD );
25916 nReserve = ROUND8(p->iSize);
25924 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
25937 return (int)pHdr->iSize;
25970 ** Fill a buffer with pseudo-random bytes. This is used to preset
25979 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
25984 nByte -= 4;
25986 while( nByte-- > 0 ){
25987 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
26015 pHdr->pNext = 0;
26016 pHdr->pPrev = mem.pLast;
26018 mem.pLast->pNext = pHdr;
26023 pHdr->iForeGuard = FOREGUARD;
26024 pHdr->eType = MEMTYPE_HEAP;
26025 pHdr->nBacktraceSlots = mem.nBacktrace;
26026 pHdr->nTitle = mem.nTitle;
26029 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
26030 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
26033 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
26036 pHdr->nBacktrace = 0;
26041 pHdr->iSize = nByte;
26046 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
26064 pBt -= pHdr->nBacktraceSlots;
26066 if( pHdr->pPrev ){
26067 assert( pHdr->pPrev->pNext==pHdr );
26068 pHdr->pPrev->pNext = pHdr->pNext;
26071 mem.pFirst = pHdr->pNext;
26073 if( pHdr->pNext ){
26074 assert( pHdr->pNext->pPrev==pHdr );
26075 pHdr->pNext->pPrev = pHdr->pPrev;
26078 mem.pLast = pHdr->pPrev;
26081 z -= pHdr->nTitle;
26082 adjustStats((int)pHdr->iSize, -1);
26083 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
26084 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
26102 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
26106 memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
26107 if( nByte>pOldHdr->iSize ){
26108 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
26116 ** Populate the low-level memory allocation function pointers in
26140 assert( pHdr->iForeGuard==FOREGUARD );
26141 pHdr->eType = eType;
26159 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
26160 if( (pHdr->eType&eType)==0 ){
26181 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
26182 if( (pHdr->eType&eType)!=0 ){
26211 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
26220 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
26222 pBt -= pHdr->nBacktraceSlots;
26223 mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
26242 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
26244 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
26246 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
26247 if( pHdr->nBacktrace ){
26250 pBt -= pHdr->nBacktraceSlots;
26251 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
26256 for(i=0; i<NCSIZE-1; i++){
26262 if( mem.nAlloc[NCSIZE-1] ){
26264 NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
26265 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
26290 ** The author disclaims copyright to this source code. In place of
26317 ** mean that the library will use a memory-pool by default, just that
26358 ** two fields form a double-linked list of chunks of related sizes.
26395 ** True if we are evaluating an out-of-memory callback.
26423 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
26456 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
26458 size = mem3.aPool[i-1].u.hdr.size4x/4;
26459 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
26462 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
26491 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
26492 size = mem3.aPool[i-1].u.hdr.size4x/4;
26493 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
26496 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
26535 ** size parameters for check-out and return a pointer to the
26542 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
26543 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
26544 x = mem3.aPool[i-1].u.hdr.size4x;
26545 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
26546 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
26547 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
26559 if( nBlock>=mem3.szKeyBlk-1 ){
26569 newi = mem3.iKeyBlk + mem3.szKeyBlk - nBlock;
26571 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = nBlock;
26572 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x |= 2;
26573 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
26574 mem3.szKeyBlk -= nBlock;
26575 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szKeyBlk;
26576 x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
26577 mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
26607 size = mem3.aPool[i-1].u.hdr.size4x;
26611 assert( i > mem3.aPool[i-1].u.hdr.prevSize );
26612 prev = i - mem3.aPool[i-1].u.hdr.prevSize;
26617 size = i + size/4 - prev;
26618 x = mem3.aPool[prev-1].u.hdr.size4x & 2;
26619 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
26620 mem3.aPool[prev+size-1].u.hdr.prevSize = size;
26660 i = mem3.aiSmall[nBlock-2];
26662 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
26668 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
26701 for(i=0; i<MX_SMALL-1; i++){
26728 i = p - mem3.aPool;
26729 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
26730 size = mem3.aPool[i-1].u.hdr.size4x/4;
26732 mem3.aPool[i-1].u.hdr.size4x &= ~1;
26733 mem3.aPool[i+size-1].u.hdr.prevSize = size;
26734 mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
26739 while( (mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x&2)==0 ){
26740 size = mem3.aPool[mem3.iKeyBlk-1].u.hdr.prevSize;
26741 mem3.iKeyBlk -= size;
26744 x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
26745 mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
26746 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk;
26748 x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2;
26749 while( (mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x&1)==0 ){
26751 mem3.szKeyBlk += mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x/4;
26752 mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x;
26753 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk;
26760 ** size returned omits the 8-byte header overhead. This only
26767 assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
26768 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
26778 return ((n+11)&~7) - 4;
26818 if( nBytes<=nOld && nBytes>=nOld-128 ){
26847 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
26893 size = mem3.aPool[i-1].u.hdr.size4x;
26899 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
26904 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
26910 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
26912 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
26916 for(i=0; i<MX_SMALL-1; i++){
26921 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
26930 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
26935 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szKeyBlk*8);
26936 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnKeyBlk*8);
26952 ** Populate the low-level memory allocation function pointers in
26980 ** The author disclaims copyright to this source code. In place of
27013 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
27022 ** N >= M*(1 + log2(n)/2) - n + 1
27051 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
27086 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
27117 ** structures, return a pointer to the idx-th such link.
27131 next = MEM5LINK(i)->next;
27132 prev = MEM5LINK(i)->prev;
27136 MEM5LINK(prev)->next = next;
27139 MEM5LINK(next)->prev = prev;
27154 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
27155 MEM5LINK(i)->prev = -1;
27158 MEM5LINK(x)->prev = i;
27180 i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
27235 iBin--;
27246 mem5.totalExcess += iFullSz - nByte;
27273 iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
27275 /* Check that the pointer pOld points to a valid, non-free block. */
27277 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
27282 assert( iBlock+size-1<(u32)mem5.nBlock );
27285 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
27290 mem5.currentCount--;
27291 mem5.currentOut -= size*mem5.szAtom;
27300 iBuddy = iBlock - size;
27362 ** memsys5Round(). Hence nBytes is always a non-negative power
27371 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
27394 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
27416 ** Examples: memsys5Log(1) -> 0
27417 ** memsys5Log(2) -> 1
27418 ** memsys5Log(4) -> 2
27419 ** memsys5Log(5) -> 3
27420 ** memsys5Log(8) -> 3
27421 ** memsys5Log(9) -> 4
27425 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
27450 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
27468 mem5.aiFreelist[ii] = -1;
27472 for(ii=LOGMAX; ii>=0; ii--){
27522 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
27568 ** The author disclaims copyright to this source code. In place of
27613 ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
27624 #define SQLITE_MUTEX_WARNONCONTENTION (-1)
27634 return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex);
27637 return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex);
27668 p->iType = iType;
27671 if( iType-2>=ArraySize(staticMutexes) ){
27676 p = &staticMutexes[iType-2];
27679 if( p->mutex==0 ){
27680 p->mutex = pGlobalMutexMethods->xMutexAlloc(iType);
27681 if( p->mutex==0 ){
27701 if( ((CheckMutex*)p)->iType<2 )
27705 pGlobalMutexMethods->xMutexFree(pCheck->mutex);
27720 if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){
27721 if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){
27725 "illegal multi-threaded access to database connection"
27728 pGlobalMutexMethods->xMutexEnter(pCheck->mutex);
27736 return pGlobalMutexMethods->xMutexTry(pCheck->mutex);
27744 pGlobalMutexMethods->xMutexLeave(pCheck->mutex);
27774 assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE );
27775 pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION;
27803 pTo->xMutexInit = pFrom->xMutexInit;
27804 pTo->xMutexEnd = pFrom->xMutexEnd;
27805 pTo->xMutexFree = pFrom->xMutexFree;
27806 pTo->xMutexEnter = pFrom->xMutexEnter;
27807 pTo->xMutexTry = pFrom->xMutexTry;
27808 pTo->xMutexLeave = pFrom->xMutexLeave;
27809 pTo->xMutexHeld = pFrom->xMutexHeld;
27810 pTo->xMutexNotheld = pFrom->xMutexNotheld;
27812 pTo->xMutexAlloc = pFrom->xMutexAlloc;
27901 ** this function is a no-op.
27932 ** The author disclaims copyright to this source code. In place of
27945 ** here are place-holders. Applications can substitute working
27946 ** mutex routines at start-time using the
28019 return p==0 || p->cnt>0;
28023 return p==0 || p->cnt==0;
28038 static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
28045 pNew->id = id;
28046 pNew->cnt = 0;
28052 if( id-2<0 || id-2>=ArraySize(aStatic) ){
28057 pNew = &aStatic[id-2];
28058 pNew->id = id;
28070 assert( p->cnt==0 );
28071 if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
28093 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
28094 p->cnt++;
28098 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
28099 p->cnt++;
28112 p->cnt--;
28113 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
28135 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
28136 ** is used regardless of the run-time threadsafety setting.
28150 ** The author disclaims copyright to this source code. In place of
28176 ** home-grown mutexes. Encapsulate these conditions into a single #define.
28219 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
28225 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
28228 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
28281 ** cases where it really needs one. If a faster non-recursive mutex
28322 pthread_mutex_init(&p->mutex, 0);
28328 pthread_mutex_init(&p->mutex, &recursiveAttr);
28332 p->id = SQLITE_MUTEX_RECURSIVE;
28340 pthread_mutex_init(&p->mutex, 0);
28342 p->id = SQLITE_MUTEX_FAST;
28349 if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
28354 p = &staticMutexes[iType-2];
28359 assert( p==0 || p->id==iType );
28371 assert( p->nRef==0 );
28373 if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
28376 pthread_mutex_destroy(&p->mutex);
28398 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
28403 ** is atomic - that it cannot be deceived into thinking self
28404 ** and p->owner are equal if p->owner changes between two values
28406 ** This implementation also assumes a coherent cache - that
28413 if( p->nRef>0 && pthread_equal(p->owner, self) ){
28414 p->nRef++;
28416 pthread_mutex_lock(&p->mutex);
28417 assert( p->nRef==0 );
28418 p->owner = self;
28419 p->nRef = 1;
28423 /* Use the built-in recursive mutexes if they are available.
28425 pthread_mutex_lock(&p->mutex);
28427 assert( p->nRef>0 || p->owner==0 );
28428 p->owner = pthread_self();
28429 p->nRef++;
28434 if( p->trace ){
28435 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
28441 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
28446 ** is atomic - that it cannot be deceived into thinking self
28447 ** and p->owner are equal if p->owner changes between two values
28449 ** This implementation also assumes a coherent cache - that
28456 if( p->nRef>0 && pthread_equal(p->owner, self) ){
28457 p->nRef++;
28459 }else if( pthread_mutex_trylock(&p->mutex)==0 ){
28460 assert( p->nRef==0 );
28461 p->owner = self;
28462 p->nRef = 1;
28469 /* Use the built-in recursive mutexes if they are available.
28471 if( pthread_mutex_trylock(&p->mutex)==0 ){
28473 p->owner = pthread_self();
28474 p->nRef++;
28483 if( rc==SQLITE_OK && p->trace ){
28484 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
28499 p->nRef--;
28500 if( p->nRef==0 ) p->owner = 0;
28502 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
28505 if( p->nRef==0 ){
28506 pthread_mutex_unlock(&p->mutex);
28509 pthread_mutex_unlock(&p->mutex);
28513 if( p->trace ){
28514 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
28547 ** The author disclaims copyright to this source code. In place of
28573 ** The author disclaims copyright to this source code. In place of
28619 ** Determine if we are dealing with Windows CE - which has a much reduced
28647 ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
28702 return p->nRef!=0 && p->owner==GetCurrentThreadId();
28706 return p->nRef==0 || p->owner!=tid;
28751 static int winMutex_isNt = -1; /* <0 means "need to query" */
28829 ** cases where it really needs one. If a faster non-recursive mutex
28855 p->id = iType;
28858 p->trace = 1;
28862 InitializeCriticalSectionEx(&p->mutex, 0, 0);
28864 InitializeCriticalSection(&p->mutex);
28871 if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
28876 p = &winMutex_staticMutexes[iType-2];
28879 InterlockedCompareExchange(&p->trace, 1, 0);
28885 assert( p==0 || p->id==iType );
28897 assert( p->nRef==0 && p->owner==0 );
28898 if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
28899 DeleteCriticalSection(&p->mutex);
28925 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
28930 EnterCriticalSection(&p->mutex);
28932 assert( p->nRef>0 || p->owner==0 );
28933 p->owner = tid;
28934 p->nRef++;
28935 if( p->trace ){
28936 OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
28937 tid, p->id, p, p->trace, p->nRef));
28948 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
28962 assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
28967 if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
28969 p->owner = tid;
28970 p->nRef++;
28978 if( p->trace ){
28979 OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
28980 tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
28998 assert( p->nRef>0 );
28999 assert( p->owner==tid );
29000 p->nRef--;
29001 if( p->nRef==0 ) p->owner = 0;
29002 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
29005 LeaveCriticalSection(&p->mutex);
29007 if( p->trace ){
29008 OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n",
29009 tid, p->id, p, p->trace, p->nRef));
29041 ** The author disclaims copyright to this source code. In place of
29056 ** Attempt to release up to n bytes of non-essential memory currently
29057 ** held by SQLite. An example of non-essential memory is memory used to
29064 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
29065 ** is a no-op returning zero if SQLite is not compiled with
29107 ** no-op.
29122 ** Set the soft heap-size limit for the library. An argument of
29123 ** zero disables the limit. A negative argument is a no-op used to
29138 if( rc ) return -1;
29153 excess = sqlite3_memory_used() - n;
29163 ** Set the hard heap-size limit for the library. An argument of zero
29164 ** disables the hard heap limit. A negative argument is a no-op used
29178 if( rc ) return -1;
29213 ** Return true if the heap is currently under memory pressure - in other
29271 /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal
29281 if( nUsed >= mem0.alarmThreshold - nFull ){
29286 if( nUsed >= mem0.hardLimit - nFull ){
29317 ** This provides a 256-byte safety margin for defense against 32-bit
29346 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
29373 return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pTrueEnd);
29389 return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL;
29391 return db->lookaside.szTrue;
29406 if( ((uptr)p)<(uptr)(db->lookaside.pTrueEnd) ){
29408 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
29409 assert( sqlite3_mutex_held(db->mutex) );
29413 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
29414 assert( sqlite3_mutex_held(db->mutex) );
29415 return db->lookaside.szTrue;
29431 if( p==0 ) return; /* IMP: R-49053-54554 */
29447 ** *db->pnBytesFreed.
29450 *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
29455 ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
29456 ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
29459 assert( db==0 || sqlite3_mutex_held(db->mutex) );
29462 if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
29464 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
29466 assert( db->pnBytesFreed==0 );
29470 pBuf->pNext = db->lookaside.pSmallFree;
29471 db->lookaside.pSmallFree = pBuf;
29475 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
29477 assert( db->pnBytesFreed==0 );
29479 memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */
29481 pBuf->pNext = db->lookaside.pFree;
29482 db->lookaside.pFree = pBuf;
29486 if( db->pnBytesFreed ){
29499 assert( sqlite3_mutex_held(db->mutex) );
29501 if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){
29503 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){
29505 assert( db->pnBytesFreed==0 );
29509 pBuf->pNext = db->lookaside.pSmallFree;
29510 db->lookaside.pSmallFree = pBuf;
29514 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){
29516 assert( db->pnBytesFreed==0 );
29518 memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */
29520 pBuf->pNext = db->lookaside.pFree;
29521 db->lookaside.pFree = pBuf;
29525 if( db->pnBytesFreed ){
29535 assert( db==0 || sqlite3_mutex_held(db->mutex) );
29548 return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
29551 sqlite3_free(pOld); /* IMP: R-26507-47431 */
29559 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
29569 nDiff = nNew - nOld;
29571 mem0.alarmThreshold-nDiff ){
29573 if( mem0.hardLimit>0 && nUsed >= mem0.hardLimit - nDiff ){
29587 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
29593 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
29605 if( n<0 ) n = 0; /* IMP: R-26507-47431 */
29649 (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
29658 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
29686 assert( sqlite3_mutex_held(db->mutex) );
29687 assert( db->pnBytesFreed==0 );
29688 if( n>db->lookaside.sz ){
29689 if( !db->lookaside.bDisable ){
29690 db->lookaside.anStat[1]++;
29691 }else if( db->mallocFailed ){
29698 if( (pBuf = db->lookaside.pSmallFree)!=0 ){
29699 db->lookaside.pSmallFree = pBuf->pNext;
29700 db->lookaside.anStat[0]++;
29702 }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){
29703 db->lookaside.pSmallInit = pBuf->pNext;
29704 db->lookaside.anStat[0]++;
29709 if( (pBuf = db->lookaside.pFree)!=0 ){
29710 db->lookaside.pFree = pBuf->pNext;
29711 db->lookaside.anStat[0]++;
29713 }else if( (pBuf = db->lookaside.pInit)!=0 ){
29714 db->lookaside.pInit = pBuf->pNext;
29715 db->lookaside.anStat[0]++;
29718 db->lookaside.anStat[2]++;
29722 assert( sqlite3_mutex_held(db->mutex) );
29723 assert( db->pnBytesFreed==0 );
29724 if( db->mallocFailed ){
29741 assert( sqlite3_mutex_held(db->mutex) );
29742 if( ((uptr)p)<(uptr)db->lookaside.pEnd ){
29744 if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){
29748 if( ((uptr)p)>=(uptr)db->lookaside.pStart ){
29749 if( n<=db->lookaside.szTrue ) return p;
29758 if( db->mallocFailed==0 ){
29774 (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
29834 n = (int)(zEnd - zStart);
29835 while( ALWAYS(n>0) && sqlite3Isspace(zStart[n-1]) ) n--;
29849 ** Call this routine to record the fact that an OOM (out-of-memory) error
29850 ** has happened. This routine will set db->mallocFailed, and also
29862 if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
29863 db->mallocFailed = 1;
29864 if( db->nVdbeExec>0 ){
29865 AtomicStore(&db->u1.isInterrupted, 1);
29868 if( db->pParse ){
29870 sqlite3ErrorMsg(db->pParse, "out of memory");
29871 db->pParse->rc = SQLITE_NOMEM_BKPT;
29872 for(pParse=db->pParse->pOuterParse; pParse; pParse = pParse->pOuterParse){
29873 pParse->nErr++;
29874 pParse->rc = SQLITE_NOMEM;
29883 ** db->mallocFailed flag as necessary.
29889 if( db->mallocFailed && db->nVdbeExec==0 ){
29890 db->mallocFailed = 0;
29891 AtomicStore(&db->u1.isInterrupted, 0);
29892 assert( db->lookaside.bDisable>0 );
29901 if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
29906 return rc & db->errMask;
29918 ** If an OOM as occurred, then the connection error-code (the value
29923 ** Otherwise the read (and possible write) of db->mallocFailed
29927 assert( sqlite3_mutex_held(db->mutex) );
29928 if( db->mallocFailed || rc ){
29931 return rc & db->errMask;
29942 ** This file contains code for a set of "printf"-like routines. These
29953 #define etRADIX 0 /* non-decimal integer types. %x %o */
29969 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
29970 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
29977 ** An "etByte" is an 8-bit unsigned value.
30006 static const char aPrefix[] = "-x0\000X0";
30045 5.0e-01, 5.0e-02, 5.0e-03, 5.0e-04, 5.0e-05,
30046 5.0e-06, 5.0e-07, 5.0e-08, 5.0e-09, 5.0e-10,
30064 ** 16 (the number of significant digits in a 64-bit float) '0' is
30071 (*cnt)--;
30075 *val = (*val - d)*10.0;
30085 p->accError = eError;
30086 if( p->mxAlloc ) sqlite3_str_reset(p);
30087 if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError);
30094 if( p->nArg<=p->nUsed ) return 0;
30095 return sqlite3_value_int64(p->apArg[p->nUsed++]);
30098 if( p->nArg<=p->nUsed ) return 0.0;
30099 return sqlite3_value_double(p->apArg[p->nUsed++]);
30102 if( p->nArg<=p->nUsed ) return 0;
30103 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
30117 if( pAccum->accError ) return 0;
30118 if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){
30122 z = sqlite3DbMallocRaw(pAccum->db, n);
30139 ** Hard limit on the precision of floating-point conversions.
30159 etByte flag_leftjustify; /* True if "-" flag is present */
30169 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
30189 assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
30192 if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){
30206 sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt));
30219 precision = -1;
30222 case '-': flag_leftjustify = 1; break;
30242 unsigned wx = c - '0';
30244 wx = wx*10 + c - '0';
30256 fmt--;
30268 width = width >= -2147483647 ? -width : 0;
30290 precision = precision >= -2147483647 ? -precision : -1;
30296 px = px*10 + c - '0';
30308 --fmt;
30323 xtype = infop->type;
30334 ** flag_leftjustify TRUE if a '-' is present or if the
30339 ** always non-negative. Zero is the default.
30341 ** is -1.
30346 assert( precision>=(-1) );
30357 if( infop->flags & FLAG_SIGNED ){
30372 testcase( v==(-1) );
30375 prefix = '-';
30395 if( flag_zeropad && precision<width-(prefix!=0) ){
30396 precision = width-(prefix!=0);
30398 if( precision<etBUFSIZE-10-etBUFSIZE/3 ){
30409 bufpt = &zOut[nOut-1];
30416 *(--bufpt) = zOrd[x*2+1];
30417 *(--bufpt) = zOrd[x*2];
30420 const char *cset = &aDigits[infop->charset];
30421 u8 base = infop->base;
30423 *(--bufpt) = cset[longvalue%base];
30427 length = (int)(&zOut[nOut-1]-bufpt);
30429 *(--bufpt) = '0'; /* Zero pad */
30433 int nn = (length - 1)/3; /* Number of "," to insert */
30434 int ix = (length - 1)%3 + 1;
30435 bufpt -= nn;
30438 ix--;
30441 nn--;
30446 if( prefix ) *(--bufpt) = prefix; /* Add sign */
30447 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
30450 pre = &aPrefix[infop->prefix];
30451 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
30453 length = (int)(&zOut[nOut-1]-bufpt);
30473 realvalue = -realvalue;
30474 prefix = '-';
30478 if( xtype==etGENERIC && precision>0 ) precision--;
30482 while( idx>=10 ){ rounder *= 1.0e-10; idx -= 10; }
30488 ex = -1023 + (int)((u>>52)&0x7ff);
30489 if( precision+(ex/3) < 15 ) rounder += realvalue*3e-16;
30505 while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
30506 while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
30526 if( exp<-4 || exp>precision ){
30529 precision = precision - exp;
30559 for(; e2>=0; e2--){
30569 for(e2++; e2<0; precision--, e2++){
30574 while( (precision--)>0 ){
30579 while( bufpt[-1]=='0' ) *(--bufpt) = 0;
30581 if( bufpt[-1]=='.' ){
30585 *(--bufpt) = 0;
30591 *(bufpt++) = aDigits[infop->charset];
30593 *(bufpt++) = '-'; exp = -exp;
30609 length = (int)(bufpt-zOut);
30616 int nPad = width - length;
30617 for(i=width; i>=nPad; i--){
30618 bufpt[i] = bufpt[i-nPad];
30621 while( nPad-- ) bufpt[i++] = '0';
30628 *(va_arg(ap,int*)) = pAccum->nChar;
30674 width -= precision-1;
30676 sqlite3_str_appendchar(pAccum, width-1, ' ');
30679 while( precision-- > 1 ){
30697 if( pAccum->nChar==0
30698 && pAccum->mxAlloc
30701 && pAccum->accError==0
30706 assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 );
30707 pAccum->zText = bufpt;
30708 pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt);
30709 pAccum->nChar = 0x7fffffff & (int)strlen(bufpt);
30710 pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED;
30721 while( precision-- > 0 && z[0] ){
30724 length = (int)(z - (unsigned char*)bufpt);
30733 /* Adjust width to account for extra bytes in UTF-8 characters */
30734 int ii = length - 1;
30735 while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++;
30760 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
30787 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
30792 sqlite3_str_appendall(pAccum, (const char*)pExpr->u.zToken);
30793 sqlite3RecordErrorOffsetOfExpr(pAccum->db, pExpr);
30799 if( pToken && pToken->n ){
30800 sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n);
30801 sqlite3RecordErrorByteOffset(pAccum->db, pToken->z);
30809 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return;
30812 if( pItem->zAlias && !flag_altform2 ){
30813 sqlite3_str_appendall(pAccum, pItem->zAlias);
30814 }else if( pItem->zName ){
30815 if( pItem->zDatabase ){
30816 sqlite3_str_appendall(pAccum, pItem->zDatabase);
30819 sqlite3_str_appendall(pAccum, pItem->zName);
30820 }else if( pItem->zAlias ){
30821 sqlite3_str_appendall(pAccum, pItem->zAlias);
30823 Select *pSel = pItem->pSelect;
30825 if( pSel->selFlags & SF_NestedFrom ){
30826 sqlite3_str_appendf(pAccum, "(join-%u)", pSel->selId);
30828 sqlite3_str_appendf(pAccum, "(subquery-%u)", pSel->selId);
30847 width -= length;
30857 sqlite3DbFree(pAccum->db, zExtra);
30876 if( db->errByteOffset!=(-2) ) return;
30877 pParse = db->pParse;
30879 zText =pParse->zTail;
30883 db->errByteOffset = (int)(z-zText);
30893 && (ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) || pExpr->w.iOfst<=0)
30895 pExpr = pExpr->pLeft;
30898 db->errByteOffset = pExpr->w.iOfst;
30910 assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
30911 if( p->accError ){
30912 testcase(p->accError==SQLITE_TOOBIG);
30913 testcase(p->accError==SQLITE_NOMEM);
30916 if( p->mxAlloc==0 ){
30918 return p->nAlloc - p->nChar - 1;
30920 char *zOld = isMalloced(p) ? p->zText : 0;
30921 i64 szNew = p->nChar;
30923 if( szNew+p->nChar<=p->mxAlloc ){
30926 szNew += p->nChar;
30928 if( szNew > p->mxAlloc ){
30933 p->nAlloc = (int)szNew;
30935 if( p->db ){
30936 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
30938 zNew = sqlite3Realloc(zOld, p->nAlloc);
30941 assert( p->zText!=0 || p->nChar==0 );
30942 if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
30943 p->zText = zNew;
30944 p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
30945 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
30959 testcase( p->nChar + (i64)N > 0x7fffffff );
30960 if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
30963 while( (N--)>0 ) p->zText[p->nChar++] = c;
30970 ** This is a helper routine to sqlite3_str_append() that does special-case
30977 memcpy(&p->zText[p->nChar], z, N);
30978 p->nChar += N;
30988 assert( p->zText!=0 || p->nChar==0 || p->accError );
30990 assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 );
30991 if( p->nChar+N >= p->nAlloc ){
30994 assert( p->zText );
30995 p->nChar += N;
30996 memcpy(&p->zText[p->nChar-N], z, N);
31001 ** Append the complete text of zero-terminated string z[] to the p string.
31009 ** Finish off a string by making sure it is zero-terminated.
31015 assert( p->mxAlloc>0 && !isMalloced(p) );
31016 zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
31018 memcpy(zText, p->zText, p->nChar+1);
31019 p->printfFlags |= SQLITE_PRINTF_MALLOCED;
31023 p->zText = zText;
31027 if( p->zText ){
31028 p->zText[p->nChar] = 0;
31029 if( p->mxAlloc>0 && !isMalloced(p) ){
31033 return p->zText;
31041 if( p->accError ){
31042 sqlite3_result_error_code(pCtx, p->accError);
31045 sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC);
31077 return p ? p->accError : SQLITE_NOMEM;
31082 return p ? p->nChar : 0;
31087 if( p==0 || p->nChar==0 ) return 0;
31088 p->zText[p->nChar] = 0;
31089 return p->zText;
31097 sqlite3DbFree(p->db, p->zText);
31098 p->printfFlags &= ~SQLITE_PRINTF_MALLOCED;
31100 p->nAlloc = 0;
31101 p->nChar = 0;
31102 p->zText = 0;
31110 ** memory is used if not NULL. db->mallocFailed is set appropriately
31120 p->zText = zBase;
31121 p->db = db;
31122 p->nAlloc = n;
31123 p->mxAlloc = mx;
31124 p->nChar = 0;
31125 p->accError = 0;
31126 p->printfFlags = 0;
31134 db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH);
31143 ** %-conversion extensions.
31151 db->aLimit[SQLITE_LIMIT_LENGTH]);
31163 ** %-conversion extensions.
31176 ** %-conversion extensions.
31200 ** %-conversion extensions.
31254 ** stack space on small-stack systems when logging is disabled.
31316 ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
31329 ** 2015-06-08
31331 ** The author disclaims copyright to this source code. In place of
31361 p->iLevel++;
31364 if( p->iLevel<(int)sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
31373 p->iLevel--;
31374 if( p->iLevel<0 ){
31391 for(i=0; i<p->iLevel && i<(int)sizeof(p->bLine)-1; i++){
31392 sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4);
31394 sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
31430 int colMoreToFollow = i<(nCol - 1);
31445 printf(" X-%s", z);
31453 if( flg & COLFLAG_NOEXPAND ) printf(" NO-EXPAND");
31464 ** Generate a human-readable description of a WITH clause.
31469 if( pWith->nCte==0 ) return;
31470 if( pWith->pOuter ){
31471 sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
31475 if( pWith->nCte>0 ){
31477 for(i=0; i<pWith->nCte; i++){
31480 const struct Cte *pCte = &pWith->a[i];
31482 sqlite3_str_appendf(&x, "%s", pCte->zName);
31483 if( pCte->pCols && pCte->pCols->nExpr>0 ){
31486 for(j=0; j<pCte->pCols->nExpr; j++){
31487 sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zEName);
31492 if( pCte->eM10d!=M10d_Any ){
31494 pCte->eM10d==M10d_No ? "NOT " : "");
31496 if( pCte->pUse ){
31497 sqlite3_str_appendf(&x, " (pUse=0x%p, nUse=%d)", pCte->pUse,
31498 pCte->pUse->nUse);
31501 sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
31502 sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
31510 ** Generate a human-readable description of a SrcList object.
31515 for(i=0; i<pSrc->nSrc; i++){
31516 const SrcItem *pItem = &pSrc->a[i];
31522 sqlite3_str_appendf(&x, "{%d:*} %!S", pItem->iCursor, pItem);
31523 if( pItem->pTab ){
31525 pItem->pTab->zName, pItem->pTab->nCol, pItem->pTab, pItem->colUsed);
31527 if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))==(JT_LEFT|JT_RIGHT) ){
31528 sqlite3_str_appendf(&x, " FULL-OUTER-JOIN");
31529 }else if( pItem->fg.jointype & JT_LEFT ){
31530 sqlite3_str_appendf(&x, " LEFT-JOIN");
31531 }else if( pItem->fg.jointype & JT_RIGHT ){
31532 sqlite3_str_appendf(&x, " RIGHT-JOIN");
31533 }else if( pItem->fg.jointype & JT_CROSS ){
31534 sqlite3_str_appendf(&x, " CROSS-JOIN");
31536 if( pItem->fg.jointype & JT_LTORJ ){
31539 if( pItem->fg.fromDDL ){
31542 if( pItem->fg.isCte ){
31543 sqlite3_str_appendf(&x, " CteUse=0x%p", pItem->u2.pCteUse);
31545 if( pItem->fg.isOn || (pItem->fg.isUsing==0 && pItem->u3.pOn!=0) ){
31549 sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1);
31551 if( pItem->pSelect ) n++;
31552 if( pItem->fg.isTabFunc ) n++;
31553 if( pItem->fg.isUsing ) n++;
31554 if( pItem->fg.isUsing ){
31555 sqlite3TreeViewIdList(pView, pItem->u3.pUsing, (--n)>0, "USING");
31557 if( pItem->pSelect ){
31558 if( pItem->pTab ){
31559 Table *pTab = pItem->pTab;
31560 sqlite3TreeViewColumnList(pView, pTab->aCol, pTab->nCol, 1);
31562 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
31563 sqlite3TreeViewSelect(pView, pItem->pSelect, (--n)>0);
31565 if( pItem->fg.isTabFunc ){
31566 sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
31573 ** Generate a human-readable description of a Select object.
31579 sqlite3TreeViewLine(pView, "nil-SELECT");
31583 if( p->pWith ){
31584 sqlite3TreeViewWith(pView, p->pWith, 1);
31589 if( p->selFlags & SF_WhereBegin ){
31594 ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
31595 ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""),
31596 p->selId, p, p->selFlags,
31597 (int)p->nSelectRow
31601 if( p->pPrior ){
31605 if( p->pSrc && p->pSrc->nSrc ) n++;
31606 if( p->pWhere ) n++;
31607 if( p->pGroupBy ) n++;
31608 if( p->pHaving ) n++;
31609 if( p->pOrderBy ) n++;
31610 if( p->pLimit ) n++;
31612 if( p->pWin ) n++;
31613 if( p->pWinDefn ) n++;
31616 if( p->pEList ){
31617 sqlite3TreeViewExprList(pView, p->pEList, n>0, "result-set");
31619 n--;
31621 if( p->pWin ){
31623 sqlite3TreeViewPush(&pView, (n--)>0);
31624 sqlite3TreeViewLine(pView, "window-functions");
31625 for(pX=p->pWin; pX; pX=pX->pNextWin){
31626 sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0);
31631 if( p->pSrc && p->pSrc->nSrc ){
31632 sqlite3TreeViewPush(&pView, (n--)>0);
31634 sqlite3TreeViewSrcList(pView, p->pSrc);
31637 if( p->pWhere ){
31638 sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
31639 sqlite3TreeViewExpr(pView, p->pWhere, 0);
31642 if( p->pGroupBy ){
31643 sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
31645 if( p->pHaving ){
31646 sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
31647 sqlite3TreeViewExpr(pView, p->pHaving, 0);
31651 if( p->pWinDefn ){
31653 sqlite3TreeViewItem(pView, "WINDOW", (n--)>0);
31654 for(pX=p->pWinDefn; pX; pX=pX->pNextWin){
31655 sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0);
31660 if( p->pOrderBy ){
31661 sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
31663 if( p->pLimit ){
31664 sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
31665 sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0);
31666 if( p->pLimit->pRight ){
31667 sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
31668 sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0);
31673 if( p->pPrior ){
31675 switch( p->op ){
31682 p = p->pPrior;
31726 ** Generate a human-readable explanation for a Window object
31731 if( pWin->pFilter ){
31733 sqlite3TreeViewExpr(pView, pWin->pFilter, 0);
31737 if( pWin->zName ){
31738 sqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin);
31742 if( pWin->zBase ) nElement++;
31743 if( pWin->pOrderBy ) nElement++;
31744 if( pWin->eFrmType ) nElement++;
31745 if( pWin->eExclude ) nElement++;
31746 if( pWin->zBase ){
31747 sqlite3TreeViewPush(&pView, (--nElement)>0);
31748 sqlite3TreeViewLine(pView, "window: %s", pWin->zBase);
31751 if( pWin->pPartition ){
31752 sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY");
31754 if( pWin->pOrderBy ){
31755 sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY");
31757 if( pWin->eFrmType ){
31760 if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE";
31761 if( pWin->eFrmType==TK_GROUPS ) zFrmType = "GROUPS";
31763 pWin->bImplicitFrame ? " (implied)" : "");
31764 sqlite3TreeViewItem(pView, zBuf, (--nElement)>0);
31765 sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1);
31766 sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0);
31769 if( pWin->eExclude ){
31772 switch( pWin->eExclude ){
31778 sqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude);
31792 ** Generate a human-readable explanation for a Window Function object
31798 pWin->pWFunc->zName, pWin->pWFunc->nArg);
31805 ** Generate a human-readable explanation of an expression tree.
31817 if( pExpr->flags || pExpr->affExpr || pExpr->vvaFlags ){
31821 pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n');
31823 sqlite3_str_appendf(&x, " outer.iJoin=%d", pExpr->w.iJoin);
31826 sqlite3_str_appendf(&x, " inner.iJoin=%d", pExpr->w.iJoin);
31838 switch( pExpr->op ){
31841 pExpr->iTable, pExpr->iColumn, zFlgs);
31845 if( pExpr->iTable<0 ){
31848 if( pExpr->op2 ){
31849 sqlite3_snprintf(sizeof(zOp2),zOp2," op2=0x%02x",pExpr->op2);
31854 pExpr->iColumn, zFlgs, zOp2);
31858 pExpr->iTable, pExpr->iColumn,
31859 pExpr->y.pTab, zFlgs);
31862 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
31867 if( pExpr->flags & EP_IntValue ){
31868 sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
31870 sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
31877 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
31883 sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
31898 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
31905 pExpr->u.zToken, pExpr->iColumn);
31909 sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
31914 sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
31921 sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
31922 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
31959 "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE"
31961 assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT );
31962 assert( pExpr->pRight );
31963 assert( sqlite3ExprSkipCollate(pExpr->pRight)->op==TK_TRUEFALSE );
31964 x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight);
31971 sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
31972 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
31979 ** up in the treeview output as "SOFT-COLLATE". Explicit COLLATE
31984 !ExprHasProperty(pExpr, EP_Collate) ? "SOFT-" : "",
31985 pExpr->u.zToken, zFlgs);
31986 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
31999 pFarg = pExpr->x.pList;
32001 pWin = ExprHasProperty(pExpr, EP_WinFunc) ? pExpr->y.pWin : 0;
32007 if( pExpr->op==TK_AGG_FUNCTION ){
32009 pExpr->op2, pExpr->u.zToken, zFlgs,
32010 pExpr->pAggInfo ? pExpr->pAggInfo->selId : 0,
32011 pExpr->iAgg, pExpr->pAggInfo);
32012 }else if( pExpr->op2!=0 ){
32015 sqlite3_snprintf(sizeof(zBuf),zBuf,"0x%02x",pExpr->op2);
32017 if( pExpr->op2==NC_IsCheck ) zOp2 = "NC_IsCheck";
32018 if( pExpr->op2==NC_IdxExpr ) zOp2 = "NC_IdxExpr";
32019 if( pExpr->op2==NC_PartIdx ) zOp2 = "NC_PartIdx";
32020 if( pExpr->op2==NC_GenCol ) zOp2 = "NC_GenCol";
32022 pExpr->u.zToken, zFlgs, zOp2);
32024 sqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs);
32039 sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags);
32040 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
32045 sqlite3TreeViewLine(pView, "subquery-expr flags=0x%x", pExpr->flags);
32046 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
32052 sqlite3_str_appendf(pStr, "IN flags=0x%x", pExpr->flags);
32053 if( pExpr->iTable ) sqlite3_str_appendf(pStr, " iTable=%d",pExpr->iTable);
32056 pExpr->y.sub.regReturn, pExpr->y.sub.iAddr);
32061 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
32063 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
32065 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
32078 ** X is stored in pExpr->pLeft.
32079 ** Y is stored in pExpr->pList->a[0].pExpr.
32080 ** Z is stored in pExpr->pList->a[1].pExpr.
32084 pX = pExpr->pLeft;
32086 assert( pExpr->x.pList->nExpr==2 );
32087 pY = pExpr->x.pList->a[0].pExpr;
32088 pZ = pExpr->x.pList->a[1].pExpr;
32097 ** to a column in the new.* or old.* pseudo-tables available to
32099 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
32100 ** is set to the column of the pseudo-table to read, or to -1 to
32104 pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
32109 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
32111 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
32117 switch( pExpr->affExpr ){
32124 sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
32130 pExpr->iTable, pExpr->iColumn, zFlgs);
32131 sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
32137 sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z);
32142 sqlite3TreeViewLine(pView, "SELECT-COLUMN %d of [0..%d]%s",
32143 pExpr->iColumn, pExpr->iTable-1,
32144 pExpr->pRight==pExpr->pLeft ? " (SELECT-owner)" : "");
32145 assert( ExprUseXSelect(pExpr->pLeft) );
32146 sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0);
32150 sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable);
32151 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
32158 tmp.op = pExpr->op2;
32163 if( pExpr->iColumn<=0 ){
32167 pExpr->iColumn-1);
32172 sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
32178 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
32179 sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
32182 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
32189 ** Generate a human-readable explanation of an expression list.
32202 for(i=0; i<pList->nExpr; i++){
32203 int j = pList->a[i].u.x.iOrderByCol;
32204 char *zName = pList->a[i].zEName;
32205 int moreToFollow = i<pList->nExpr - 1;
32211 switch( pList->a[i].fg.eEName ){
32216 fprintf(stdout, "TABLE-ALIAS-NAME(\"%s\") ", zName);
32217 if( pList->a[i].fg.bUsed ) fprintf(stdout, "(used) ");
32218 if( pList->a[i].fg.bUsingTerm ) fprintf(stdout, "(USING-term) ");
32219 if( pList->a[i].fg.bNoExpand ) fprintf(stdout, "(NoExpand) ");
32232 sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow);
32251 ** Generate a human-readable explanation of an id-list.
32264 for(i=0; i<pList->nId; i++){
32265 char *zName = pList->a[i].zName;
32266 int moreToFollow = i<pList->nId - 1;
32270 if( pList->eU4==EU4_NONE ){
32272 }else if( pList->eU4==EU4_IDX ){
32273 fprintf(stdout, "%s (%d)\n", zName, pList->a[i].u4.idx);
32275 assert( pList->eU4==EU4_EXPR );
32276 if( pList->a[i].u4.pExpr==0 ){
32280 sqlite3TreeViewPush(&pView, i<pList->nId-1);
32281 sqlite3TreeViewExpr(pView, pList->a[i].u4.pExpr, 0);
32301 ** Generate a human-readable explanation of a list of Upsert objects
32312 sqlite3TreeViewPush(&pView, pUpsert->pNextUpsert!=0 || moreToFollow);
32314 pUpsert->isDoUpdate ? "UPDATE" : "NOTHING");
32315 n = (pUpsert->pUpsertSet!=0) + (pUpsert->pUpsertWhere!=0);
32316 sqlite3TreeViewExprList(pView, pUpsert->pUpsertTarget, (n--)>0, "TARGET");
32317 sqlite3TreeViewExprList(pView, pUpsert->pUpsertSet, (n--)>0, "SET");
32318 if( pUpsert->pUpsertWhere ){
32319 sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
32320 sqlite3TreeViewExpr(pView, pUpsert->pUpsertWhere, 0);
32324 pUpsert = pUpsert->pNextUpsert;
32331 ** Generate a human-readable diagram of the data structure that go
32353 sqlite3TreeViewPush(&pView, (--n)>0);
32358 sqlite3TreeViewPush(&pView, (--n)>0);
32364 sqlite3TreeViewPush(&pView, (--n)>0);
32370 sqlite3TreeViewExprList(pView, pOrderBy, (--n)>0, "ORDER-BY");
32373 sqlite3TreeViewPush(&pView, (--n)>0);
32379 sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1);
32387 ** Generate a human-readable diagram of the data structure that go
32420 sqlite3TreeViewPush(&pView, (--n)>0);
32425 sqlite3TreeViewPush(&pView, (--n)>0);
32431 sqlite3TreeViewIdList(pView, pColumnList, (--n)>0, "COLUMNS");
32434 sqlite3TreeViewPush(&pView, (--n)>0);
32435 sqlite3TreeViewLine(pView, "DATA-SOURCE");
32440 sqlite3TreeViewExprList(pView, pExprList, (--n)>0, "VALUES");
32443 sqlite3TreeViewPush(&pView, (--n)>0);
32449 sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1);
32457 ** Generate a human-readable diagram of the data structure that go
32492 sqlite3TreeViewPush(&pView, (--n)>0);
32497 sqlite3TreeViewPush(&pView, (--n)>0);
32503 sqlite3TreeViewExprList(pView, pChanges, (--n)>0, "SET");
32506 sqlite3TreeViewPush(&pView, (--n)>0);
32512 sqlite3TreeViewExprList(pView, pOrderBy, (--n)>0, "ORDER-BY");
32515 sqlite3TreeViewPush(&pView, (--n)>0);
32521 sqlite3TreeViewPush(&pView, (--n)>0);
32527 sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1);
32535 ** Show a human-readable graph of a TriggerStep
32546 moreToFollow || (showFullList && pStep->pNext!=0));
32548 if( cnt++ && pStep->pNext==0 ){
32552 sqlite3TreeViewLine(pView, "%s", pStep->zSpan ? pStep->zSpan : "RETURNING");
32553 }while( showFullList && (pStep = pStep->pNext)!=0 );
32558 ** Show a human-readable graph of a Trigger
32569 moreToFollow || (showFullList && pTrigger->pNext!=0));
32571 if( cnt++ && pTrigger->pNext==0 ){
32575 sqlite3TreeViewLine(pView, "TRIGGER %s", pTrigger->zName);
32577 sqlite3TreeViewTriggerStep(pView, pTrigger->step_list, 0, 1);
32579 }while( showFullList && (pTrigger = pTrigger->pNext)!=0 );
32586 ** These simplified versions of the tree-view routines omit unnecessary
32624 ** The author disclaims copyright to this source code. In place of
32632 ** This file contains code to implement a pseudo-random number
32651 /* The RFC-7539 ChaCha20 block function
32653 #define ROTL(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
32682 /* The "wsdPrng" macro will resolve to the pseudo-random number generator
32684 ** we have to locate the state vector at run-time. In the more common
32736 memcpy(zBuf, &wsdPrng.out[wsdPrng.n-N], N);
32737 wsdPrng.n -= N;
32742 N -= wsdPrng.n;
32784 ** The author disclaims copyright to this source code. In place of
32793 ** This file presents a simple cross-platform threading interface for
32806 ** single-threaded if desired.
32818 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
32841 /* This routine is never used in single-threaded mode */
32848 p->xTask = xTask;
32849 p->pIn = pIn;
32857 rc = pthread_create(&p->tid, 0, xTask, pIn);
32860 p->done = 1;
32861 p->pOut = xTask(pIn);
32873 if( p->done ){
32874 *ppOut = p->pOut;
32877 rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
32890 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
32916 assert( p->id==GetCurrentThreadId() );
32918 assert( p->xTask!=0 );
32919 p->pResult = p->xTask(p->pIn);
32946 p->xTask = xTask;
32947 p->pIn = pIn;
32948 p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
32949 if( p->tid==0 ){
32953 if( p->xTask==0 ){
32954 p->id = GetCurrentThreadId();
32955 p->pResult = xTask(pIn);
32970 if( p->xTask==0 ){
32971 /* assert( p->id==GetCurrentThreadId() ); */
32973 assert( p->tid==0 );
32975 assert( p->id!=0 && p->id!=GetCurrentThreadId() );
32976 rc = sqlite3Win32Wait((HANDLE)p->tid);
32978 bRc = CloseHandle((HANDLE)p->tid);
32981 if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
32990 /********************************* Single-Threaded **************************/
33019 p->xTask = xTask;
33020 p->pIn = pIn;
33022 p->xTask = 0;
33023 p->pResult = xTask(pIn);
33034 if( p->xTask ){
33035 *ppOut = p->xTask(p->pIn);
33037 *ppOut = p->pResult;
33053 /****************************** End Single-Threaded *************************/
33061 ** The author disclaims copyright to this source code. In place of
33069 ** This file contains routines used to translate between UTF-8,
33070 ** UTF-16, UTF-16BE, and UTF-16LE.
33072 ** Notes on UTF-8:
33074 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
33081 ** Notes on UTF-16: (with wwww+1==uuuuu)
33083 ** Word-0 Word-1 Value
33089 ** 0xff 0xfe little-endian utf-16 follows
33090 ** 0xfe 0xff big-endian utf-16 follows
33107 ** a multi-byte UTF8 character.
33146 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
33147 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
33158 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
33159 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
33166 ** Translate a single UTF-8 character. Return the unicode value.
33173 ** Notes On Invalid UTF-8:
33175 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
33176 ** be encoded as a multi-byte character. Any multi-byte character that
33180 ** If a multi-byte character attempts to encode a value between
33184 ** byte of a character are interpreted as single-byte characters
33188 ** * This routine accepts over-length UTF8 encodings
33189 ** for unicode values 0x80 and greater. It does not change over-length
33195 c = sqlite3Utf8Trans1[c-0xc0]; \
33209 ** For this routine, we assume the UTF8 string is always zero-terminated.
33213 c = sqlite3Utf8Trans1[c-0xc0];
33247 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
33248 assert( pMem->flags&MEM_Str );
33249 assert( pMem->enc!=desiredEnc );
33250 assert( pMem->enc!=0 );
33251 assert( pMem->n>=0 );
33263 /* If the translation is between UTF-16 little and big endian, then
33267 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
33275 zIn = (u8*)pMem->z;
33276 zTerm = &zIn[pMem->n&~1];
33283 pMem->enc = desiredEnc;
33289 /* When converting from UTF-16, the maximum growth results from
33290 ** translating a 2-byte character to a 4-byte UTF-8 character.
33292 ** nul-terminator.
33294 pMem->n &= ~1;
33295 len = 2 * (sqlite3_int64)pMem->n + 1;
33297 /* When converting from UTF-8 to UTF-16 the maximum growth is caused
33298 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
33300 ** nul-terminator.
33302 len = 2 * (sqlite3_int64)pMem->n + 2;
33311 zIn = (u8*)pMem->z;
33312 zTerm = &zIn[pMem->n];
33313 zOut = sqlite3DbMallocRaw(pMem->db, len);
33319 if( pMem->enc==SQLITE_UTF8 ){
33321 /* UTF-8 -> UTF-16 Little-endian */
33328 /* UTF-8 -> UTF-16 Big-endian */
33334 pMem->n = (int)(z - zOut);
33338 if( pMem->enc==SQLITE_UTF16LE ){
33339 /* UTF-16 Little-endian -> UTF-8 */
33351 zIn -= 2;
33368 /* UTF-16 Big-endian -> UTF-8 */
33380 zIn -= 2;
33397 pMem->n = (int)(z - zOut);
33400 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
33402 c = MEM_Str|MEM_Term|(pMem->flags&(MEM_AffMask|MEM_Subtype));
33404 pMem->flags = c;
33405 pMem->enc = desiredEnc;
33406 pMem->z = (char*)zOut;
33407 pMem->zMalloc = pMem->z;
33408 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
33426 ** This routine checks for a byte-order mark at the beginning of the
33427 ** UTF-16 string stored in *pMem. If one is present, it is removed and
33429 ** byte-swapping, it just sets Mem.enc appropriately.
33438 assert( pMem->n>=0 );
33439 if( pMem->n>1 ){
33440 u8 b1 = *(u8 *)pMem->z;
33441 u8 b2 = *(((u8 *)pMem->z) + 1);
33453 pMem->n -= 2;
33454 memmove(pMem->z, &pMem->z[2], pMem->n);
33455 pMem->z[pMem->n] = '\0';
33456 pMem->z[pMem->n+1] = '\0';
33457 pMem->flags |= MEM_Term;
33458 pMem->enc = bom;
33466 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
33479 zTerm = (const u8*)(-1);
33489 /* This test function is not currently used by the automated test-suite.
33494 ** Translate UTF-8 to UTF-8.
33496 ** This has the effect of making sure that the string is well-formed
33497 ** UTF-8. Miscoded characters are removed.
33499 ** The translation is done in-place and aborted if the output
33514 return (int)(zOut - zStart);
33520 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
33521 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
33532 if( db->mallocFailed ){
33536 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
33537 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
33538 assert( m.z || db->mallocFailed );
33543 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
33545 ** in pZ. nChar must be non-negative.
33559 return (int)(z-(unsigned char const *)zIn)
33560 - (SQLITE_UTF16NATIVE==SQLITE_UTF16LE);
33579 n = (int)(z-zBuf);
33588 assert( (z-zBuf)==n );
33599 ** The author disclaims copyright to this source code. In place of
33625 ** sqlite3FaultSim() function only returns non-zero during testing.
33627 ** During testing, if the test harness has set a fault-sim callback using
33629 ** each call to sqlite3FaultSim() is relayed to that application-supplied
33630 ** callback and the integer return value form the application-supplied
33668 ** lower 30 bits of a 32-bit signed integer.
33683 ** The column type is an extra string stored after the zero-terminator on
33687 if( pCol->colFlags & COLFLAG_HASTYPE ){
33688 return pCol->zCnName + strlen(pCol->zCnName) + 1;
33689 }else if( pCol->eCType ){
33690 assert( pCol->eCType<=SQLITE_N_STDTYPE );
33691 return (char*)sqlite3StdType[pCol->eCType-1];
33698 ** Helper function for sqlite3Error() - called rarely. Broken out into
33703 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
33714 db->errCode = err_code;
33715 if( err_code || db->pErr ){
33718 db->errByteOffset = -1;
33728 db->errCode = SQLITE_OK;
33729 db->errByteOffset = -1;
33730 if( db->pErr ) sqlite3ValueSetNull(db->pErr);
33741 db->iSysErrno = sqlite3OsGetLastError(db->pVfs);
33751 ** assumed to be encoded in UTF-8.
33759 db->errCode = err_code;
33763 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
33769 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
33774 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
33786 sqlite3 *db = pParse->db;
33788 assert( db->pParse==pParse || db->pParse->pToplevel==pParse );
33789 db->errByteOffset = -2;
33793 if( db->errByteOffset<-1 ) db->errByteOffset = -1;
33794 if( db->suppressErr ){
33796 if( db->mallocFailed ){
33797 pParse->nErr++;
33798 pParse->rc = SQLITE_NOMEM;
33801 pParse->nErr++;
33802 sqlite3DbFree(db, pParse->zErrMsg);
33803 pParse->zErrMsg = zMsg;
33804 pParse->rc = SQLITE_ERROR;
33805 pParse->pWith = 0;
33816 if( db==0 || (pParse = db->pParse)==0 ) return errCode;
33817 pParse->rc = errCode;
33818 pParse->nErr++;
33823 ** Convert an SQL-style quoted string into a normal string by removing
33824 ** the quote characters. The conversion is done in-place. If the
33826 ** is a no-op.
33828 ** The input string must be zero-terminated. A new zero-terminator
33831 ** The return value is -1 if no dequoting occurs or the length of the
33835 ** 2002-02-14: This routine is extended to remove MS-Access style
33836 ** brackets from around identifiers. For example: "[a-b-c]" becomes
33837 ** "a-b-c".
33863 assert( sqlite3Isquote(p->u.zToken[0]) );
33864 p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted;
33865 sqlite3Dequote(p->u.zToken);
33872 ** "abc" -> abc
33873 ** "ab""cd" -> (not possible because of the interior "")
33877 ** is always a no-op.
33881 if( p->n<2 ) return;
33882 if( !sqlite3Isquote(p->z[0]) ) return;
33883 for(i=1; i<p->n-1; i++){
33884 if( sqlite3Isquote(p->z[i]) ) return;
33886 p->n -= 2;
33887 p->z++;
33894 p->z = z;
33895 p->n = sqlite3Strlen30(z);
33898 /* Convenient short-hand */
33905 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
33907 ** the contents of two buffers containing UTF-8 strings in a
33908 ** case-independent fashion, using the same definition of "case
33913 return zRight ? -1 : 0;
33930 c = (int)UpperToLower[c] - (int)UpperToLower[x];
33941 return zRight ? -1 : 0;
33947 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
33948 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
33952 ** Compute an 8-bit hash on a string that is insensitive to case differences
33965 ** Compute 10 to the E-th power. Examples: E==1 results in 10.
34008 ** uses the encoding enc. The string is not necessarily zero-terminated.
34016 ** -1 => Not a valid number, but has a valid prefix which
34021 ** [+-]digits[E[+-]digits]
34022 ** [+-]digits.[digits][E[+-]digits]
34023 ** [+-].digits[E[+-]digits]
34045 int eValid = 1; /* True exponent is either not used or is well-formed */
34048 int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */
34064 for(i=3-enc; i<length && z[i]==0; i+=2){}
34065 if( i<length ) eType = -100;
34075 if( *z=='-' ){
34076 sign = -1;
34084 s = s*10 + (*z - '0');
34086 if( s>=((LARGEST_INT64-9)/10) ){
34087 /* skip non-significant significand digits
34101 if( s<((LARGEST_INT64-9)/10) ){
34102 s = s*10 + (*z - '0');
34103 d--;
34120 if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
34123 if( *z=='-' ){
34124 esign = -1;
34131 e = e<10000 ? (e*10 + (*z - '0')) : 10000;
34144 esign = -1;
34145 e *= -1;
34152 result = sign<0 ? -(double)0 : (double)0;
34160 while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
34162 if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
34165 if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
34168 e--;
34172 s = sign<0 ? -s : s;
34174 if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
34178 if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
34179 if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
34180 LONGDOUBLE_TYPE scale = sqlite3Pow10(e-308);
34213 /* return true if number and no extra non-whitespace chracters after */
34217 return -1;
34230 ** Render an signed 64-bit integer as text. Store the result in zOut[].
34239 x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v;
34243 i = sizeof(zTemp)-2;
34244 zTemp[sizeof(zTemp)-1] = 0;
34246 zTemp[i--] = (x%10) + '0';
34249 if( v<0 ) zTemp[i--] = '-';
34250 memcpy(zOut, &zTemp[i+1], sizeof(zTemp)-1-i);
34254 ** Compare the 19-character string zNum against the text representation
34265 ** will return -8.
34273 c = (zNum[i*incr]-pow63[i])*10;
34276 c = zNum[18*incr] - '8';
34277 testcase( c==(-1) );
34285 ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
34290 ** -1 Not even a prefix of the input text looks like an integer
34291 ** 0 Successful transformation. Fits in a 64-bit signed integer.
34292 ** 1 Excess non-space text after the integer value
34293 ** 2 Integer too large for a 64-bit signed integer or is malformed
34297 ** The string is not necessarily zero-terminated. The encoding is
34306 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
34317 for(i=3-enc; i<length && zNum[i]==0; i+=2){}
34324 if( *zNum=='-' ){
34334 u = u*10 + c - '0';
34341 ** from clang and -fsanitize=undefined. This test and assignment make
34343 ** them, but we must appaise the undefined-behavior pharisees. */
34346 *pNum = -(i64)u;
34352 rc = -1;
34353 }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */
34359 rc = 1; /* Extra non-space text after the integer */
34370 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
34384 assert( u-1==LARGEST_INT64 );
34392 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
34393 ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
34398 ** 0 Successful transformation. Fits in a 64-bit signed integer.
34400 ** 2 Integer too large for a 64-bit signed integer or is malformed
34415 return (z[k]==0 && k-i<=16) ? 0 : 2;
34424 ** If zNum represents an integer that will fit in 32-bits, then set
34429 ** Any non-numeric characters that following zNum are ignored.
34431 ** input number to be zero-terminated.
34437 if( zNum[0]=='-' ){
34464 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
34471 ** 2^31 -> 2147483648
34477 testcase( v-neg==2147483647 );
34478 if( v-neg>2147483647 ){
34482 v = -v;
34489 ** Return a 32-bit integer value extracted from a string. If the
34499 ** Try to convert z into an unsigned 32-bit integer. Return true on
34508 v = v*10 + z[i] - '0';
34517 ** The variable-length integer encoding is as follows:
34524 ** 7 bits - A
34525 ** 14 bits - BA
34526 ** 21 bits - BBA
34527 ** 28 bits - BBBA
34528 ** 35 bits - BBBBA
34529 ** 42 bits - BBBBBA
34530 ** 49 bits - BBBBBBA
34531 ** 56 bits - BBBBBBBA
34532 ** 64 bits - BBBBBBBBC
34536 ** Write a 64-bit variable-length integer to memory starting at p[0].
34540 ** A variable-length integer consists of the lower 7 bits of each byte
34551 for(i=7; i>=0; i--){
34564 for(i=0, j=n-1; j>=0; j--, i++){
34596 ** Read a 64-bit variable-length integer from memory starting at p[0].
34739 b = p[-4];
34750 ** Read a 32-bit variable-length integer from memory starting at p[0].
34753 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
34757 ** single-byte case. All code should use the MACRO version as
34758 ** this function assumes the single-byte case has already been handled.
34763 /* The 1-byte case. Overwhelmingly the most common. Handled inline
34776 /* The 2-byte case */
34789 /* The 3-byte case */
34804 /* A 32-bit varint is used to store size information in btrees.
34805 ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
34806 ** A 3-byte varint is sufficient, for example, to record the size
34807 ** of a 1048569-byte BLOB or string.
34809 ** We only unroll the first 1-, 2-, and 3- byte cases. The very
34810 ** rare larger cases can be handled by the slower 64-bit varint
34818 n = sqlite3GetVarint(p-2, &v64);
34830 ** unrolling for the 3- and 4-byte varint cases. This code is
34863 ** slow) general-purpose sqlite3GetVarint() routine to extract the
34869 p -= 4;
34880 ** 64-bit integer.
34890 ** Read or write a four-byte big-endian integer value.
34957 n--;
35000 eOpenState = db->eOpenState;
35013 eOpenState = db->eOpenState;
35026 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
35027 ** the other 64-bit signed integer at *pA and store the result in *pA.
35037 testcase( iB==-1 ); testcase( iB==0 );
35039 testcase( iA>0 && LARGEST_INT64 - iA == iB );
35040 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
35041 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
35043 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
35044 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
35045 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
35057 testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
35059 *pA -= iB;
35062 return sqlite3AddInt64(pA, -iB);
35080 if( -iA>LARGEST_INT64/-iB ) return 1;
35089 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
35090 ** if the integer has a value of -2147483648, return +2147483647
35095 return -x;
35100 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
35106 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
35111 ** test.db-journal => test.nal
35112 ** test.db-wal => test.wal
35113 ** test.db-shm => test.shm
35114 ** test.db-mj7f3319fa => test.9fa
35123 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
35124 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
35142 5, 5, 5, /* 12-14 */
35143 4, 4, 4, 4, /* 15-18 */
35144 3, 3, 3, 3, 3, 3, /* 19-24 */
35145 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
35150 return a+x[a-b];
35154 return b+x[b-a];
35167 while( x<8 ){ y -= 10; x <<= 1; }
35170 int i = 60 - __builtin_clzll(x);
35174 while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
35178 return a[x&7] + y - 10;
35192 e = (a>>52) - 1022;
35203 if( n>=5 ) n -= 2;
35204 else if( n>=1 ) n -= 1;
35206 return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
35213 ** db->mallocFailed flag is set.
35226 ** is always zero-terminated.
35317 ** The author disclaims copyright to this source code. In place of
35325 ** This is the implementation of generic hash-tables
35338 pNew->first = 0;
35339 pNew->count = 0;
35340 pNew->htsize = 0;
35341 pNew->ht = 0;
35352 elem = pH->first;
35353 pH->first = 0;
35354 sqlite3_free(pH->ht);
35355 pH->ht = 0;
35356 pH->htsize = 0;
35358 HashElem *next_elem = elem->next;
35362 pH->count = 0;
35371 while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
35374 ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. */
35392 pHead = pEntry->count ? pEntry->chain : 0;
35393 pEntry->count++;
35394 pEntry->chain = pNew;
35399 pNew->next = pHead;
35400 pNew->prev = pHead->prev;
35401 if( pHead->prev ){ pHead->prev->next = pNew; }
35402 else { pH->first = pNew; }
35403 pHead->prev = pNew;
35405 pNew->next = pH->first;
35406 if( pH->first ){ pH->first->prev = pNew; }
35407 pNew->prev = 0;
35408 pH->first = pNew;
35427 if( new_size==pH->htsize ) return 0;
35443 sqlite3_free(pH->ht);
35444 pH->ht = new_ht;
35445 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
35447 for(elem=pH->first, pH->first=0; elem; elem = next_elem){
35448 unsigned int h = strHash(elem->pKey) % new_size;
35449 next_elem = elem->next;
35470 if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
35472 h = strHash(pKey) % pH->htsize;
35473 pEntry = &pH->ht[h];
35474 elem = pEntry->chain;
35475 count = pEntry->count;
35478 elem = pH->first;
35479 count = pH->count;
35482 while( count-- ){
35484 if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
35487 elem = elem->next;
35501 if( elem->prev ){
35502 elem->prev->next = elem->next;
35504 pH->first = elem->next;
35506 if( elem->next ){
35507 elem->next->prev = elem->prev;
35509 if( pH->ht ){
35510 pEntry = &pH->ht[h];
35511 if( pEntry->chain==elem ){
35512 pEntry->chain = elem->next;
35514 assert( pEntry->count>0 );
35515 pEntry->count--;
35518 pH->count--;
35519 if( pH->count==0 ){
35520 assert( pH->first==0 );
35521 assert( pH->count==0 );
35533 return findElementWithHash(pH, pKey, 0)->data;
35558 if( elem->data ){
35559 void *old_data = elem->data;
35563 elem->data = data;
35564 elem->pKey = pKey;
35571 new_elem->pKey = pKey;
35572 new_elem->data = data;
35573 pH->count++;
35574 if( pH->count>=10 && pH->count > 2*pH->htsize ){
35575 if( rehash(pH, pH->count*2) ){
35576 assert( pH->htsize>0 );
35577 h = strHash(pKey) % pH->htsize;
35580 insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
35657 /* 59 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
35658 /* 60 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"),
35659 /* 61 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
35688 /* 90 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
35705 /* 107 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
35722 /* 124 */ "SeekScan" OpHelp("Scan-ahead up to P1 rows"),
35758 /* 160 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
35793 ** 2022-09-06
35795 ** The author disclaims copyright to this source code. In place of
35836 ** VFS - the database and the rollback journal.
35845 sqlite3_int64 szDb; /* Database file size. -1 means unknown */
35958 /* Forward declarations for the low-level storage engine
35974 sqlite3_snprintf(KVSTORAGE_KEY_SZ, zKeyOut, "kvvfs-%s-%s", zClass, zKeyIn);
35978 ** underlying key/value store to use - either "local" or "session".
35980 ** Both zKey and zData are zero-terminated pure text strings.
35994 SQLITE_KV_TRACE(("KVVFS-WRITE %-15s (%d) %.50s%s\n", zXKey,
36007 ** this routine is a no-op.
36013 SQLITE_KV_TRACE(("KVVFS-DELETE %-15s\n", zXKey));
36024 ** not counting the final zero terminator. Return -1 if the key does
36044 SQLITE_KV_TRACE(("KVVFS-READ %-15s (-1)\n", zXKey));
36045 return -1;
36051 SQLITE_KV_TRACE(("KVVFS-READ %-15s (%d)\n", zXKey,
36060 SQLITE_KV_TRACE(("KVVFS-READ %-15s (-1)\n", zXKey));
36061 return -1;
36063 sqlite3_int64 n = fread(zBuf, 1, nBuf-1, fd);
36066 SQLITE_KV_TRACE(("KVVFS-READ %-15s (%lld) %.50s%s\n", zXKey,
36093 ** for JavaScript-side implementations in WASM builds. In such builds
36122 ** ---------------
36124 ** * Non-zero bytes are encoded as upper-case hexadecimal
36126 ** * A sequence of one or more zero-bytes that are not at the
36127 ** beginning of the buffer are encoded as a little-endian
36128 ** base-26 number using a..z. "a" means 0. "b" means 1,
36132 ** of hexadecimal and base-26 numbers, it is always clear where
36144 /* A sequence of 1 or more zeros is stored as a little-endian
36145 ** base-26 number using a..z as the digits. So one zero is "b".
36151 i += k-1;
36163 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36164 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36165 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36166 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
36167 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36168 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36169 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36170 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36172 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36173 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36174 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36175 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36176 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36177 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36178 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
36179 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
36202 n += (c - 'a')*mult;
36206 if( j+n>nOut ) return -1;
36223 ** Decode a complete journal file. Allocate space in pFile->aJrnl
36224 ** and store the decoding there. Or leave pFile->aJrnl set to NULL
36227 ** The first few characters of the text encoding will be a little-endian
36228 ** base-26 number (digits a..z) that is the total number of bytes
36229 ** in the decoded journal file image. This base-26 number is followed
36231 ** separator is required to act as a terminator for the base-26 number.
36234 KVVfsFile *pFile, /* Store decoding in pFile->aJrnl */
36235 const char *zTxt, /* Text encoding. Zero-terminated */
36243 n += (zTxt[i] - 'a')*mult;
36246 sqlite3_free(pFile->aJrnl);
36247 pFile->aJrnl = sqlite3_malloc64( n );
36248 if( pFile->aJrnl==0 ){
36249 pFile->nJrnl = 0;
36252 pFile->nJrnl = n;
36253 n = kvvfsDecode(zTxt+i, pFile->aJrnl, pFile->nJrnl);
36254 if( n<pFile->nJrnl ){
36255 sqlite3_free(pFile->aJrnl);
36256 pFile->aJrnl = 0;
36257 pFile->nJrnl = 0;
36267 sqlite3KvvfsMethods.xRead(pFile->zClass, "sz", zData, sizeof(zData)-1);
36273 return sqlite3KvvfsMethods.xWrite(pFile->zClass, "sz", zData);
36279 ** Close an kvvfs-file.
36284 SQLITE_KV_LOG(("xClose %s %s\n", pFile->zClass,
36285 pFile->isJournal ? "journal" : "db"));
36286 sqlite3_free(pFile->aJrnl);
36291 ** Read from the -journal file.
36300 assert( pFile->isJournal );
36301 SQLITE_KV_LOG(("xRead('%s-journal',%d,%lld)\n", pFile->zClass, iAmt, iOfst));
36302 if( pFile->aJrnl==0 ){
36303 int szTxt = kvstorageRead(pFile->zClass, "jrnl", 0, 0);
36310 kvstorageRead(pFile->zClass, "jrnl", aTxt, szTxt+1);
36313 if( pFile->aJrnl==0 ) return SQLITE_IOERR;
36315 if( iOfst+iAmt>pFile->nJrnl ){
36318 memcpy(zBuf, pFile->aJrnl+iOfst, iAmt);
36338 SQLITE_KV_LOG(("xRead('%s-db',%d,%lld)\n", pFile->zClass, iAmt, iOfst));
36343 if( (iAmt & (iAmt-1))!=0 || iAmt<512 || iAmt>65536 ){
36346 pFile->szPage = iAmt;
36352 got = sqlite3KvvfsMethods.xRead(pFile->zClass, zKey, aData, sizeof(aData)-1);
36360 n = kvvfsDecode(aData, &aData[2000], sizeof(aData)-2000);
36372 memset(zBuf+n, 0, iAmt-n);
36380 ** Write into the -journal file.
36390 SQLITE_KV_LOG(("xWrite('%s-journal',%d,%lld)\n", pFile->zClass, iAmt, iOfst));
36392 if( pFile->aJrnl==0 || pFile->nJrnl<iEnd ){
36393 char *aNew = sqlite3_realloc(pFile->aJrnl, iEnd);
36397 pFile->aJrnl = aNew;
36398 if( pFile->nJrnl<iOfst ){
36399 memset(pFile->aJrnl+pFile->nJrnl, 0, iOfst-pFile->nJrnl);
36401 pFile->nJrnl = iEnd;
36403 memcpy(pFile->aJrnl+iOfst, zBuf, iAmt);
36420 SQLITE_KV_LOG(("xWrite('%s-db',%d,%lld)\n", pFile->zClass, iAmt, iOfst));
36422 assert( (iAmt & (iAmt-1))==0 );
36423 assert( pFile->szPage<0 || pFile->szPage==iAmt );
36424 pFile->szPage = iAmt;
36428 if( sqlite3KvvfsMethods.xWrite(pFile->zClass, zKey, aData) ){
36431 if( iOfst+iAmt > pFile->szDb ){
36432 pFile->szDb = iOfst + iAmt;
36438 ** Truncate an kvvfs-file.
36442 SQLITE_KV_LOG(("xTruncate('%s-journal',%lld)\n", pFile->zClass, size));
36444 sqlite3KvvfsMethods.xDelete(pFile->zClass, "jrnl");
36445 sqlite3_free(pFile->aJrnl);
36446 pFile->aJrnl = 0;
36447 pFile->nJrnl = 0;
36452 if( pFile->szDb>size
36453 && pFile->szPage>0
36454 && (size % pFile->szPage)==0
36458 SQLITE_KV_LOG(("xTruncate('%s-db',%lld)\n", pFile->zClass, size));
36459 pgno = 1 + size/pFile->szPage;
36460 pgnoMax = 2 + pFile->szDb/pFile->szPage;
36463 sqlite3KvvfsMethods.xDelete(pFile->zClass, zKey);
36466 pFile->szDb = size;
36473 ** Sync an kvvfs-file.
36479 SQLITE_KV_LOG(("xSync('%s-journal')\n", pFile->zClass));
36480 if( pFile->nJrnl<=0 ){
36483 zOut = sqlite3_malloc64( pFile->nJrnl*2 + 50 );
36487 n = pFile->nJrnl;
36494 kvvfsEncode(pFile->aJrnl, pFile->nJrnl, &zOut[i]);
36495 i = sqlite3KvvfsMethods.xWrite(pFile->zClass, "jrnl", zOut);
36504 ** Return the current file-size of an kvvfs-file.
36508 SQLITE_KV_LOG(("xFileSize('%s-journal')\n", pFile->zClass));
36509 *pSize = pFile->nJrnl;
36514 SQLITE_KV_LOG(("xFileSize('%s-db')\n", pFile->zClass));
36515 if( pFile->szDb>=0 ){
36516 *pSize = pFile->szDb;
36524 ** Lock an kvvfs-file.
36528 assert( !pFile->isJournal );
36529 SQLITE_KV_LOG(("xLock(%s,%d)\n", pFile->zClass, eLock));
36532 pFile->szDb = kvvfsReadFileSize(pFile);
36538 ** Unlock an kvvfs-file.
36542 assert( !pFile->isJournal );
36543 SQLITE_KV_LOG(("xUnlock(%s,%d)\n", pFile->zClass, eLock));
36545 pFile->szDb = -1;
36551 ** Check if another file-handle holds a RESERVED lock on an kvvfs-file.
36560 ** File control method. For custom operations on an kvvfs-file.
36571 SQLITE_KV_LOG(("xSync('%s-db')\n", pFile->zClass));
36572 if( pFile->szDb>0 && 0!=kvvfsWriteFileSize(pFile, pFile->szDb) ){
36581 ** Return the sector-size in bytes for an kvvfs-file.
36588 ** Return the device characteristic flags supported by an kvvfs-file.
36612 pFile->isJournal = 0;
36613 pFile->base.pMethods = &kvvfs_db_io_methods;
36615 if( strcmp(zName, "local-journal")==0
36616 || strcmp(zName, "session-journal")==0
36618 pFile->isJournal = 1;
36619 pFile->base.pMethods = &kvvfs_jrnl_io_methods;
36624 pFile->zClass = "session";
36626 pFile->zClass = "local";
36628 pFile->aJrnl = 0;
36629 pFile->nJrnl = 0;
36630 pFile->szPage = -1;
36631 pFile->szDb = -1;
36637 ** ensure the file-system modifications are synced to disk before
36641 if( strcmp(zPath, "local-journal")==0 ){
36644 if( strcmp(zPath, "session-journal")==0 ){
36661 if( strcmp(zPath, "local-journal")==0 ){
36664 if( strcmp(zPath, "session-journal")==0 ){
36697 if( nOut<nPath+1 ) nPath = nOut - 1;
36749 ** This routine is called initialize the KV-vfs as the default VFS.
36770 ** The author disclaims copyright to this source code. In place of
36779 ** This file contains the VFS implementation for unix-like operating systems
36785 ** use flock(), dot-files, various proprietary locking schemas, or simply
36788 ** This source file is organized into divisions where the logic for various
36795 ** * General-purpose declarations and utility functions.
36799 ** + for no-op locks
36800 ** + for dot-file locks
36808 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
36821 ** 3. Dot-file locking,
36880 ** -DHAVE_GETHOSTUUID=0
36881 ** -DHAVE_GETHOSTUUID=1
36884 ** -DSQLITE_ENABLE_LOCKING_STYLE.
36922 ** If we are to be thread-safe, include the pthreads header.
36943 ** Maximum supported path-length.
36965 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
36994 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
37021 ** transaction counter in bytes 24-27 of database files are updated
37086 ** The threadid macro resolves to the thread-id or to 0. Used for
37107 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
37108 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
37116 ** Linux-specific IOCTL magic numbers used for controlling F2FS
37134 ** which always has the same well-defined interface.
37145 ** Many system calls are accessed through pointer-to-functions so that
37174 ** DJGPP. But it is DOS - what did you expect?
37321 ** log if they come from non-root processes. So avoid calling fchown() if
37401 int i = -1;
37405 for(i=0; i<ArraySize(aSyscall)-1; i++){
37433 ** The m parameter will be non-zero only when creating -wal, -journal,
37434 ** and -shm files. We want those files to have *exactly* the same
37436 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
37461 fd = -1;
37526 ** integer lock-type.
37545 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
37546 ** command-line option on the compiler. This code is normally
37562 if( p->l_type==F_RDLCK ){
37564 }else if( p->l_type==F_WRLCK ){
37566 }else if( p->l_type==F_UNLCK ){
37571 assert( p->l_whence==SEEK_SET );
37575 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
37576 (int)p->l_pid, s);
37577 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
37590 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
37610 /* On Android, ftruncate() always uses 32-bit offsets, even if
37671 ** a performance-critical path, so it is sufficient to put these
37696 ** Changes are made in-place. Return the new name length.
37698 ** The original filename is in z[0..n-1]. Return the number of
37703 while( n>1 && z[n-1]=='/' ){ n--; }
37712 while( j>0 && z[j-1]!='/' ){ j--; }
37713 if( j>0 ){ j--; }
37744 pNew->zCanonicalName = (char*)&pNew[1];
37745 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
37746 n = vxworksSimplifyName(pNew->zCanonicalName, n);
37753 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
37754 if( pCandidate->nName==n
37755 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
37758 pCandidate->nRef++;
37765 pNew->nRef = 1;
37766 pNew->nName = n;
37767 pNew->pNext = vxworksFileList;
37779 assert( pId->nRef>0 );
37780 pId->nRef--;
37781 if( pId->nRef==0 ){
37783 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
37785 *pp = pId->pNext;
37843 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
37871 ** on linux - with NPTL a lock created by thread A can override locks
37872 ** in thread B. But there is no way to know at compile-time which
37874 ** compile-time whether or not thread A can override locks on thread B.
37875 ** One has to do a run-time check to discover the behavior of the
37895 ** sizes ino_t at only 32-bits instead of 64-bits. (See
37896 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
37897 ** To work around this, always allocate 64-bits for the inode number.
37898 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
37965 assert( pFile->pInode );
37966 return sqlite3_mutex_held(pFile->pInode->pLockMutex);
37969 assert( pFile->pInode );
37970 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex);
37976 ** This function - unixLogErrorAtLine(), is only ever called via the macro
37981 ** errno and, if possible, the human-readable equivalent from strerror() or
37987 ** failed (e.g. "unlink", "open") and the associated file-system path,
37995 int iLine /* Source line number where error occurred */
38001 ** the strerror() function to obtain the human-readable error message
38024 strerror_r(iErrno, aErr, sizeof(aErr)-1);
38030 /* Non-threadsafe build, use strerror(). */
38036 "os_unix.c:%d: (%d) %s(%s) - %s",
38059 pFile ? pFile->zPath : 0, lineno);
38064 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
38068 pFile->lastErrno = error;
38072 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
38075 unixInodeInfo *pInode = pFile->pInode;
38079 for(p=pInode->pUnused; p; p=pNext){
38080 pNext = p->pNext;
38081 robust_close(pFile, p->fd, __LINE__);
38084 pInode->pUnused = 0;
38094 unixInodeInfo *pInode = pFile->pInode;
38098 pInode->nRef--;
38099 if( pInode->nRef==0 ){
38100 assert( pInode->pShmNode==0 );
38101 sqlite3_mutex_enter(pInode->pLockMutex);
38103 sqlite3_mutex_leave(pInode->pLockMutex);
38104 if( pInode->pPrev ){
38105 assert( pInode->pPrev->pNext==pInode );
38106 pInode->pPrev->pNext = pInode->pNext;
38109 inodeList = pInode->pNext;
38111 if( pInode->pNext ){
38112 assert( pInode->pNext->pPrev==pInode );
38113 pInode->pNext->pPrev = pInode->pPrev;
38115 sqlite3_mutex_free(pInode->pLockMutex);
38137 struct stat statbuf; /* Low-level file information */
38142 /* Get low-level information about the file that we can used to
38145 fd = pFile->h;
38150 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
38157 ** incorrectly for zero-size files. See ticket #3260. To work
38166 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
38183 fileId.pId = pFile->pId;
38189 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
38190 pInode = pInode->pNext;
38198 memcpy(&pInode->fileId, &fileId, sizeof(fileId));
38200 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
38201 if( pInode->pLockMutex==0 ){
38206 pInode->nRef = 1;
38208 pInode->pNext = inodeList;
38209 pInode->pPrev = 0;
38210 if( inodeList ) inodeList->pPrev = pInode;
38213 pInode->nRef++;
38224 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
38227 return pFile->pInode!=0 &&
38228 (osStat(pFile->zPath, &buf)!=0
38229 || (u64)buf.st_ino!=pFile->pInode->fileId.ino);
38248 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
38250 rc = osFstat(pFile->h, &buf);
38252 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
38256 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
38260 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
38264 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
38273 ** to a non-zero value otherwise *pResOut is set to zero. The return value
38284 assert( pFile->eFileLock<=SHARED_LOCK );
38285 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
38288 if( pFile->pInode->eFileLock>SHARED_LOCK ){
38295 if( !reserved && !pFile->pInode->bProcessLock ){
38301 if( osFcntl(pFile->h, F_GETLK, &lock) ){
38310 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
38311 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
38321 ** Set a posix-advisory-lock.
38325 ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
38330 ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
38341 int tm = pFile->iBusyTimeout;
38351 tm--;
38359 ** Attempt to set a system-lock on the file pFile. The lock is
38362 ** If the pFile was opened read/write from unix-excl, then the only lock
38365 ** operations become no-ops. Locking operations still happen internally,
38370 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
38371 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
38372 ** and is read-only.
38374 ** Zero is returned if the call completes successfully, or -1 if a call
38379 unixInodeInfo *pInode = pFile->pInode;
38381 assert( sqlite3_mutex_held(pInode->pLockMutex) );
38382 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){
38383 if( pInode->bProcessLock==0 ){
38385 assert( pInode->nLock==0 );
38390 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile);
38392 pInode->bProcessLock = 1;
38393 pInode->nLock++;
38398 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile);
38404 ** Lock the file with the lock specified by parameter eFileLock - one
38418 ** UNLOCKED -> SHARED
38419 ** SHARED -> RESERVED
38420 ** SHARED -> (PENDING) -> EXCLUSIVE
38421 ** RESERVED -> (PENDING) -> EXCLUSIVE
38422 ** PENDING -> EXCLUSIVE
38430 ** lock primitives (called read-locks and write-locks below, to avoid
38439 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
38440 ** byte'. If this is successful, 'shared byte range' is read-locked
38443 ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
38445 ** Windows95 is now pretty much extinct, but this work-around for the
38446 ** lack of shared-locks on Windows95 lives on, for backwards
38450 ** A RESERVED lock is implemented by grabbing a write-lock on the
38454 ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
38462 ** implemented by obtaining a write-lock on the entire 'shared byte
38463 ** range'. Since all other locks require a read-lock on one of the bytes
38474 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
38475 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
38476 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
38483 if( pFile->eFileLock>=eFileLock ){
38484 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
38494 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
38496 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
38498 /* This mutex is needed because pFile->pInode is shared across threads
38500 pInode = pFile->pInode;
38501 sqlite3_mutex_enter(pInode->pLockMutex);
38506 if( (pFile->eFileLock!=pInode->eFileLock &&
38507 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
38518 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
38520 assert( pFile->eFileLock==0 );
38521 assert( pInode->nShared>0 );
38522 pFile->eFileLock = SHARED_LOCK;
38523 pInode->nShared++;
38524 pInode->nLock++;
38536 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
38555 assert( pInode->nShared==0 );
38556 assert( pInode->eFileLock==0 );
38559 /* Now get the read-lock */
38583 pFile->eFileLock = SHARED_LOCK;
38584 pInode->nLock++;
38585 pInode->nShared = 1;
38587 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
38596 assert( 0!=pFile->eFileLock );
38619 /* Set up the transaction-counter change checking flags when
38625 && pFile->eFileLock<=SHARED_LOCK
38628 pFile->transCntrChng = 0;
38629 pFile->dbUpdate = 0;
38630 pFile->inNormalWrite = 1;
38636 pFile->eFileLock = eFileLock;
38637 pInode->eFileLock = eFileLock;
38639 pFile->eFileLock = PENDING_LOCK;
38640 pInode->eFileLock = PENDING_LOCK;
38644 sqlite3_mutex_leave(pInode->pLockMutex);
38645 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
38655 unixInodeInfo *pInode = pFile->pInode;
38656 UnixUnusedFd *p = pFile->pPreallocatedUnused;
38658 p->pNext = pInode->pUnused;
38659 pInode->pUnused = p;
38660 pFile->h = -1;
38661 pFile->pPreallocatedUnused = 0;
38669 ** the requested locking level, this routine is a no-op.
38684 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
38685 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
38689 if( pFile->eFileLock<=eFileLock ){
38692 pInode = pFile->pInode;
38693 sqlite3_mutex_enter(pInode->pLockMutex);
38694 assert( pInode->nShared!=0 );
38695 if( pFile->eFileLock>SHARED_LOCK ){
38696 assert( pInode->eFileLock==pFile->eFileLock );
38707 pFile->inNormalWrite = 0;
38711 ** before establishing the readlock - to avoid a race condition we downgrade
38727 off_t divSize = SHARED_SIZE - 1;
38733 if( unixFileLock(pFile, &lock)==(-1) ){
38743 if( unixFileLock(pFile, &lock)==(-1) ){
38754 lock.l_len = SHARED_SIZE-divSize;
38755 if( unixFileLock(pFile, &lock)==(-1) ){
38786 pInode->eFileLock = SHARED_LOCK;
38798 pInode->nShared--;
38799 if( pInode->nShared==0 ){
38804 pInode->eFileLock = NO_LOCK;
38808 pInode->eFileLock = NO_LOCK;
38809 pFile->eFileLock = NO_LOCK;
38817 pInode->nLock--;
38818 assert( pInode->nLock>=0 );
38819 if( pInode->nLock==0 ) closePendingFds(pFile);
38823 sqlite3_mutex_leave(pInode->pLockMutex);
38825 pFile->eFileLock = eFileLock;
38835 ** the requested locking level, this routine is a no-op.
38839 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
38864 if( pFile->h>=0 ){
38865 robust_close(pFile, pFile->h, __LINE__);
38866 pFile->h = -1;
38869 if( pFile->pId ){
38870 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
38871 osUnlink(pFile->pId->zCanonicalName);
38873 vxworksReleaseFileId(pFile->pId);
38874 pFile->pId = 0;
38878 if( pFile->ctrlFlags & UNIXFILE_DELETE ){
38879 osUnlink(pFile->zPath);
38880 sqlite3_free(*(char**)&pFile->zPath);
38881 pFile->zPath = 0;
38884 OSTRACE(("CLOSE %-3d\n", pFile->h));
38885 OpenCounter(-1);
38886 sqlite3_free(pFile->pPreallocatedUnused);
38897 unixInodeInfo *pInode = pFile->pInode;
38908 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
38909 sqlite3_mutex_enter(pInode->pLockMutex);
38910 if( pInode->nLock ){
38913 ** descriptor to pInode->pUnused list. It will be automatically closed
38918 sqlite3_mutex_leave(pInode->pLockMutex);
38920 assert( pFile->pShm==0 );
38930 ****************************** No-op Locking **********************************
38936 ** This locking mode is appropriate for use on read-only databases
38937 ** (ex: databases that are burned into CD-ROM, for example.) It can
38967 /******************* End of the no-op lock implementation *********************
38971 ************************* Begin dot-file Locking ******************************
39001 ** to a non-zero value otherwise *pResOut is set to zero. The return value
39016 reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
39017 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
39023 ** Lock the file with the lock specified by parameter eFileLock - one
39037 ** UNLOCKED -> SHARED
39038 ** SHARED -> RESERVED
39039 ** SHARED -> (PENDING) -> EXCLUSIVE
39040 ** RESERVED -> (PENDING) -> EXCLUSIVE
39041 ** PENDING -> EXCLUSIVE
39051 char *zLockFile = (char *)pFile->lockingContext;
39058 if( pFile->eFileLock > NO_LOCK ){
39059 pFile->eFileLock = eFileLock;
39086 pFile->eFileLock = eFileLock;
39095 ** the requested locking level, this routine is a no-op.
39101 char *zLockFile = (char *)pFile->lockingContext;
39105 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
39106 pFile->eFileLock, osGetpid(0)));
39109 /* no-op if possible */
39110 if( pFile->eFileLock==eFileLock ){
39118 pFile->eFileLock = SHARED_LOCK;
39135 pFile->eFileLock = NO_LOCK;
39146 sqlite3_free(pFile->lockingContext);
39149 /****************** End of the dot-file lock implementation *******************
39157 ** flock() locking is like dot-file locking in that the various
39158 ** fine-grain locking levels supported by SQLite are collapsed into
39185 ** to a non-zero value otherwise *pResOut is set to zero. The return value
39198 if( pFile->eFileLock>SHARED_LOCK ){
39205 int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
39208 lrc = robust_flock(pFile->h, LOCK_UN);
39227 OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
39240 ** Lock the file with the lock specified by parameter eFileLock - one
39254 ** UNLOCKED -> SHARED
39255 ** SHARED -> RESERVED
39256 ** SHARED -> (PENDING) -> EXCLUSIVE
39257 ** RESERVED -> (PENDING) -> EXCLUSIVE
39258 ** PENDING -> EXCLUSIVE
39276 if (pFile->eFileLock > NO_LOCK) {
39277 pFile->eFileLock = eFileLock;
39283 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
39292 pFile->eFileLock = eFileLock;
39294 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
39310 ** the requested locking level, this routine is a no-op.
39316 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
39317 pFile->eFileLock, osGetpid(0)));
39320 /* no-op if possible */
39321 if( pFile->eFileLock==eFileLock ){
39327 pFile->eFileLock = eFileLock;
39332 if( robust_flock(pFile->h, LOCK_UN) ){
39338 pFile->eFileLock = NO_LOCK;
39362 ** Semaphore locking is like dot-lock and flock in that it really only
39372 ** to a non-zero value otherwise *pResOut is set to zero. The return value
39385 if( pFile->eFileLock>SHARED_LOCK ){
39391 sem_t *pSem = pFile->pInode->pSem;
39393 if( sem_trywait(pSem)==-1 ){
39400 reserved = (pFile->eFileLock < SHARED_LOCK);
39407 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
39414 ** Lock the file with the lock specified by parameter eFileLock - one
39428 ** UNLOCKED -> SHARED
39429 ** SHARED -> RESERVED
39430 ** SHARED -> (PENDING) -> EXCLUSIVE
39431 ** RESERVED -> (PENDING) -> EXCLUSIVE
39432 ** PENDING -> EXCLUSIVE
39444 sem_t *pSem = pFile->pInode->pSem;
39449 if (pFile->eFileLock > NO_LOCK) {
39450 pFile->eFileLock = eFileLock;
39456 if( sem_trywait(pSem)==-1 ){
39462 pFile->eFileLock = eFileLock;
39473 ** the requested locking level, this routine is a no-op.
39477 sem_t *pSem = pFile->pInode->pSem;
39481 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
39482 pFile->eFileLock, osGetpid(0)));
39485 /* no-op if possible */
39486 if( pFile->eFileLock==eFileLock ){
39492 pFile->eFileLock = eFileLock;
39497 if ( sem_post(pSem)==-1 ) {
39505 pFile->eFileLock = NO_LOCK;
39538 ** on Apple Macintosh computers - both OS9 and OSX.
39540 ** Third-party implementations of AFP are available. But this code here
39567 ** This is a utility for setting or clearing a bit-range lock on an
39586 pb.fd = pFile->h;
39589 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
39592 if ( err==-1 ) {
39615 ** to a non-zero value otherwise *pResOut is set to zero. The return value
39627 context = (afpLockingContext *) pFile->lockingContext;
39628 if( context->reserved ){
39632 sqlite3_mutex_enter(pFile->pInode->pLockMutex);
39634 if( pFile->pInode->eFileLock>SHARED_LOCK ){
39642 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
39646 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
39656 sqlite3_mutex_leave(pFile->pInode->pLockMutex);
39657 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
39664 ** Lock the file with the lock specified by parameter eFileLock - one
39678 ** UNLOCKED -> SHARED
39679 ** SHARED -> RESERVED
39680 ** SHARED -> (PENDING) -> EXCLUSIVE
39681 ** RESERVED -> (PENDING) -> EXCLUSIVE
39682 ** PENDING -> EXCLUSIVE
39690 unixInodeInfo *pInode = pFile->pInode;
39691 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
39694 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
39695 azFileLock(eFileLock), azFileLock(pFile->eFileLock),
39696 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
39702 if( pFile->eFileLock>=eFileLock ){
39703 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
39713 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
39715 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
39717 /* This mutex is needed because pFile->pInode is shared across threads
39719 pInode = pFile->pInode;
39720 sqlite3_mutex_enter(pInode->pLockMutex);
39725 if( (pFile->eFileLock!=pInode->eFileLock &&
39726 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
39737 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
39739 assert( pFile->eFileLock==0 );
39740 assert( pInode->nShared>0 );
39741 pFile->eFileLock = SHARED_LOCK;
39742 pInode->nShared++;
39743 pInode->nLock++;
39752 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
39755 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
39769 assert( pInode->nShared==0 );
39770 assert( pInode->eFileLock==0 );
39773 /* Now get the read-lock SHARED_LOCK */
39776 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
39777 lrc1 = afpSetLock(context->dbPath, pFile,
39778 SHARED_FIRST+pInode->sharedByte, 1, 1);
39780 lrc1Errno = pFile->lastErrno;
39783 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
39795 pFile->eFileLock = SHARED_LOCK;
39796 pInode->nLock++;
39797 pInode->nShared = 1;
39799 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
39809 assert( 0!=pFile->eFileLock );
39810 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
39812 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
39814 context->reserved = 1;
39823 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
39824 pInode->sharedByte, 1, 0)) ){
39827 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
39829 if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
39830 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
39848 pFile->eFileLock = eFileLock;
39849 pInode->eFileLock = eFileLock;
39851 pFile->eFileLock = PENDING_LOCK;
39852 pInode->eFileLock = PENDING_LOCK;
39856 sqlite3_mutex_leave(pInode->pLockMutex);
39857 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
39867 ** the requested locking level, this routine is a no-op.
39873 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
39876 int h = pFile->h;
39880 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
39881 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
39885 if( pFile->eFileLock<=eFileLock ){
39888 pInode = pFile->pInode;
39889 sqlite3_mutex_enter(pInode->pLockMutex);
39890 assert( pInode->nShared!=0 );
39891 if( pFile->eFileLock>SHARED_LOCK ){
39892 assert( pInode->eFileLock==pFile->eFileLock );
39894 SimulateIOError( h=(-1) )
39906 assert( pFile->inNormalWrite==0
39907 || pFile->dbUpdate==0
39908 || pFile->transCntrChng==1 );
39909 pFile->inNormalWrite = 0;
39912 if( pFile->eFileLock==EXCLUSIVE_LOCK ){
39913 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
39914 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
39915 /* only re-establish the shared lock if necessary */
39916 int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
39917 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
39922 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
39923 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
39925 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
39926 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
39928 context->reserved = 0;
39931 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
39932 pInode->eFileLock = SHARED_LOCK;
39941 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
39942 pInode->nShared--;
39943 if( pInode->nShared==0 ){
39945 SimulateIOError( h=(-1) )
39948 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
39951 pInode->eFileLock = NO_LOCK;
39952 pFile->eFileLock = NO_LOCK;
39956 pInode->nLock--;
39957 assert( pInode->nLock>=0 );
39958 if( pInode->nLock==0 ) closePendingFds(pFile);
39962 sqlite3_mutex_leave(pInode->pLockMutex);
39964 pFile->eFileLock = eFileLock;
39979 if( pFile->pInode ){
39980 unixInodeInfo *pInode = pFile->pInode;
39981 sqlite3_mutex_enter(pInode->pLockMutex);
39982 if( pInode->nLock ){
39985 ** descriptor to pInode->aPending. It will be automatically closed when
39990 sqlite3_mutex_leave(pInode->pLockMutex);
39993 sqlite3_free(pFile->lockingContext);
40003 ** is available. If you don't compile for a mac, then the "unix-afp"
40018 ** the requested locking level, this routine is a no-op.
40034 **************** Non-locking sqlite3_file methods *****************************
40064 assert( id->h>2 );
40067 got = osPread(id->h, pBuf, cnt, offset);
40068 SimulateIOError( got = -1 );
40070 got = osPread64(id->h, pBuf, cnt, offset);
40071 SimulateIOError( got = -1 );
40073 newOffset = lseek(id->h, offset, SEEK_SET);
40074 SimulateIOError( newOffset = -1 );
40077 return -1;
40079 got = osRead(id->h, pBuf, cnt);
40088 cnt -= got;
40095 OSTRACE(("READ %-3d %5d %7lld %llu\n",
40096 id->h, got+prior, offset-prior, TIMER_ELAPSED));
40117 /* If this is a database file (not a journal, super-journal or temp
40120 assert( pFile->pPreallocatedUnused==0
40129 if( offset<pFile->mmapSize ){
40130 if( offset+amt <= pFile->mmapSize ){
40131 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
40134 int nCopy = pFile->mmapSize - offset;
40135 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
40137 amt -= nCopy;
40147 /* pFile->lastErrno has been set by seekAndRead().
40154 switch( pFile->lastErrno ){
40168 /* Unread parts of the buffer must be zero-filled */
40169 memset(&((char*)pBuf)[got], 0, amt-got);
40175 ** Attempt to seek the file-descriptor passed as the first argument to
40177 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
40203 SimulateIOError( iSeek = -1 );
40205 rc = -1;
40213 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
40221 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
40228 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
40247 /* If this is a database file (not a journal, super-journal or temp
40250 assert( pFile->pPreallocatedUnused==0
40258 ** doing a hot-journal rollback or a write to some file other than a
40263 if( pFile->inNormalWrite ){
40264 pFile->dbUpdate = 1; /* The database has been modified */
40271 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
40272 pFile->transCntrChng = 1; /* The transaction counter has changed */
40281 if( offset<pFile->mmapSize ){
40282 if( offset+amt <= pFile->mmapSize ){
40283 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
40286 int nCopy = pFile->mmapSize - offset;
40287 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
40289 amt -= nCopy;
40296 amt -= wrote;
40300 SimulateIOError(( wrote=(-1), amt=1 ));
40304 if( wrote<0 && pFile->lastErrno!=ENOSPC ){
40329 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
40399 ** no-op. But go ahead and call fstat() to validate the file
40432 if( rc==-1 && errno==ENOTSUP ){
40438 if( OS_VXWORKS && rc!= -1 ){
40451 ** The directory file descriptor is used for only one thing - to
40460 ** replace this routine with a harmless no-op. To make this routine
40461 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
40469 int fd = -1;
40473 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
40482 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
40497 ** has been created by fsync-ing the directory that contains the file.
40502 ** will not roll back - possibly leading to database corruption.
40522 OSTRACE(("SYNC %-3d\n", pFile->h));
40523 rc = full_fsync(pFile->h, isFullsync, isDataOnly);
40527 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
40531 ** is set. This is a one-time occurrence. Many systems (examples: AIX)
40534 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
40536 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
40538 rc = osOpenDirectory(pFile->zPath, &dirfd);
40546 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
40560 /* If the user has configured a chunk-size for this file, truncate the
40565 if( pFile->szChunk>0 ){
40566 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
40569 rc = robust_ftruncate(pFile->h, nByte);
40572 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
40576 ** doing a hot-journal rollback or a write to some file other than a
40579 ** when restoring a database using the backup API from a zero-length
40580 ** source.
40582 if( pFile->inNormalWrite && nByte==0 ){
40583 pFile->transCntrChng = 1;
40592 if( nByte<pFile->mmapSize ){
40593 pFile->mmapSize = nByte;
40608 rc = osFstat(((unixFile*)id)->h, &buf);
40616 /* When opening a zero-size database, the findInodeInfo() procedure
40618 ** in the OS-X msdos filesystem. In order to avoid problems with upper
40630 ** Handler for proxy-locking file-control verbs. Defined below in the
40638 ** file-control operation. Enlarge the database to nBytes in size
40639 ** (rounded up to the next chunk-size). If the database is already
40640 ** nBytes or larger, this routine is a no-op.
40643 if( pFile->szChunk>0 ){
40647 if( osFstat(pFile->h, &buf) ){
40651 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
40660 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
40667 ** at offset (nSize-1), to set the size of the file correctly.
40671 int nBlk = buf.st_blksize; /* File-system block size */
40675 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
40678 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
40679 if( iWrite>=nSize ) iWrite = nSize - 1;
40688 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
40690 if( pFile->szChunk<=0 ){
40691 if( robust_ftruncate(pFile->h, nByte) ){
40693 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
40707 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
40709 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
40713 *pArg = (pFile->ctrlFlags & mask)!=0;
40715 pFile->ctrlFlags &= ~mask;
40717 pFile->ctrlFlags |= mask;
40735 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE);
40739 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE);
40743 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE);
40749 *(int*)pArg = pFile->eFileLock;
40753 *(int*)pArg = pFile->lastErrno;
40757 pFile->szChunk = *(int *)pArg;
40776 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
40780 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
40782 unixGetTempname(pFile->pVfs->mxPathname, zTFile);
40793 int iOld = pFile->iBusyTimeout;
40794 pFile->iBusyTimeout = *(int*)pArg;
40809 ** 64-bit type. */
40814 *(i64*)pArg = pFile->mmapSizeMax;
40815 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
40816 pFile->mmapSizeMax = newLimit;
40817 if( pFile->mmapSize>0 ){
40819 rc = unixMapfile(pFile, -1);
40832 ((unixFile*)id)->dbUpdate = 0;
40856 ** If pFd->sectorSize is non-zero when this function is called, it is a
40857 ** no-op. Otherwise, the values of pFd->sectorSize and
40858 ** pFd->deviceCharacteristics are set according to the file-system
40866 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 );
40867 if( pFd->sectorSize==0 ){
40873 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f);
40875 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC;
40880 if( pFd->ctrlFlags & UNIXFILE_PSOW ){
40881 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
40884 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
40891 if( pFile->sectorSize == 0 ){
40894 /* Set defaults for non-supported filesystems */
40895 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
40896 pFile->deviceCharacteristics = 0;
40897 if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
40902 pFile->sectorSize = fsInfo.f_bsize;
40903 pFile->deviceCharacteristics =
40911 pFile->sectorSize = fsInfo.f_bsize;
40912 pFile->deviceCharacteristics =
40914 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
40921 pFile->sectorSize = fsInfo.f_bsize;
40922 pFile->deviceCharacteristics =
40930 pFile->sectorSize = fsInfo.f_bsize;
40931 pFile->deviceCharacteristics =
40933 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
40938 pFile->sectorSize = fsInfo.f_bsize;
40939 pFile->deviceCharacteristics =
40941 ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
40946 pFile->deviceCharacteristics =
40955 if( pFile->sectorSize % 512 != 0 ){
40956 pFile->deviceCharacteristics = 0;
40957 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
40968 ** if two files are created in the same file-system directory (i.e.
40975 return pFd->sectorSize;
40984 ** words, after a power-loss event, parts of the file that were never
40985 ** written might end up being altered.) However, non-PSOW behavior is very,
40988 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
40994 return pFd->deviceCharacteristics;
41022 ** When multiple threads all reference the same wal-index, each thread
41024 ** of this unixShmNode object. In other words, each wal-index is opened
41039 ** The following fields are read-only after the object is created:
41053 int szRegion; /* Size of shared-memory regions */
41055 u8 isReadonly; /* True if read-only */
41057 char **apRegion; /* Array of mapped shared-memory regions */
41060 int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
41073 ** are read-only thereafter:
41078 ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
41084 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
41098 ** wal-mode transactions in other processes on database file pFile. If
41107 if( pFile->pShm){
41108 unixShmNode *pShmNode = pFile->pShm->pShmNode;
41115 f.l_len = SQLITE_SHM_NLOCK - 3;
41117 sqlite3_mutex_enter(pShmNode->pShmMutex);
41118 if( osFcntl(pShmNode->hShm, F_GETLK, &f)<0 ){
41123 sqlite3_mutex_leave(pShmNode->pShmMutex);
41131 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
41133 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
41142 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
41147 pShmNode = pFile->pInode->pShmNode;
41148 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) );
41149 assert( pShmNode->nRef>0 || unixMutexHeld() );
41157 if( pShmNode->hShm>=0 ){
41164 res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile);
41165 if( res==-1 ){
41167 rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY);
41177 OSTRACE(("SHM-LOCK "));
41178 mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
41182 pShmNode->exclMask &= ~mask;
41183 pShmNode->sharedMask &= ~mask;
41185 OSTRACE(("read-lock %d ok", ofst));
41186 pShmNode->exclMask &= ~mask;
41187 pShmNode->sharedMask |= mask;
41190 OSTRACE(("write-lock %d ok", ofst));
41191 pShmNode->exclMask |= mask;
41192 pShmNode->sharedMask &= ~mask;
41198 OSTRACE(("read-lock failed"));
41201 OSTRACE(("write-lock %d failed", ofst));
41204 OSTRACE((" - afterwards %03x,%03x\n",
41205 pShmNode->sharedMask, pShmNode->exclMask));
41215 ** current system page-size.
41218 ** to use 64KB pages - in this case each mapping must cover at least two
41224 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
41232 ** This is not a VFS shared-memory method; it is a utility function called
41233 ** by VFS shared-memory methods.
41236 unixShmNode *p = pFd->pInode->pShmNode;
41238 if( p && ALWAYS(p->nRef==0) ){
41241 assert( p->pInode==pFd->pInode );
41242 sqlite3_mutex_free(p->pShmMutex);
41243 for(i=0; i<p->nRegion; i+=nShmPerMap){
41244 if( p->hShm>=0 ){
41245 osMunmap(p->apRegion[i], p->szRegion);
41247 sqlite3_free(p->apRegion[i]);
41250 sqlite3_free(p->apRegion);
41251 if( p->hShm>=0 ){
41252 robust_close(pFd, p->hShm, __LINE__);
41253 p->hShm = -1;
41255 p->pInode->pShmNode = 0;
41267 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
41276 ** and proceed with opening the *-shm file.
41280 ** DMS byte and truncate the *-shm file to zero bytes in size. Then
41287 ** EXCLUSIVE failed just before truncating the *-shm file, then this
41288 ** process might open and use the *-shm file without truncating it.
41289 ** And if the *-shm file has been corrupted by a power failure or
41295 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) {
41298 if( pShmNode->isReadonly ){
41299 pShmNode->isUnlocked = 1;
41303 /* The first connection to attach must truncate the -shm file. We
41305 ** -shm header size) rather than 0 as a system debugging aid, to
41306 ** help detect if a -shm file truncation is legitimate or is the work
41308 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){
41309 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename);
41324 ** Open a shared-memory area associated with open database file pDbFd.
41327 ** The file used to implement shared-memory is in the same directory
41329 ** file with the "-shm" suffix added. For example, if the database file
41331 ** for shared memory will be called "/home/user1/config.db-shm".
41337 ** database to end up using different files for shared memory -
41338 ** meaning that their memory would not really be shared - resulting
41340 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
41341 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
41345 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
41348 ** When opening a new shared-memory file, if no other instances of that
41352 ** If the original database file (pDbFd) is using the "unix-excl" VFS
41370 assert( pDbFd->pShm==0 );
41377 pInode = pDbFd->pInode;
41378 pShmNode = pInode->pShmNode;
41382 const char *zBasePath = pDbFd->zPath;
41386 ** a new *-shm file is created, an attempt will be made to create it
41389 if( osFstat(pDbFd->h, &sStat) ){
41405 zShm = pShmNode->zFilename = (char*)&pShmNode[1];
41408 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
41411 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath);
41412 sqlite3FileSuffix3(pDbFd->zPath, zShm);
41414 pShmNode->hShm = -1;
41415 pDbFd->pInode->pShmNode = pShmNode;
41416 pShmNode->pInode = pDbFd->pInode;
41418 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
41419 if( pShmNode->pShmMutex==0 ){
41425 if( pInode->bProcessLock==0 ){
41426 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
41427 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW,
41430 if( pShmNode->hShm<0 ){
41431 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW,
41433 if( pShmNode->hShm<0 ){
41437 pShmNode->isReadonly = 1;
41444 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid);
41452 p->pShmNode = pShmNode;
41454 p->id = pShmNode->nextShmId++;
41456 pShmNode->nRef++;
41457 pDbFd->pShm = p;
41464 ** at pShmNode->pFirst. This must be done while holding the
41465 ** pShmNode->pShmMutex.
41467 sqlite3_mutex_enter(pShmNode->pShmMutex);
41468 p->pNext = pShmNode->pFirst;
41469 pShmNode->pFirst = p;
41470 sqlite3_mutex_leave(pShmNode->pShmMutex);
41483 ** shared-memory associated with the database file fd. Shared-memory regions
41484 ** are numbered starting from zero. Each shared-memory region is szRegion
41489 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
41492 ** bExtend is non-zero and the requested shared-memory region has not yet
41495 ** If the shared-memory region has already been allocated or is allocated by
41514 /* If the shared-memory file has not yet been opened, open it now. */
41515 if( pDbFd->pShm==0 ){
41520 p = pDbFd->pShm;
41521 pShmNode = p->pShmNode;
41522 sqlite3_mutex_enter(pShmNode->pShmMutex);
41523 if( pShmNode->isUnlocked ){
41526 pShmNode->isUnlocked = 0;
41528 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
41529 assert( pShmNode->pInode==pDbFd->pInode );
41530 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
41531 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
41536 if( pShmNode->nRegion<nReqRegion ){
41541 pShmNode->szRegion = szRegion;
41543 if( pShmNode->hShm>=0 ){
41545 ** Check to see if it has been allocated (i.e. if the wal-index file is
41548 if( osFstat(pShmNode->hShm, &sStat) ){
41576 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){
41577 const char *zFile = pShmNode->zFilename;
41588 pShmNode->apRegion, nReqRegion*sizeof(char *)
41594 pShmNode->apRegion = apNew;
41595 while( pShmNode->nRegion<nReqRegion ){
41599 if( pShmNode->hShm>=0 ){
41601 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
41602 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion
41605 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
41618 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
41620 pShmNode->nRegion += nShmPerMap;
41625 if( pShmNode->nRegion>iRegion ){
41626 *pp = pShmNode->apRegion[iRegion];
41630 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
41631 sqlite3_mutex_leave(pShmNode->pShmMutex);
41636 ** Check that the pShmNode->aLock[] array comports with the locking bitmasks
41646 assert( sqlite3_mutex_held(pShmNode->pShmMutex) );
41649 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
41652 if( pX->exclMask & (1<<i) ){
41654 aLock[i] = -1;
41655 }else if( pX->sharedMask & (1<<i) ){
41662 assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) );
41663 return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0);
41668 ** Change the lock state for a shared-memory segment.
41688 p = pDbFd->pShm;
41690 pShmNode = p->pShmNode;
41692 aLock = pShmNode->aLock;
41694 assert( pShmNode==pDbFd->pInode->pShmNode );
41695 assert( pShmNode->pInode==pDbFd->pInode );
41703 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 );
41704 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 );
41720 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
41722 && (ofst!=1 || (p->exclMask|p->sharedMask)==0)
41723 && (ofst!=0 || (p->exclMask|p->sharedMask)<3)
41724 && (ofst<3 || (p->exclMask|p->sharedMask)<(1<<ofst))
41728 mask = (1<<(ofst+n)) - (1<<ofst);
41730 sqlite3_mutex_enter(pShmNode->pShmMutex);
41733 if( (p->exclMask|p->sharedMask) & mask ){
41738 if( aLock[ii]>((p->sharedMask & (1<<ii)) ? 1 : 0) ){
41748 }else if( ALWAYS(p->sharedMask & (1<<ofst)) ){
41750 aLock[ofst]--;
41755 p->exclMask &= ~mask;
41756 p->sharedMask &= ~mask;
41761 assert( (p->exclMask & (1<<ofst))==0 );
41762 if( (p->sharedMask & mask)==0 ){
41771 p->sharedMask |= mask;
41780 assert( (p->sharedMask & mask)==0 );
41781 if( ALWAYS((p->exclMask & (1<<ii))==0) && aLock[ii] ){
41788 ** also update the in-memory values. */
41792 assert( (p->sharedMask & mask)==0 );
41793 p->exclMask |= mask;
41795 aLock[ii] = -1;
41801 sqlite3_mutex_leave(pShmNode->pShmMutex);
41802 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
41803 p->id, osGetpid(0), p->sharedMask, p->exclMask));
41817 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
41818 assert( fd->pMethods->xLock==nolockLock
41826 ** Close a connection to shared-memory. Delete the underlying
41830 ** routine is a harmless no-op.
41834 int deleteFlag /* Delete shared-memory if true */
41837 unixShmNode *pShmNode; /* The underlying shared-memory file */
41842 p = pDbFd->pShm;
41844 pShmNode = p->pShmNode;
41846 assert( pShmNode==pDbFd->pInode->pShmNode );
41847 assert( pShmNode->pInode==pDbFd->pInode );
41851 sqlite3_mutex_enter(pShmNode->pShmMutex);
41852 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
41853 *pp = p->pNext;
41857 pDbFd->pShm = 0;
41858 sqlite3_mutex_leave(pShmNode->pShmMutex);
41860 /* If pShmNode->nRef has reached 0, then close the underlying
41861 ** shared-memory file, too */
41864 assert( pShmNode->nRef>0 );
41865 pShmNode->nRef--;
41866 if( pShmNode->nRef==0 ){
41867 if( deleteFlag && pShmNode->hShm>=0 ){
41868 osUnlink(pShmNode->zFilename);
41890 assert( pFd->nFetchOut==0 );
41891 if( pFd->pMapRegion ){
41892 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
41893 pFd->pMapRegion = 0;
41894 pFd->mmapSize = 0;
41895 pFd->mmapSizeActual = 0;
41919 int h = pFd->h; /* File descriptor open on db file */
41920 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
41921 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
41925 assert( pFd->nFetchOut==0 );
41926 assert( nNew>pFd->mmapSize );
41927 assert( nNew<=pFd->mmapSizeMax );
41929 assert( pFd->mmapSizeActual>=pFd->mmapSize );
41933 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
41938 i64 nReuse = pFd->mmapSize;
41941 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
41947 osMunmap(pReq, nOrig-nReuse);
41954 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
41957 osMunmap(pNew, nNew - nReuse);
41979 unixLogError(SQLITE_OK, zErr, pFd->zPath);
41984 pFd->mmapSizeMax = 0;
41986 pFd->pMapRegion = (void *)pNew;
41987 pFd->mmapSize = pFd->mmapSizeActual = nNew;
41991 ** Memory map or remap the file opened by file-descriptor pFd (if the file
41994 ** outstanding xFetch() references to it, this function is a no-op.
41996 ** If parameter nByte is non-negative, then it is the requested size of
42007 assert( nMap>=0 || pFd->nFetchOut==0 );
42008 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
42009 if( pFd->nFetchOut>0 ) return SQLITE_OK;
42012 struct stat statbuf; /* Low-level file information */
42013 if( osFstat(pFd->h, &statbuf) ){
42018 if( nMap>pFd->mmapSizeMax ){
42019 nMap = pFd->mmapSizeMax;
42022 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
42023 if( nMap!=pFd->mmapSize ){
42050 if( pFd->mmapSizeMax>0 ){
42051 if( pFd->pMapRegion==0 ){
42052 int rc = unixMapfile(pFd, -1);
42055 if( pFd->mmapSize >= iOff+nAmt ){
42056 *pp = &((u8 *)pFd->pMapRegion)[iOff];
42057 pFd->nFetchOut++;
42065 ** If the third argument is non-NULL, then this function releases a
42082 assert( (p==0)==(pFd->nFetchOut==0) );
42085 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
42088 pFd->nFetchOut--;
42093 assert( pFd->nFetchOut>=0 );
42111 ** of "finder" functions. A finder-function is used to locate the appropriate
42114 ** the correct finder-function for that VFS.
42117 ** object. The only interesting finder-function is autolockIoFinder, which
42121 ** For finder-function F, two objects are created:
42123 ** (1) The real finder-function named "FImpt()".
42130 ** directly at the finder-function since C90 rules prevent a void*
42247 ** The proxy locking method is a "super-method" in the sense that it
42249 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
42318 if( statfs(filePath, &fsInfo) != -1 ){
42330 ** Test byte-range lock using fcntl(). If the call succeeds,
42331 ** assume that the file-system supports POSIX style locks.
42337 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
42377 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
42415 assert( pNew->pInode==NULL );
42420 OSTRACE(("OPEN %-3d %s\n", h, zFilename));
42421 pNew->h = h;
42422 pNew->pVfs = pVfs;
42423 pNew->zPath = zFilename;
42424 pNew->ctrlFlags = (u8)ctrlFlags;
42426 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
42430 pNew->ctrlFlags |= UNIXFILE_PSOW;
42432 if( strcmp(pVfs->zName,"unix-excl")==0 ){
42433 pNew->ctrlFlags |= UNIXFILE_EXCL;
42437 pNew->pId = vxworksFindFileId(zFilename);
42438 if( pNew->pId==0 ){
42447 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
42452 pNew->lockingContext = (void*)zFilename;
42462 rc = findInodeInfo(pNew, &pNew->pInode);
42475 ** handle h - as it is guaranteed that no posix locks will be released
42483 h = -1;
42494 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
42501 pCtx->dbPath = zFilename;
42502 pCtx->reserved = 0;
42505 rc = findInodeInfo(pNew, &pNew->pInode);
42507 sqlite3_free(pNew->lockingContext);
42509 h = -1;
42530 pNew->lockingContext = zLockFile;
42539 rc = findInodeInfo(pNew, &pNew->pInode);
42540 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
42541 char *zSemName = pNew->pInode->aSemName;
42544 pNew->pId->zCanonicalName);
42547 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
42548 if( pNew->pInode->pSem == SEM_FAILED ){
42550 pNew->pInode->aSemName[0] = '\0';
42561 h = -1;
42563 pNew->ctrlFlags |= UNIXFILE_DELETE;
42569 pId->pMethods = pLockingStyle;
42622 ** pVfs->mxPathname bytes.
42629 /* It's odd to simulate an io-error here, but really this is just
42630 ** using the io-error infrastructure to test that SQLite handles this
42645 zBuf[nBuf-2] = 0;
42648 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ){
42660 ** Routine to transform a unixFile into a proxy-locking unixFile.
42661 ** Implementation in the proxy-lock division, but used by unixOpen()
42669 ** file (not a journal or super-journal file) identified by pathname
42675 ** other file descriptor open on the same file is holding a file-lock.
42681 ** such file descriptor is located, -1 is returned.
42699 ** ignored and -1 is returned. The caller will try to open a new file
42708 while( pInode && (pInode->fileId.dev!=sStat.st_dev
42709 || pInode->fileId.ino!=(u64)sStat.st_ino) ){
42710 pInode = pInode->pNext;
42714 assert( sqlite3_mutex_notheld(pInode->pLockMutex) );
42715 sqlite3_mutex_enter(pInode->pLockMutex);
42717 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
42720 *pp = pUnused->pNext;
42722 sqlite3_mutex_leave(pInode->pLockMutex);
42762 ** this function queries the file-system for the permissions on the
42791 ** "<path to db>-journal"
42792 ** "<path to db>-wal"
42793 ** "<path to db>-journalNN"
42794 ** "<path to db>-walNN"
42800 ** a '-' character. However in 8+3 filename mode, or if a corrupt
42801 ** rollback journal specifies a super-journal with a goofy name, then
42802 ** the '-' might be missing or the '-' might be the first character in
42805 nDb = sqlite3Strlen30(zPath) - 1;
42807 if( zPath[nDb]=='-' ){
42813 nDb--;
42842 ** ReadWrite() -> (READWRITE | CREATE)
42843 ** ReadOnly() -> (READONLY)
42844 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
42846 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
42860 int fd = -1; /* File descriptor returned by open() */
42879 /* If creating a super- or main-file journal, this function will open
42880 ** a file-descriptor on the directory too. The first time unixSync()
42907 /* The main DB, main journal, WAL file and super-journal are never
42914 /* Assert that the upper layer has set one of the "file-type" flags. */
42941 fd = pUnused->fd;
42948 p->pPreallocatedUnused = pUnused;
42950 /* Database filenames are double-zero terminated if they are not
42958 rc = unixGetTempname(pVfs->mxPathname, zTmpname);
42964 /* Generated temporary filenames are always double-zero terminated
42985 assert( !p->pPreallocatedUnused );
42990 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
42998 /* Failed to open the file for read/write access. Try read-only. */
43015 ** the case. The chown() system call will be a no-op if the current
43034 if( p->pPreallocatedUnused ){
43035 p->pPreallocatedUnused->fd = fd;
43036 p->pPreallocatedUnused->flags =
43055 p->openFlags = openFlags;
43060 if( fstatfs(fd, &fsInfo) == -1 ){
43066 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
43069 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
43085 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
43090 ** never use proxy, NULL means use proxy for non-local files only. */
43103 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
43121 sqlite3_free(p->pPreallocatedUnused);
43139 if( osUnlink(zPath)==(-1) ){
43204 ** If the last component of the pathname in z[0]..z[j-1] is something
43212 for(i=j-1; i>0 && z[i-1]!='/'; i--){}
43214 if( z[i]=='.' && i==j-2 && z[i+1]=='.' ) return 0;
43215 *pJ = i-1;
43235 if( osGetcwd(zOut, nOut-2)==0 ){
43242 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
43247 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
43288 ** is stored as a nul-terminated string in the buffer pointed to by
43292 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
43310 assert( pVfs->mxPathname==MAX_PATHNAME );
43313 /* It's odd to simulate an io-error here, but really this is just
43314 ** using the io-error infrastructure to test that SQLite handles this
43344 nByte = osReadlink(zIn, zDel, nOut-1);
43350 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
43410 ** GCC with -pedantic-errors says that C90 does not allow a void* to be
43413 ** use dlsym() with -pedantic-errors?
43421 ** This work-around is unlikely to work correctly on any system where
43450 ** errors. The reports issued by valgrind are incorrect - we would
43452 ** uninitialized space in zBuf - but valgrind errors tend to worry
43515 ** The following variable, if set to a non-zero value, is interpreted as
43579 ** low-level error message when operating-system problems come up
43598 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
43600 ** meta-layer over top of the primitive locking implemented above. For
43603 ** been defined - so that the primitive locking methods are available
43608 ** The default locking schemes in SQLite use byte-range locks on the
43613 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
43621 ** SHARED_RANGE 0x40000002 -> 0x40000200
43625 ** the read cache when byte-range locks are present. Enabling the read
43628 ** close-to-open semantics for ensuring cache coherency
43632 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
43641 ** -----------------
43673 ** -----------------------
43683 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
43684 ** by taking an sqlite-style shared lock on the conch file, reading the
43688 ** is patterned after the database file name as ".<databasename>-conch".
43696 ** The proxy file - a single-byte file used for all advisory file locks
43712 ** ---------------------
43716 ** Database files accessed on non-local file systems are
43761 int conchHeld; /* 1 if the conch is held, -1 if lockless */
43794 if( lPath[len-1]!='/' ){
43823 if( lockPath[i] == '/' && (i - start > 0) ){
43825 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
43826 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
43858 int fd = -1;
43867 ** 2. if that fails, and this is a lock file (not-conch), try creating
43869 ** 3. if that fails, try to open the file read-only
43874 fd = pUnused->fd;
43915 pNew->openFlags = openFlags;
43919 pUnused->fd = fd;
43920 pUnused->flags = openFlags;
43921 pNew->pPreallocatedUnused = pUnused;
43979 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
43991 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
43992 unixFile *conchFile = pCtx->conchFile;
43995 char *cPath = pCtx->conchFilePath;
43999 int fd = -1;
44000 int rc = -1;
44003 /* create a new path by replace the trailing '-conch' with '-break' */
44006 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
44011 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
44032 robust_close(pFile, conchFile->h, __LINE__);
44033 conchFile->h = fd;
44034 conchFile->openFlags = O_RDWR | O_CREAT;
44051 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
44052 unixFile *conchFile = pCtx->conchFile;
44059 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
44069 if( osFstat(conchFile->h, &buf) ){
44088 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
44110 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
44113 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
44123 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
44129 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
44131 if( pCtx->conchHeld!=0 ){
44134 unixFile *conchFile = pCtx->conchFile;
44147 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
44148 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
44164 storeLastErrno(pFile, conchFile->lastErrno);
44176 ** retry with a new auto-generated path
44184 if( !pCtx->lockProxyPath ){
44185 /* for auto-named local lock file, just check the host ID and we'll
44189 size_t pathLen = (readLen - PROXY_PATHINDEX);
44192 pathLen=MAXPATHLEN-1;
44202 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
44203 readLen-PROXY_PATHINDEX)
44211 if( (conchFile->openFlags&O_RDWR) == 0 ){
44217 if( !pCtx->lockProxyPath ){
44218 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
44227 futimes(conchFile->h, NULL);
44229 if( conchFile->pInode && conchFile->pInode->nShared>1 ){
44245 if( pCtx->lockProxyPath!=NULL ){
44246 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
44252 robust_ftruncate(conchFile->h, writeSize);
44254 full_fsync(conchFile->h,0,0);
44260 int err = osFstat(pFile->h, &buf);
44266 osFchmod(conchFile->h, cmode);
44269 rc = osFchmod(conchFile->h, cmode);
44270 }while( rc==(-1) && errno==EINTR );
44286 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
44289 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
44290 if( rc==SQLITE_OK && pFile->openFlags ){
44292 if( pFile->h>=0 ){
44293 robust_close(pFile, pFile->h, __LINE__);
44295 pFile->h = -1;
44296 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
44299 pFile->h = fd;
44305 if( rc==SQLITE_OK && !pCtx->lockProxy ){
44306 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
44307 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
44310 ** so try again via auto-naming
44322 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
44323 if( !pCtx->lockProxyPath ){
44329 pCtx->conchHeld = 1;
44331 if( pCtx->lockProxy->pMethod == &afpIoMethods ){
44333 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
44334 afpCtx->dbPath = pCtx->lockProxyPath;
44337 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
44339 OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
44342 } while (1); /* in case we need to retry the :auto: lock file -
44355 pCtx = (proxyLockingContext *)pFile->lockingContext;
44356 conchFile = pCtx->conchFile;
44357 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
44358 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
44360 if( pCtx->conchHeld>0 ){
44361 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
44363 pCtx->conchHeld = 0;
44364 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
44382 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
44394 for( i=(len-1); i>=0; i-- ){
44406 /* append the "-conch" suffix to the file */
44407 memcpy(&conchPath[i+1], "-conch", 7);
44414 /* Takes a fully configured proxy locking-style unix file and switches
44418 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
44419 char *oldPath = pCtx->lockProxyPath;
44422 if( pFile->eFileLock!=NO_LOCK ){
44431 unixFile *lockProxy = pCtx->lockProxy;
44432 pCtx->lockProxy=NULL;
44433 pCtx->conchHeld = 0;
44435 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
44440 pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
44455 if( pFile->pMethod == &afpIoMethods ){
44458 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
44459 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
44463 if( pFile->pMethod == &dotlockIoMethods ){
44466 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
44467 memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
44470 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
44471 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
44481 ** ->lockingContext
44482 ** ->pMethod
44490 if( pFile->eFileLock!=NO_LOCK ){
44500 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
44509 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
44511 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
44512 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
44514 ** (c) the file system is read-only, then enable no-locking access.
44522 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
44524 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
44529 pCtx->conchHeld = -1; /* read only FS/ lockless */
44535 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
44539 pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
44540 if( pCtx->dbPath==NULL ){
44548 pCtx->oldLockingContext = pFile->lockingContext;
44549 pFile->lockingContext = pCtx;
44550 pCtx->pOldMethod = pFile->pMethod;
44551 pFile->pMethod = &proxyIoMethods;
44553 if( pCtx->conchFile ){
44554 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
44555 sqlite3_free(pCtx->conchFile);
44557 sqlite3DbFree(0, pCtx->lockProxyPath);
44558 sqlite3_free(pCtx->conchFilePath);
44561 OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
44575 if( pFile->pMethod == &proxyIoMethods ){
44576 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
44578 if( pCtx->lockProxyPath ){
44579 *(const char **)pArg = pCtx->lockProxyPath;
44591 int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
44594 /* turn off proxy locking - not supported. If support is added for
44600 /* turn off proxy locking - already off - NOOP */
44607 (proxyLockingContext*)pFile->lockingContext;
44609 || (pCtx->lockProxyPath &&
44610 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
44633 ** above this point are all utilities. The lock-related methods of the
44634 ** proxy-locking sqlite3_io_method object follow.
44641 ** to a non-zero value otherwise *pResOut is set to zero. The return value
44648 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
44649 if( pCtx->conchHeld>0 ){
44650 unixFile *proxy = pCtx->lockProxy;
44651 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
44660 ** Lock the file with the lock specified by parameter eFileLock - one
44674 ** UNLOCKED -> SHARED
44675 ** SHARED -> RESERVED
44676 ** SHARED -> (PENDING) -> EXCLUSIVE
44677 ** RESERVED -> (PENDING) -> EXCLUSIVE
44678 ** PENDING -> EXCLUSIVE
44687 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
44688 if( pCtx->conchHeld>0 ){
44689 unixFile *proxy = pCtx->lockProxy;
44690 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
44691 pFile->eFileLock = proxy->eFileLock;
44705 ** the requested locking level, this routine is a no-op.
44711 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
44712 if( pCtx->conchHeld>0 ){
44713 unixFile *proxy = pCtx->lockProxy;
44714 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
44715 pFile->eFileLock = proxy->eFileLock;
44729 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
44730 unixFile *lockProxy = pCtx->lockProxy;
44731 unixFile *conchFile = pCtx->conchFile;
44735 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
44737 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
44740 pCtx->lockProxy = 0;
44743 if( pCtx->conchHeld ){
44747 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
44751 sqlite3DbFree(0, pCtx->lockProxyPath);
44752 sqlite3_free(pCtx->conchFilePath);
44753 sqlite3DbFree(0, pCtx->dbPath);
44755 pFile->lockingContext = pCtx->oldLockingContext;
44756 pFile->pMethod = pCtx->pOldMethod;
44758 return pFile->pMethod->xClose(id);
44778 ** This routine registers all VFS implementations for unix-like operating
44795 ** when compiling with -pedantic-errors on GCC.)
44798 ** finder-function. The finder-function returns a pointer to the
44801 ** macro for addition information on finder-functions.
44849 UNIXVFS("unix-none", nolockIoFinder ),
44850 UNIXVFS("unix-dotfile", dotlockIoFinder ),
44851 UNIXVFS("unix-excl", posixIoFinder ),
44853 UNIXVFS("unix-namedsem", semIoFinder ),
44856 UNIXVFS("unix-posix", posixIoFinder ),
44859 UNIXVFS("unix-flock", flockIoFinder ),
44862 UNIXVFS("unix-afp", afpIoFinder ),
44863 UNIXVFS("unix-nfs", nfsIoFinder ),
44864 UNIXVFS("unix-proxy", proxyIoFinder ),
44869 /* Double-check that the aSyscall[] array has been constructed
44895 ** READ-0 UNIX_SHM_BASE+3 123
44896 ** READ-1 UNIX_SHM_BASE+4 124
44897 ** READ-2 UNIX_SHM_BASE+5 125
44898 ** READ-3 UNIX_SHM_BASE+6 126
44899 ** READ-4 UNIX_SHM_BASE+7 127
44902 assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */
44916 ** This routine is a no-op for unix.
44930 ** The author disclaims copyright to this source code. In place of
44970 ** based on the sub-platform)?
44978 ** based on the sub-platform)?
45066 ** characters, so we allocate 4 bytes per character assuming worst-case of
45067 ** 4-bytes-per-character for UTF8.
45090 ** Returns non-zero if the character should be treated as a directory
45154 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
45167 typedef struct winShm winShm; /* A connection to shared-memory */
45168 typedef struct winShmNode winShmNode; /* A region of shared-memory */
45226 BOOL bNoLock; /* Non-zero if locking is disabled. */
45240 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
45250 * If this is non-zero, an isolated heap will be created by the native Win32
45256 * WARNING: It is important to note that when this setting is non-zero and the
45268 * This is the maximum possible initial size of the Win32-specific heap, in
45276 * This is the extra space for the initial size of the Win32-specific heap,
45289 # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
45296 * Win32-specific heap. It cannot be negative.
45302 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
45308 * initial size of the Win32-specific heap to exceed the maximum amount
45317 * The initial size of the Win32-specific heap. This value may be zero.
45326 * The maximum size of the Win32-specific heap. This value may be zero.
45342 ** The winMemData structure stores information required by the Win32-specific
45426 ** Many system calls are accessed through pointer-to-functions so that
46043 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
46155 int i = -1;
46159 for(i=0; i<ArraySize(aSyscall)-1; i++){
46174 ** "pnLargest" argument, if non-zero, will be used to return the size of the
46264 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
46265 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
46266 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
46332 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
46360 ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
46385 ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
46480 if( n==(SIZE_T)-1 ){
46502 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
46503 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
46506 if( !pWinMemData->hHeap ){
46514 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
46516 if( !pWinMemData->hHeap ){
46523 pWinMemData->bOwned = TRUE;
46524 assert( pWinMemData->bOwned );
46527 pWinMemData->hHeap = osGetProcessHeap();
46528 if( !pWinMemData->hHeap ){
46533 pWinMemData->bOwned = FALSE;
46534 assert( !pWinMemData->bOwned );
46536 assert( pWinMemData->hHeap!=0 );
46537 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
46539 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
46551 assert( pWinMemData->magic1==WINMEM_MAGIC1 );
46552 assert( pWinMemData->magic2==WINMEM_MAGIC2 );
46554 if( pWinMemData->hHeap ){
46555 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
46557 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
46559 if( pWinMemData->bOwned ){
46560 if( !osHeapDestroy(pWinMemData->hHeap) ){
46562 osGetLastError(), (void*)pWinMemData->hHeap);
46564 pWinMemData->bOwned = FALSE;
46566 pWinMemData->hHeap = NULL;
46571 ** Populate the low-level memory allocation function pointers in
46598 ** Convert a UTF-8 string to Microsoft Unicode.
46606 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
46614 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
46624 ** Convert a Microsoft Unicode string to UTF-8.
46632 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
46640 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
46660 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
46669 nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
46679 ** Convert a Microsoft Unicode string to a multi-byte character string,
46689 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
46697 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
46707 ** Convert a multi-byte character string to UTF-8.
46725 ** Convert a UTF-8 string to a multi-byte character string.
46840 ** it accepts a UTF-8 string.
46884 ** it accepts a UTF-16 string.
46917 ** is zero if the error message fits in the buffer, or non-zero
46997 ** This function - winLogErrorAtLine() - is only ever called via the macro
47002 ** error code and, if possible, the human-readable equivalent from
47008 ** failed and the associated file-system path, if any.
47016 int iLine /* Source line number where error occurred */
47028 "os_win.c:%d: (%lu) %s(%s) - %s",
47037 ** will be retried following a locking error - probably caused by
47054 ** non-zero if the error code is transient in nature and the operation
47142 y.tm_year = pTm.wYear - 1900;
47143 y.tm_mon = pTm.wMonth - 1;
47157 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
47191 memset(&pFile->local, 0, sizeof(pFile->local));
47201 pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
47202 if (!pFile->hMutex){
47203 pFile->lastErrno = osGetLastError();
47205 return winLogError(SQLITE_IOERR, pFile->lastErrno,
47210 winceMutexAcquire(pFile->hMutex);
47213 ** case-sensitive, take advantage of that by uppercasing the mutex name
47217 pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
47222 ** must be zero-initialized */
47231 if( pFile->hShared ){
47232 pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
47235 if( !pFile->shared ){
47236 pFile->lastErrno = osGetLastError();
47237 winLogError(SQLITE_IOERR, pFile->lastErrno,
47240 osCloseHandle(pFile->hShared);
47241 pFile->hShared = NULL;
47246 if( pFile->hShared==NULL ){
47248 pFile->lastErrno = lastErrno;
47249 winLogError(SQLITE_IOERR, pFile->lastErrno,
47253 winceMutexRelease(pFile->hMutex);
47254 osCloseHandle(pFile->hMutex);
47255 pFile->hMutex = NULL;
47261 memset(pFile->shared, 0, sizeof(winceLock));
47264 winceMutexRelease(pFile->hMutex);
47272 if (pFile->hMutex){
47274 winceMutexAcquire(pFile->hMutex);
47278 if (pFile->local.nReaders){
47279 pFile->shared->nReaders --;
47281 if (pFile->local.bReserved){
47282 pFile->shared->bReserved = FALSE;
47284 if (pFile->local.bPending){
47285 pFile->shared->bPending = FALSE;
47287 if (pFile->local.bExclusive){
47288 pFile->shared->bExclusive = FALSE;
47291 /* De-reference and close our copy of the shared memory handle */
47292 osUnmapViewOfFile(pFile->shared);
47293 osCloseHandle(pFile->hShared);
47296 winceMutexRelease(pFile->hMutex);
47297 osCloseHandle(pFile->hMutex);
47298 pFile->hMutex = NULL;
47318 if (!pFile->hMutex) return TRUE;
47319 winceMutexAcquire(pFile->hMutex);
47324 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
47325 pFile->shared->bExclusive = TRUE;
47326 pFile->local.bExclusive = TRUE;
47331 /* Want a read-only lock? */
47334 if (pFile->shared->bExclusive == 0){
47335 pFile->local.nReaders ++;
47336 if (pFile->local.nReaders == 1){
47337 pFile->shared->nReaders ++;
47347 if (pFile->shared->bPending == 0) {
47348 pFile->shared->bPending = TRUE;
47349 pFile->local.bPending = TRUE;
47357 if (pFile->shared->bReserved == 0) {
47358 pFile->shared->bReserved = TRUE;
47359 pFile->local.bReserved = TRUE;
47364 winceMutexRelease(pFile->hMutex);
47384 if (!pFile->hMutex) return TRUE;
47385 winceMutexAcquire(pFile->hMutex);
47390 if (pFile->local.bExclusive){
47392 pFile->local.bExclusive = FALSE;
47393 pFile->shared->bExclusive = FALSE;
47398 else if (pFile->local.nReaders){
47401 pFile->local.nReaders --;
47402 if (pFile->local.nReaders == 0)
47404 pFile->shared->nReaders --;
47413 if (pFile->local.bPending){
47414 pFile->local.bPending = FALSE;
47415 pFile->shared->bPending = FALSE;
47422 if (pFile->local.bReserved) {
47423 pFile->local.bReserved = FALSE;
47424 pFile->shared->bReserved = FALSE;
47429 winceMutexRelease(pFile->hMutex);
47509 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
47515 ** Otherwise, set pFile->lastErrno and return non-zero.
47524 OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
47530 ** containing the lower 32-bits of the new file-offset. Or, if it fails,
47536 dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
47540 pFile->lastErrno = lastErrno;
47541 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
47542 "winSeekFile", pFile->zPath);
47543 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
47547 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
47558 bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
47561 pFile->lastErrno = osGetLastError();
47562 winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
47563 "winSeekFile", pFile->zPath);
47564 OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
47568 OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
47596 assert( pFile->pShm==0 );
47598 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
47600 osGetCurrentProcessId(), pFile, pFile->h));
47607 rc = osCloseHandle(pFile->h);
47613 winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData;
47614 if( pAppData==NULL || !pAppData->bNoLock ){
47618 if( pFile->zDeleteOnClose ){
47621 osDeleteFileW(pFile->zDeleteOnClose)==0
47622 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
47627 sqlite3_free(pFile->zDeleteOnClose);
47631 pFile->h = NULL;
47633 OpenCounter(-1);
47635 osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
47638 "winClose", pFile->zPath);
47665 pFile->h, pBuf, amt, offset, pFile->locktype));
47670 if( offset<pFile->mmapSize ){
47671 if( offset+amt <= pFile->mmapSize ){
47672 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
47673 OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
47674 osGetCurrentProcessId(), pFile, pFile->h));
47677 int nCopy = (int)(pFile->mmapSize - offset);
47678 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
47680 amt -= nCopy;
47689 osGetCurrentProcessId(), pFile, pFile->h));
47692 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
47697 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
47702 pFile->lastErrno = lastErrno;
47704 osGetCurrentProcessId(), pFile, pFile->h));
47705 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
47706 "winRead", pFile->zPath);
47710 /* Unread parts of the buffer must be zero-filled */
47711 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
47713 osGetCurrentProcessId(), pFile, pFile->h));
47718 osGetCurrentProcessId(), pFile, pFile->h));
47743 pFile->h, pBuf, amt, offset, pFile->locktype));
47748 if( offset<pFile->mmapSize ){
47749 if( offset+amt <= pFile->mmapSize ){
47750 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
47751 OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
47752 osGetCurrentProcessId(), pFile, pFile->h));
47755 int nCopy = (int)(pFile->mmapSize - offset);
47756 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
47758 amt -= nCopy;
47786 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
47788 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
47804 nRem -= nWrite;
47807 pFile->lastErrno = lastErrno;
47813 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
47814 || ( pFile->lastErrno==ERROR_DISK_FULL )){
47816 osGetCurrentProcessId(), pFile, pFile->h));
47817 return winLogError(SQLITE_FULL, pFile->lastErrno,
47818 "winWrite1", pFile->zPath);
47821 osGetCurrentProcessId(), pFile, pFile->h));
47822 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
47823 "winWrite2", pFile->zPath);
47828 osGetCurrentProcessId(), pFile, pFile->h));
47841 if( pFile->nFetchOut>0 ){
47842 /* File truncation is a no-op if there are outstanding memory mapped
47848 ** No real harm comes of this - the database file is not corrupted,
47852 ** The only feasible work-around is to defer the truncation until after
47853 ** all references to memory-mapped content are closed. That is doable,
47856 ** now to simply make trancations a no-op if there are pending reads. We
47866 osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
47868 /* If the user has configured a chunk-size for this file, truncate the
47873 if( pFile->szChunk>0 ){
47874 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
47878 if( pFile->pMapRegion ){
47879 oldMmapSize = pFile->mmapSize;
47886 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
47888 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
47889 "winTruncate1", pFile->zPath);
47890 }else if( 0==osSetEndOfFile(pFile->h) &&
47892 pFile->lastErrno = lastErrno;
47893 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
47894 "winTruncate2", pFile->zPath);
47900 winMapfile(pFile, -1);
47908 osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
47954 osGetCurrentProcessId(), pFile, pFile->h, flags,
47955 pFile->locktype));
47967 ** no-op
47970 OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
47971 osGetCurrentProcessId(), pFile, pFile->h));
47975 if( pFile->pMapRegion ){
47976 if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
47977 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
47979 pFile, pFile->pMapRegion));
47981 pFile->lastErrno = osGetLastError();
47982 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
47984 pFile, pFile->pMapRegion));
47985 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
47986 "winSync1", pFile->zPath);
47990 rc = osFlushFileBuffers(pFile->h);
47994 osGetCurrentProcessId(), pFile, pFile->h));
47997 pFile->lastErrno = osGetLastError();
47999 osGetCurrentProcessId(), pFile, pFile->h));
48000 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
48001 "winSync2", pFile->zPath);
48016 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
48021 if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
48025 pFile->lastErrno = osGetLastError();
48026 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
48027 "winFileSize", pFile->zPath);
48036 lowerBits = osGetFileSize(pFile->h, &upperBits);
48040 pFile->lastErrno = lastErrno;
48041 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
48042 "winFileSize", pFile->zPath);
48047 pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
48089 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
48096 res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
48098 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
48106 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
48107 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
48108 SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
48112 pFile->lastErrno = osGetLastError();
48115 OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
48125 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
48127 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
48131 res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
48135 pFile->lastErrno = lastErrno;
48136 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
48137 "winUnlockReadLock", pFile->zPath);
48139 OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
48144 ** Lock the file with the lock specified by parameter locktype - one
48158 ** UNLOCKED -> SHARED
48159 ** SHARED -> RESERVED
48160 ** SHARED -> (PENDING) -> EXCLUSIVE
48161 ** RESERVED -> (PENDING) -> EXCLUSIVE
48162 ** PENDING -> EXCLUSIVE
48172 int newLocktype; /* Set pFile->locktype to this value before exiting */
48179 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
48185 if( pFile->locktype>=locktype ){
48186 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
48190 /* Do not allow any kind of write-lock on a read-only database
48192 if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
48198 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
48200 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
48206 newLocktype = pFile->locktype;
48207 if( pFile->locktype==NO_LOCK
48208 || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
48211 while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
48214 ** around problems caused by indexing and/or anti-virus software on
48220 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
48221 pFile->h, cnt, res));
48223 pFile->lastErrno = lastErrno;
48225 OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
48226 pFile->h, cnt, sqlite3ErrName(rc)));
48240 assert( pFile->locktype==NO_LOCK );
48252 assert( pFile->locktype==SHARED_LOCK );
48253 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
48271 assert( pFile->locktype>=SHARED_LOCK );
48273 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
48287 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
48296 pFile->lastErrno = lastErrno;
48298 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
48299 pFile->h, locktype, newLocktype));
48301 pFile->locktype = (u8)newLocktype;
48303 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
48310 ** non-zero, otherwise zero.
48317 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
48320 if( pFile->locktype>=RESERVED_LOCK ){
48322 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
48324 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
48326 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
48329 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
48332 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
48333 pFile->h, pResOut, *pResOut));
48342 ** the requested locking level, this routine is a no-op.
48355 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
48356 type = pFile->locktype;
48358 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
48363 "winUnlock", pFile->zPath);
48367 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
48373 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
48375 pFile->locktype = (u8)locktype;
48377 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
48382 ****************************** No-op Locking **********************************
48388 ** This locking mode is appropriate for use on read-only databases
48389 ** (ex: databases that are burned into CD-ROM, for example.) It can
48416 /******************* End of the no-op lock implementation *********************
48421 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
48423 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
48427 *pArg = (pFile->ctrlFlags & mask)!=0;
48429 pFile->ctrlFlags &= ~mask;
48431 pFile->ctrlFlags |= mask;
48446 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
48449 *(int*)pArg = pFile->locktype;
48450 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
48454 *(int*)pArg = (int)pFile->lastErrno;
48455 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
48459 pFile->szChunk = *(int *)pArg;
48460 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
48464 if( pFile->szChunk>0 ){
48475 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
48478 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
48483 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
48488 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
48492 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
48493 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
48508 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
48513 *phFile = pFile->h;
48514 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
48520 HANDLE hOldFile = pFile->h;
48521 pFile->h = *phFile;
48524 hOldFile, pFile->h));
48530 int rc = winGetTempname(pFile->pVfs, &zTFile);
48534 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
48547 ** least a 64-bit type. */
48552 *(i64*)pArg = pFile->mmapSizeMax;
48553 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
48554 pFile->mmapSizeMax = newLimit;
48555 if( pFile->mmapSize>0 ){
48557 rc = winMapfile(pFile, -1);
48560 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
48565 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
48575 ** if two files are created in the same file-system directory (i.e.
48590 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
48632 ** log-summary, each thread has its own winFile object, but they all
48634 ** log-summary is opened only once per process.
48642 ** The following fields are read-only after the object is created:
48657 int szRegion; /* Size of shared-memory regions */
48659 u8 isReadonly; /* True if read-only */
48688 ** are read-only thereafter:
48693 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
48720 winShmNode *pFile, /* Apply locks to this open shared-memory segment */
48728 assert( pFile->nRef==0 || sqlite3_mutex_held(pFile->mutex) );
48730 OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
48731 pFile->hFile.h, lockType, ofst, nByte));
48733 /* Release/Acquire the system-level lock */
48735 rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
48740 rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
48746 pFile->lastErrno = osGetLastError();
48750 OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
48751 pFile->hFile.h, (lockType == WINSHM_UNLCK) ? "winUnlockFile" :
48752 "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
48764 ** This is not a VFS shared-memory method; it is a utility function called
48765 ** by VFS shared-memory methods.
48771 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
48775 if( p->nRef==0 ){
48777 if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
48778 for(i=0; i<p->nRegion; i++){
48779 BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
48780 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
48783 bRc = osCloseHandle(p->aRegion[i].hMap);
48784 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
48788 if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
48790 winClose((sqlite3_file *)&p->hFile);
48796 winDelete(pVfs, p->zFilename, 0);
48800 *pp = p->pNext;
48801 sqlite3_free(p->aRegion);
48804 pp = &p->pNext;
48816 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
48822 if( pShmNode->isReadonly ){
48823 pShmNode->isUnlocked = 1;
48826 }else if( winTruncate((sqlite3_file*)&pShmNode->hFile, 0) ){
48829 "winLockSharedMemory", pShmNode->zFilename);
48841 ** Open the shared-memory area associated with database file pDbFd.
48843 ** When opening a new shared-memory file, if no other instances of that
48854 assert( pDbFd->pShm==0 ); /* Not previously opened */
48861 nName = sqlite3Strlen30(pDbFd->zPath);
48867 pNew->zFilename = (char*)&pNew[1];
48868 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
48869 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
48875 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
48879 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
48889 ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
48890 pShmNode->pNext = winShmNodeList;
48894 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
48895 if( pShmNode->mutex==0 ){
48901 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
48906 rc = winOpen(pDbFd->pVfs, pShmNode->zFilename,
48907 (sqlite3_file*)&pShmNode->hFile,
48911 pShmNode->zFilename);
48914 if( outFlags==SQLITE_OPEN_READONLY ) pShmNode->isReadonly = 1;
48921 p->pShmNode = pShmNode;
48923 p->id = pShmNode->nextShmId++;
48925 pShmNode->nRef++;
48926 pDbFd->pShm = p;
48933 ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
48936 sqlite3_mutex_enter(pShmNode->mutex);
48937 p->pNext = pShmNode->pFirst;
48938 pShmNode->pFirst = p;
48939 sqlite3_mutex_leave(pShmNode->mutex);
48945 winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
48953 ** Close a connection to shared-memory. Delete the underlying
48960 winFile *pDbFd; /* Database holding shared-memory */
48962 winShmNode *pShmNode; /* The underlying shared-memory file */
48966 p = pDbFd->pShm;
48968 pShmNode = p->pShmNode;
48972 sqlite3_mutex_enter(pShmNode->mutex);
48973 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
48974 *pp = p->pNext;
48978 pDbFd->pShm = 0;
48979 sqlite3_mutex_leave(pShmNode->mutex);
48981 /* If pShmNode->nRef has reached 0, then close the underlying
48982 ** shared-memory file, too */
48984 assert( pShmNode->nRef>0 );
48985 pShmNode->nRef--;
48986 if( pShmNode->nRef==0 ){
48987 winShmPurge(pDbFd->pVfs, deleteFlag);
48995 ** Change the lock state for a shared-memory segment.
49004 winShm *p = pDbFd->pShm; /* The shared memory being locked */
49011 pShmNode = p->pShmNode;
49022 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
49024 sqlite3_mutex_enter(pShmNode->mutex);
49029 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
49031 assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
49032 allMask |= pX->sharedMask;
49035 /* Unlock the system-level locks */
49044 p->exclMask &= ~mask;
49045 p->sharedMask &= ~mask;
49054 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
49055 if( (pX->exclMask & mask)!=0 ){
49059 allShared |= pX->sharedMask;
49073 p->sharedMask |= mask;
49079 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
49080 if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
49092 assert( (p->sharedMask & mask)==0 );
49093 p->exclMask |= mask;
49097 sqlite3_mutex_leave(pShmNode->mutex);
49098 OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
49099 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
49114 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
49121 ** shared-memory associated with the database file fd. Shared-memory regions
49122 ** are numbered starting from zero. Each shared-memory region is szRegion
49127 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
49130 ** isWrite is non-zero and the requested shared-memory region has not yet
49133 ** If the shared-memory region has already been allocated or is allocated by
49146 winShm *pShm = pDbFd->pShm;
49155 pShm = pDbFd->pShm;
49158 pShmNode = pShm->pShmNode;
49160 sqlite3_mutex_enter(pShmNode->mutex);
49161 if( pShmNode->isUnlocked ){
49164 pShmNode->isUnlocked = 0;
49166 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
49168 if( pShmNode->nRegion<=iRegion ){
49171 sqlite3_int64 sz; /* Current size of wal-index file */
49173 pShmNode->szRegion = szRegion;
49176 ** Check to see if it has been allocated (i.e. if the wal-index file is
49179 rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
49182 "winShmMap1", pDbFd->zPath);
49190 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
49194 rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
49197 "winShmMap2", pDbFd->zPath);
49204 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
49210 pShmNode->aRegion = apNew;
49212 if( pShmNode->isReadonly ){
49217 while( pShmNode->nRegion<=iRegion ){
49218 HANDLE hMap = NULL; /* file-mapping handle */
49222 hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
49226 hMap = osCreateFileMappingW(pShmNode->hFile.h,
49230 hMap = osCreateFileMappingA(pShmNode->hFile.h,
49234 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
49235 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
49238 int iOffset = pShmNode->nRegion*szRegion;
49242 iOffset - iOffsetShift, szRegion + iOffsetShift
49246 0, iOffset - iOffsetShift, szRegion + iOffsetShift
49249 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
49250 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
49254 pShmNode->lastErrno = osGetLastError();
49255 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
49256 "winShmMap3", pDbFd->zPath);
49261 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
49262 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
49263 pShmNode->nRegion++;
49268 if( pShmNode->nRegion>iRegion ){
49271 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
49276 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
49277 sqlite3_mutex_leave(pShmNode->mutex);
49294 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
49296 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
49297 pFile->mmapSize, pFile->mmapSizeMax));
49298 if( pFile->pMapRegion ){
49299 if( !osUnmapViewOfFile(pFile->pMapRegion) ){
49300 pFile->lastErrno = osGetLastError();
49301 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
49303 pFile->pMapRegion));
49304 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
49305 "winUnmapfile1", pFile->zPath);
49307 pFile->pMapRegion = 0;
49308 pFile->mmapSize = 0;
49310 if( pFile->hMap!=NULL ){
49311 if( !osCloseHandle(pFile->hMap) ){
49312 pFile->lastErrno = osGetLastError();
49313 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
49314 osGetCurrentProcessId(), pFile, pFile->hMap));
49315 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
49316 "winUnmapfile2", pFile->zPath);
49318 pFile->hMap = NULL;
49320 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
49326 ** Memory map or remap the file opened by file-descriptor pFd (if the file
49329 ** outstanding xFetch() references to it, this function is a no-op.
49331 ** If parameter nByte is non-negative, then it is the requested size of
49345 assert( nMap>=0 || pFd->nFetchOut==0 );
49346 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
49349 if( pFd->nFetchOut>0 ) return SQLITE_OK;
49354 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
49359 if( nMap>pFd->mmapSizeMax ){
49360 nMap = pFd->mmapSizeMax;
49362 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
49364 if( nMap==0 && pFd->mmapSize>0 ){
49367 if( nMap!=pFd->mmapSize ){
49374 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
49380 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
49382 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
49386 pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
49390 if( pFd->hMap==NULL ){
49391 pFd->lastErrno = osGetLastError();
49392 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
49393 "winMapfile1", pFd->zPath);
49395 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
49402 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
49404 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
49407 osCloseHandle(pFd->hMap);
49408 pFd->hMap = NULL;
49409 pFd->lastErrno = osGetLastError();
49410 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
49411 "winMapfile2", pFd->zPath);
49413 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
49417 pFd->pMapRegion = pNew;
49418 pFd->mmapSize = nMap;
49421 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
49449 if( pFd->mmapSizeMax>0 ){
49450 if( pFd->pMapRegion==0 ){
49451 int rc = winMapfile(pFd, -1);
49458 if( pFd->mmapSize >= iOff+nAmt ){
49459 assert( pFd->pMapRegion!=0 );
49460 *pp = &((u8 *)pFd->pMapRegion)[iOff];
49461 pFd->nFetchOut++;
49472 ** If the third argument is non-NULL, then this function releases a
49488 assert( (p==0)==(pFd->nFetchOut==0) );
49491 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
49497 pFd->nFetchOut--;
49501 ** is unnecessary can be omitted - potentially improving
49506 assert( pFd->nFetchOut>=0 );
49594 ** supports for filenames into UTF-8. Space to hold the result is
49613 ** Convert a UTF-8 filename into whatever form the underlying
49633 ** This function returns non-zero if the specified UTF-8 string buffer
49641 if( winIsDirSep(zBuf[nLen-1]) ){
49680 /* It's odd to simulate an io-error here, but really this is just
49681 ** using the io-error infrastructure to test that SQLite handles this
49689 nMax = pVfs->mxPathname; nBuf = nMax + 2;
49692 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
49700 nDir = nMax - (nPre + 15);
49705 if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
49711 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
49753 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
49766 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
49774 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
49781 ** its name into UTF-8 (i.e. if it is UTF-16 right now).
49787 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
49805 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
49811 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
49823 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
49833 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
49838 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
49848 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
49862 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
49880 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
49884 sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
49889 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
49895 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
49941 const char *zName, /* Name of the file (UTF-8) */
49958 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
50000 /* The main DB, main journal, WAL file and super-journal are never
50007 /* Assert that the upper layer has set one of the "file-type" flags. */
50016 pFile->h = INVALID_HANDLE_VALUE;
50038 /* Database filenames are double-zero terminated if they are not
50184 pFile->lastErrno = lastErrno;
50185 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
50202 pAppData = (winVfsAppData*)pVfs->pAppData;
50207 && ((pAppData==NULL) || !pAppData->bNoLock)
50213 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
50218 pFile->zDeleteOnClose = zConverted;
50226 id->pMethods = pAppData ? pAppData->pMethod : &winIoMethod;
50227 pFile->pVfs = pVfs;
50228 pFile->h = h;
50230 pFile->ctrlFlags |= WINFILE_RDONLY;
50235 pFile->ctrlFlags |= WINFILE_PSOW;
50237 pFile->lastErrno = NO_ERROR;
50238 pFile->zPath = zName;
50240 pFile->hMap = NULL;
50241 pFile->pMapRegion = 0;
50242 pFile->mmapSize = 0;
50243 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
50399 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
50445 ** Returns non-zero if the specified path name starts with the "long path"
50456 ** Returns non-zero if the specified path name starts with a drive letter
50466 ** Returns non-zero if the specified path name should be used verbatim. If
50467 ** non-zero is returned from this function, the calling function must simply
50468 ** use the provided path name verbatim -OR- resolve it into a full path name
50504 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
50530 assert( nFull>=pVfs->mxPathname );
50538 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
50544 CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
50554 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
50560 char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
50566 zRelative, zOut, pVfs->mxPathname+1)<0 ){
50576 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
50595 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
50598 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
50604 /* It's odd to simulate an io-error here, but really this is just
50605 ** using the io-error infrastructure to test that SQLite handles this
50617 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
50678 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
50709 int nFull = pVfs->mxPathname+1;
50784 for(j=0, k=p->i; j<sz; j++){
50785 p->a[k++] ^= x[j];
50786 if( k>=p->na ) k = 0;
50788 p->i = k;
50789 p->nXor += sz;
50860 ** The following variable, if set to a non-zero value, is interpreted as
50879 /* FILETIME structure is a 64-bit value representing the number of
50880 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
50887 /* 2^32 - to avoid use of LL and warnings in gcc */
50937 ** buffer with a nul-terminated UTF-8 encoded error message
50943 ** is zero if the error message fits in the buffer, or non-zero
50944 ** otherwise (if the message was truncated). If non-zero is returned,
50945 ** then it is not necessary to include the nul-terminator character
51002 "win32-longpath", /* zName */
51027 "win32-none", /* zName */
51052 "win32-longpath-none", /* zName */
51073 /* Double-check that the aSyscall[] array has been constructed
51126 ** 2016-09-07
51128 ** The author disclaims copyright to this source code. In place of
51137 ** This file implements an in-memory VFS. A database is held as a contiguous
51153 /* Access to a lower-level VFS that (might) implement dynamic loading,
51156 #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
51216 ** File-scope variables for holding the memdb files that are accessible
51320 sqlite3_mutex_enter(p->pMutex);
51323 sqlite3_mutex_leave(p->pMutex);
51330 ** Close an memdb-file.
51335 MemStore *p = ((MemFile*)pFile)->pStore;
51336 if( p->zFName ){
51345 if( p->nRef==1 ){
51346 memdb_g.apMemStore[i] = memdb_g.apMemStore[--memdb_g.nMemStore];
51359 p->nRef--;
51360 if( p->nRef<=0 ){
51361 if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ){
51362 sqlite3_free(p->aData);
51365 sqlite3_mutex_free(p->pMutex);
51374 ** Read data from an memdb-file.
51382 MemStore *p = ((MemFile*)pFile)->pStore;
51384 if( iOfst+iAmt>p->sz ){
51386 if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
51390 memcpy(zBuf, p->aData+iOfst, iAmt);
51400 if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || NEVER(p->nMmap>0) ){
51403 if( newSz>p->szMax ){
51407 if( newSz>p->szMax ) newSz = p->szMax;
51408 pNew = sqlite3Realloc(p->aData, newSz);
51410 p->aData = pNew;
51411 p->szAlloc = newSz;
51416 ** Write data to an memdb-file.
51424 MemStore *p = ((MemFile*)pFile)->pStore;
51426 if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ){
51432 if( iOfst+iAmt>p->sz ){
51434 if( iOfst+iAmt>p->szAlloc
51440 if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
51441 p->sz = iOfst+iAmt;
51443 memcpy(p->aData+iOfst, z, iAmt);
51449 ** Truncate an memdb-file.
51456 MemStore *p = ((MemFile*)pFile)->pStore;
51459 if( size>p->sz ){
51463 p->sz = size;
51470 ** Sync an memdb-file.
51479 ** Return the current file-size of an memdb-file.
51482 MemStore *p = ((MemFile*)pFile)->pStore;
51484 *pSize = p->sz;
51490 ** Lock an memdb-file.
51494 MemStore *p = pThis->pStore;
51496 if( eLock<=pThis->eLock ) return SQLITE_OK;
51499 assert( p->nWrLock==0 || p->nWrLock==1 );
51500 assert( pThis->eLock<=SQLITE_LOCK_SHARED || p->nWrLock==1 );
51501 assert( pThis->eLock==SQLITE_LOCK_NONE || p->nRdLock>=1 );
51503 if( eLock>SQLITE_LOCK_SHARED && (p->mFlags & SQLITE_DESERIALIZE_READONLY) ){
51508 assert( pThis->eLock==SQLITE_LOCK_NONE );
51509 if( p->nWrLock>0 ){
51512 p->nRdLock++;
51519 assert( pThis->eLock>=SQLITE_LOCK_SHARED );
51520 if( ALWAYS(pThis->eLock==SQLITE_LOCK_SHARED) ){
51521 if( p->nWrLock>0 ){
51524 p->nWrLock = 1;
51532 assert( pThis->eLock>=SQLITE_LOCK_SHARED );
51533 if( p->nRdLock>1 ){
51535 }else if( pThis->eLock==SQLITE_LOCK_SHARED ){
51536 p->nWrLock = 1;
51542 if( rc==SQLITE_OK ) pThis->eLock = eLock;
51548 ** Unlock an memdb-file.
51552 MemStore *p = pThis->pStore;
51553 if( eLock>=pThis->eLock ) return SQLITE_OK;
51558 if( ALWAYS(pThis->eLock>SQLITE_LOCK_SHARED) ){
51559 p->nWrLock--;
51562 if( pThis->eLock>SQLITE_LOCK_SHARED ){
51563 p->nWrLock--;
51565 p->nRdLock--;
51568 pThis->eLock = eLock;
51576 ** occur on an in-memory database.
51586 ** File control method. For custom operations on an memdb-file.
51589 MemStore *p = ((MemFile*)pFile)->pStore;
51593 *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
51598 if( iLimit<p->sz ){
51600 iLimit = p->szMax;
51602 iLimit = p->sz;
51605 p->szMax = iLimit;
51615 ** Return the sector-size in bytes for an memdb-file.
51623 ** Return the device characteristic flags supported by an memdb-file.
51633 /* Fetch a page of a memory-mapped file */
51640 MemStore *p = ((MemFile*)pFile)->pStore;
51642 if( iOfst+iAmt>p->sz || (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)!=0 ){
51645 p->nMmap++;
51646 *pp = (void*)(p->aData + iOfst);
51652 /* Release a memory-mapped page */
51654 MemStore *p = ((MemFile*)pFile)->pStore;
51658 p->nMmap--;
51687 if( strcmp(memdb_g.apMemStore[i]->zFName,zName)==0 ){
51709 p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE|SQLITE_DESERIALIZE_FREEONCLOSE;
51710 p->szMax = sqlite3GlobalConfig.mxMemdbSize;
51711 p->zFName = (char*)&p[1];
51712 memcpy(p->zFName, zName, szName+1);
51713 p->pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
51714 if( p->pMutex==0 ){
51715 memdb_g.nMemStore--;
51720 p->nRef = 1;
51724 p->nRef++;
51733 p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
51734 p->szMax = sqlite3GlobalConfig.mxMemdbSize;
51736 pFile->pStore = p;
51740 pFd->pMethods = &memdb_io_methods;
51745 #if 0 /* Only used to delete rollback journals, super-journals, and WAL
51749 ** ensure the file-system modifications are synced to disk before
51796 return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
51801 ** utf-8 string describing the most recent error encountered associated
51805 ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
51812 return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
51819 ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
51827 return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
51835 return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
51843 return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
51848 return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
51851 return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
51863 if( p->base.pMethods!=&memdb_io_methods ) return 0;
51864 pStore = p->pStore;
51866 if( pStore->zFName!=0 ) p = 0;
51897 if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
51900 if( piSize ) *piSize = -1;
51903 MemStore *pStore = p->pStore;
51904 assert( pStore->pMutex==0 );
51905 if( piSize ) *piSize = pStore->sz;
51907 pOut = pStore->aData;
51909 pOut = sqlite3_malloc64( pStore->sz );
51910 if( pOut ) memcpy(pOut, pStore->aData, pStore->sz);
51914 pBt = db->aDb[iDb].pBt;
51918 rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
51937 unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
51977 sqlite3_mutex_enter(db->mutex);
51978 if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
51989 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
51993 db->init.iDb = (u8)iDb;
51994 db->init.reopenMemdb = 1;
51996 db->init.reopenMemdb = 0;
52005 MemStore *pStore = p->pStore;
52006 pStore->aData = pData;
52008 pStore->sz = szDb;
52009 pStore->szAlloc = szBuf;
52010 pStore->szMax = szBuf;
52011 if( pStore->szMax<sqlite3GlobalConfig.mxMemdbSize ){
52012 pStore->szMax = sqlite3GlobalConfig.mxMemdbSize;
52014 pStore->mFlags = mFlags;
52023 sqlite3_mutex_leave(db->mutex);
52035 sz = pLower->szOsFile;
52052 ** The author disclaims copyright to this source code. In place of
52060 ** This file implements an object that represents a fixed-length
52064 ** journalled during a transaction, or which pages have the "dont-write"
52093 (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
52110 ** sub-dividing and re-hashing. */
52115 ** no fewer collisions than the no-op *1. */
52135 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
52144 u32 nSet; /* Number of bits that are set - only valid for aHash
52168 p->iSize = iSize;
52174 ** Check to see if the i-th bit is set. Return true or false.
52180 i--;
52181 if( i>=p->iSize ) return 0;
52182 while( p->iDivisor ){
52183 u32 bin = i/p->iDivisor;
52184 i = i%p->iDivisor;
52185 p = p->u.apSub[bin];
52190 if( p->iSize<=BITVEC_NBIT ){
52191 return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
52194 while( p->u.aHash[h] ){
52195 if( p->u.aHash[h]==i ) return 1;
52206 ** Set the i-th bit. Return 0 on success and an error code if
52209 ** This routine might cause sub-bitmaps to be allocated. Failing
52210 ** to get the memory needed to hold the sub-bitmap is the only
52221 assert( i<=p->iSize );
52222 i--;
52223 while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
52224 u32 bin = i/p->iDivisor;
52225 i = i%p->iDivisor;
52226 if( p->u.apSub[bin]==0 ){
52227 p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
52228 if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
52230 p = p->u.apSub[bin];
52232 if( p->iSize<=BITVEC_NBIT ){
52233 p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
52239 /* worring about sub-dividing and re-hashing. */
52240 if( !p->u.aHash[h] ){
52241 if (p->nSet<(BITVEC_NINT-1)) {
52250 if( p->u.aHash[h]==i ) return SQLITE_OK;
52253 } while( p->u.aHash[h] );
52258 if( p->nSet>=BITVEC_MXHASH ){
52261 u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
52265 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
52266 memset(p->u.apSub, 0, sizeof(p->u.apSub));
52267 p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
52277 p->nSet++;
52278 p->u.aHash[h] = i;
52283 ** Clear the i-th bit.
52291 i--;
52292 while( p->iDivisor ){
52293 u32 bin = i/p->iDivisor;
52294 i = i%p->iDivisor;
52295 p = p->u.apSub[bin];
52300 if( p->iSize<=BITVEC_NBIT ){
52301 p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
52305 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
52306 memset(p->u.aHash, 0, sizeof(p->u.aHash));
52307 p->nSet = 0;
52310 u32 h = BITVEC_HASH(aiValues[j]-1);
52311 p->nSet++;
52312 while( p->u.aHash[h] ){
52316 p->u.aHash[h] = aiValues[j];
52327 if( p->iDivisor ){
52330 sqlite3BitvecDestroy(p->u.apSub[i]);
52341 return p->iSize;
52383 ** If a memory allocation error occurs, return -1.
52388 int rc = -1;
52411 i = aOp[pc+2] - 1;
52423 if( (--aOp[pc+1]) > 0 ) nx = 0;
52439 ** match (rc==0). Change rc to non-zero if a discrepancy
52444 + (sqlite3BitvecSize(pBitvec) - sz);
52466 ** The author disclaims copyright to this source code. In place of
52490 ** such that p was added to the list more recently than p->pDirtyNext.
52495 ** page to eject from the cache mid-transaction. It is better to eject
52535 pPg = (PgHdr*)pLower->pExtra;
52536 printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
52537 a = (unsigned char *)pLower->pBuf;
52547 if( pCache->pCache==0 ) return;
52551 pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
52554 if( ((PgHdr*)pLower)->pPage==0 ){
52555 sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
52572 for(p=pCache->pDirty; p; p=p->pDirtyNext){
52592 assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
52593 pCache = pPg->pCache;
52595 if( pPg->flags & PGHDR_CLEAN ){
52596 assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
52599 assert( (pPg->flags & PGHDR_DIRTY)!=0 );/* If not CLEAN must be DIRTY */
52600 assert( pPg->pDirtyNext==0 || pPg->pDirtyNext->pDirtyPrev==pPg );
52601 assert( pPg->pDirtyPrev==0 || pPg->pDirtyPrev->pDirtyNext==pPg );
52602 assert( pPg->pDirtyPrev!=0 || pCache->pDirty==pPg );
52606 if( pPg->flags & PGHDR_WRITEABLE ){
52607 assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
52645 PCache *p = pPage->pCache;
52649 pPage->pgno));
52651 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
52652 assert( pPage->pDirtyPrev || pPage==p->pDirty );
52655 if( p->pSynced==pPage ){
52656 p->pSynced = pPage->pDirtyPrev;
52659 if( pPage->pDirtyNext ){
52660 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
52662 assert( pPage==p->pDirtyTail );
52663 p->pDirtyTail = pPage->pDirtyPrev;
52665 if( pPage->pDirtyPrev ){
52666 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
52672 assert( pPage==p->pDirty );
52673 p->pDirty = pPage->pDirtyNext;
52674 assert( p->bPurgeable || p->eCreate==2 );
52675 if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
52676 assert( p->bPurgeable==0 || p->eCreate==1 );
52677 p->eCreate = 2;
52682 pPage->pDirtyPrev = 0;
52683 pPage->pDirtyNext = p->pDirty;
52684 if( pPage->pDirtyNext ){
52685 assert( pPage->pDirtyNext->pDirtyPrev==0 );
52686 pPage->pDirtyNext->pDirtyPrev = pPage;
52688 p->pDirtyTail = pPage;
52689 if( p->bPurgeable ){
52690 assert( p->eCreate==2 );
52691 p->eCreate = 1;
52694 p->pDirty = pPage;
52700 ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
52701 if( !p->pSynced
52702 && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
52704 p->pSynced = pPage;
52712 ** being used for an in-memory database, this function is a no-op.
52715 if( p->pCache->bPurgeable ){
52716 pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
52717 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
52718 pcacheDump(p->pCache);
52723 ** Compute the number of pages of cache requested. p->szCache is the
52727 if( p->szCache>=0 ){
52728 /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
52730 return p->szCache;
52733 /* IMPLEMANTATION-OF: R-59858-46238 If the argument N is negative, then the
52737 n = ((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
52750 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
52751 ** built-in default page cache is used instead of the application defined
52760 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
52791 p->szPage = 1;
52792 p->szExtra = szExtra;
52794 p->bPurgeable = bPurgeable;
52795 p->eCreate = 2;
52796 p->xStress = xStress;
52797 p->pStress = pStress;
52798 p->szCache = 100;
52799 p->szSpill = 1;
52809 assert( pCache->nRefSum==0 && pCache->pDirty==0 );
52810 if( pCache->szPage ){
52813 szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
52814 pCache->bPurgeable
52818 if( pCache->pCache ){
52819 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
52821 pCache->pCache = pNew;
52822 pCache->szPage = szPage;
52861 assert( pCache->pCache!=0 );
52863 assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
52872 eCreate = createFlag & pCache->eCreate;
52874 assert( createFlag==0 || pCache->eCreate==eCreate );
52875 assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
52876 pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
52900 if( pCache->eCreate==2 ) return 0;
52902 if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
52903 /* Find a dirty page to write-out and recycle. First try to find a
52904 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
52912 for(pPg=pCache->pSynced;
52913 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
52914 pPg=pPg->pDirtyPrev
52916 pCache->pSynced = pPg;
52918 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
52924 "spill page %d making room for %d - cache used: %d/%d",
52925 pPg->pgno, pgno,
52926 sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
52929 pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
52930 rc = pCache->xStress(pCache->pStress, pPg);
52937 *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
52957 pPgHdr = (PgHdr*)pPage->pExtra;
52958 assert( pPgHdr->pPage==0 );
52959 memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
52960 pPgHdr->pPage = pPage;
52961 pPgHdr->pData = pPage->pBuf;
52962 pPgHdr->pExtra = (void *)&pPgHdr[1];
52963 memset(pPgHdr->pExtra, 0, 8);
52964 pPgHdr->pCache = pCache;
52965 pPgHdr->pgno = pgno;
52966 pPgHdr->flags = PGHDR_CLEAN;
52984 pPgHdr = (PgHdr *)pPage->pExtra;
52986 if( !pPgHdr->pPage ){
52989 pCache->nRefSum++;
52990 pPgHdr->nRef++;
53000 assert( p->nRef>0 );
53001 p->pCache->nRefSum--;
53002 if( (--p->nRef)==0 ){
53003 if( p->flags&PGHDR_CLEAN ){
53016 assert(p->nRef>0);
53018 p->nRef++;
53019 p->pCache->nRefSum++;
53028 assert( p->nRef==1 );
53030 if( p->flags&PGHDR_DIRTY ){
53033 p->pCache->nRefSum--;
53034 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
53042 assert( p->nRef>0 );
53044 if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
53045 p->flags &= ~PGHDR_DONT_WRITE;
53046 if( p->flags & PGHDR_CLEAN ){
53047 p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
53048 pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
53049 assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
53063 assert( (p->flags & PGHDR_DIRTY)!=0 );
53064 assert( (p->flags & PGHDR_CLEAN)==0 );
53066 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
53067 p->flags |= PGHDR_CLEAN;
53068 pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
53070 if( p->nRef==0 ){
53080 pcacheTrace(("%p.CLEAN-ALL\n",pCache));
53081 while( (p = pCache->pDirty)!=0 ){
53091 pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
53092 for(p=pCache->pDirty; p; p=p->pDirtyNext){
53093 p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
53095 pCache->pSynced = pCache->pDirtyTail;
53103 for(p=pCache->pDirty; p; p=p->pDirtyNext){
53104 p->flags &= ~PGHDR_NEED_SYNC;
53106 pCache->pSynced = pCache->pDirtyTail;
53113 PCache *pCache = p->pCache;
53115 assert( p->nRef>0 );
53118 pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
53119 pOther = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, newPgno, 0);
53121 PgHdr *pXPage = (PgHdr*)pOther->pExtra;
53122 assert( pXPage->nRef==0 );
53123 pXPage->nRef++;
53124 pCache->nRefSum++;
53127 sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
53128 p->pgno = newPgno;
53129 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
53145 if( pCache->pCache ){
53149 for(p=pCache->pDirty; p; p=pNext){
53150 pNext = p->pDirtyNext;
53155 assert( p->pgno>0 );
53156 if( p->pgno>pgno ){
53157 assert( p->flags&PGHDR_DIRTY );
53161 if( pgno==0 && pCache->nRefSum ){
53163 pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
53165 ** pCache->nRefSum>0 */
53166 memset(pPage1->pBuf, 0, pCache->szPage);
53170 sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
53178 assert( pCache->pCache!=0 );
53180 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
53199 if( pA->pgno<pB->pgno ){
53200 pTail->pDirty = pA;
53202 pA = pA->pDirty;
53204 pTail->pDirty = pB;
53208 pTail->pDirty = pB;
53210 pB = pB->pDirty;
53212 pTail->pDirty = pA;
53237 pIn = p->pDirty;
53238 p->pDirty = 0;
53239 for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
53248 if( NEVER(i==N_SORT_BUCKET-1) ){
53268 for(p=pCache->pDirty; p; p=p->pDirtyNext){
53269 p->pDirty = p->pDirtyNext;
53271 return pcacheSortDirtyList(pCache->pDirty);
53281 return pCache->nRefSum;
53288 return p->nRef;
53295 assert( pCache->pCache!=0 );
53296 return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
53301 ** Get the suggested cache-size value.
53309 ** Set the suggested cache-size value.
53312 assert( pCache->pCache!=0 );
53313 pCache->szCache = mxPage;
53314 sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
53319 ** Set the suggested cache-spill value. Make no changes if if the
53320 ** argument is zero. Return the effective cache-spill size, which will
53325 assert( p->pCache!=0 );
53328 mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
53330 p->szSpill = mxPage;
53333 if( res<p->szSpill ) res = p->szSpill;
53341 assert( pCache->pCache!=0 );
53342 sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
53347 ** in the page-cache hierarchy.
53359 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
53368 return (pCache->pDirty!=0);
53380 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
53391 ** The author disclaims copyright to this source code. In place of
53408 ** -------------------------------------------------------------
53410 ** -------------------------------------------------------------
53426 ** size can vary according to architecture, compile-time options, and
53432 ** allocations. However, the btree layer needs a small (16-byte) overrun
53443 ** SOURCE OF PAGE CACHE MEMORY:
53447 ** (1) The general-purpose memory allocator - sqlite3Malloc()
53448 ** (2) Global page-cache memory provided using sqlite3_config() with
53450 ** (3) PCache-local bulk allocation.
53460 ** Or if N is negative, then -1024*N bytes of memory are allocated and used
53464 ** (3) is exhausted, subsequent allocations fail over to the general-purpose
53480 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
53490 ** but causes a 2-byte gap in the structure for most architectures (since
53491 ** pointers must be either 4 or 8-byte aligned). As this structure is located
53493 ** corrupt, code at the b-tree layer may overread the page buffer and
53499 ** The pLruNext and pLruPrev pointers form a double-linked circular list
53520 #define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
53521 #define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
53549 unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
53555 ** open database file (including each in-memory database and each
53570 unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
53588 PgHdr1 *pFree; /* List of unused pcache-local pages */
53589 void *pBulk; /* Bulk memory used by pcache-local */
53623 ** reading because (1) most platforms read a 32-bit integer atomically and
53640 # define pcache1EnterMutex(X) assert((X)->mutex==0)
53641 # define pcache1LeaveMutex(X) assert((X)->mutex==0)
53644 # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
53645 # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
53655 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
53674 while( n-- ){
53676 p->pNext = pcache1.pFree;
53685 ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
53686 ** true if pCache->pFree ends up containing one or more free pages.
53693 if( pCache->nMax<3 ) return 0;
53696 szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
53698 szBulk = -1024 * (i64)pcache1.nInitPage;
53700 if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
53701 szBulk = pCache->szAlloc*(i64)pCache->nMax;
53703 zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
53706 int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
53708 PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
53709 pX->page.pBuf = zBulk;
53710 pX->page.pExtra = &pX[1];
53711 pX->isBulkLocal = 1;
53712 pX->isAnchor = 0;
53713 pX->pNext = pCache->pFree;
53714 pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
53715 pCache->pFree = pX;
53716 zBulk += pCache->szAlloc;
53717 }while( --nBulk );
53719 return pCache->pFree!=0;
53738 pcache1.pFree = pcache1.pFree->pNext;
53739 pcache1.nFreeSlot--;
53776 pSlot->pNext = pcache1.pFree;
53823 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
53824 if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
53825 assert( pCache->pFree!=0 );
53826 p = pCache->pFree;
53827 pCache->pFree = p->pNext;
53828 p->pNext = 0;
53835 assert( pCache->pGroup==&pcache1.grp );
53836 pcache1LeaveMutex(pCache->pGroup);
53839 pPg = pcache1Alloc(pCache->szAlloc);
53842 pcache1EnterMutex(pCache->pGroup);
53845 p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
53846 p->page.pBuf = pPg;
53847 p->page.pExtra = &p[1];
53848 p->isBulkLocal = 0;
53849 p->isAnchor = 0;
53850 p->pLruPrev = 0; /* Initializing this saves a valgrind error */
53852 (*pCache->pnPurgeable)++;
53862 pCache = p->pCache;
53863 assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
53864 if( p->isBulkLocal ){
53865 p->pNext = pCache->pFree;
53866 pCache->pFree = p;
53868 pcache1Free(p->page.pBuf);
53870 (*pCache->pnPurgeable)--;
53908 if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
53929 assert( sqlite3_mutex_held(p->pGroup->mutex) );
53931 nNew = p->nHash*2;
53936 pcache1LeaveMutex(p->pGroup);
53937 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
53939 if( p->nHash ){ sqlite3EndBenignMalloc(); }
53940 pcache1EnterMutex(p->pGroup);
53942 for(i=0; i<p->nHash; i++){
53944 PgHdr1 *pNext = p->apHash[i];
53946 unsigned int h = pPage->iKey % nNew;
53947 pNext = pPage->pNext;
53948 pPage->pNext = apNew[h];
53952 sqlite3_free(p->apHash);
53953 p->apHash = apNew;
53954 p->nHash = nNew;
53961 ** LRU list, then this function is a no-op.
53968 assert( pPage->pLruNext );
53969 assert( pPage->pLruPrev );
53970 assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
53971 pPage->pLruPrev->pLruNext = pPage->pLruNext;
53972 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
53973 pPage->pLruNext = 0;
53974 /* pPage->pLruPrev = 0;
53976 assert( pPage->isAnchor==0 );
53977 assert( pPage->pCache->pGroup->lru.isAnchor==1 );
53978 pPage->pCache->nRecyclable--;
53992 PCache1 *pCache = pPage->pCache;
53995 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
53996 h = pPage->iKey % pCache->nHash;
53997 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
53998 *pp = (*pp)->pNext;
54000 pCache->nPage--;
54009 PGroup *pGroup = pCache->pGroup;
54011 assert( sqlite3_mutex_held(pGroup->mutex) );
54012 while( pGroup->nPurgeable>pGroup->nMaxPage
54013 && (p=pGroup->lru.pLruPrev)->isAnchor==0
54015 assert( p->pCache->pGroup==pGroup );
54020 if( pCache->nPage==0 && pCache->pBulk ){
54021 sqlite3_free(pCache->pBulk);
54022 pCache->pBulk = pCache->pFree = 0;
54037 TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
54039 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
54040 assert( pCache->iMaxKey >= iLimit );
54041 assert( pCache->nHash > 0 );
54042 if( pCache->iMaxKey - iLimit < pCache->nHash ){
54047 h = iLimit % pCache->nHash;
54048 iStop = pCache->iMaxKey % pCache->nHash;
54049 TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
54053 h = pCache->nHash/2;
54054 iStop = h - 1;
54059 assert( h<pCache->nHash );
54060 pp = &pCache->apHash[h];
54062 if( pPage->iKey>=iLimit ){
54063 pCache->nPage--;
54064 *pp = pPage->pNext;
54068 pp = &pPage->pNext;
54073 h = (h+1) % pCache->nHash;
54075 assert( nPage<0 || pCache->nPage==(unsigned)nPage );
54092 ** private PGroup (mode-1). pcache1.separateCache is false if the single
54093 ** PGroup in pcache1.grp is used for all page caches (mode-2).
54095 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
54097 ** * Use a unified cache in single-threaded applications that have
54098 ** configured a start-time buffer for use as page-cache memory using
54099 ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
54102 ** * Otherwise use separate caches (mode-1)
54156 assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
54164 pGroup->mxPinned = 10;
54169 if( pGroup->lru.isAnchor==0 ){
54170 pGroup->lru.isAnchor = 1;
54171 pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
54173 pCache->pGroup = pGroup;
54174 pCache->szPage = szPage;
54175 pCache->szExtra = szExtra;
54176 pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
54177 pCache->bPurgeable = (bPurgeable ? 1 : 0);
54180 pCache->nMin = 10;
54181 pGroup->nMinPage += pCache->nMin;
54182 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
54183 pCache->pnPurgeable = &pGroup->nPurgeable;
54185 pCache->pnPurgeable = &pCache->nPurgeableDummy;
54188 if( pCache->nHash==0 ){
54205 if( pCache->bPurgeable ){
54206 PGroup *pGroup = pCache->pGroup;
54209 if( n > 0x7fff0000 - pGroup->nMaxPage + pCache->nMax ){
54210 n = 0x7fff0000 - pGroup->nMaxPage + pCache->nMax;
54212 pGroup->nMaxPage += (n - pCache->nMax);
54213 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
54214 pCache->nMax = n;
54215 pCache->n90pct = pCache->nMax*9/10;
54228 if( pCache->bPurgeable ){
54229 PGroup *pGroup = pCache->pGroup;
54232 savedMaxPage = pGroup->nMaxPage;
54233 pGroup->nMaxPage = 0;
54235 pGroup->nMaxPage = savedMaxPage;
54246 pcache1EnterMutex(pCache->pGroup);
54247 n = pCache->nPage;
54248 pcache1LeaveMutex(pCache->pGroup);
54267 PGroup *pGroup = pCache->pGroup;
54271 assert( pCache->nPage >= pCache->nRecyclable );
54272 nPinned = pCache->nPage - pCache->nRecyclable;
54273 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
54274 assert( pCache->n90pct == pCache->nMax*9/10 );
54276 nPinned>=pGroup->mxPinned
54277 || nPinned>=pCache->n90pct
54278 || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
54283 if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
54284 assert( pCache->nHash>0 && pCache->apHash );
54287 if( pCache->bPurgeable
54288 && !pGroup->lru.pLruPrev->isAnchor
54289 && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
54292 pPage = pGroup->lru.pLruPrev;
54296 pOther = pPage->pCache;
54297 if( pOther->szAlloc != pCache->szAlloc ){
54301 pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
54313 unsigned int h = iKey % pCache->nHash;
54314 pCache->nPage++;
54315 pPage->iKey = iKey;
54316 pPage->pNext = pCache->apHash[h];
54317 pPage->pCache = pCache;
54318 pPage->pLruNext = 0;
54319 /* pPage->pLruPrev = 0;
54321 *(void **)pPage->page.pExtra = 0;
54322 pCache->apHash[h] = pPage;
54323 if( iKey>pCache->iMaxKey ){
54324 pCache->iMaxKey = iKey;
54340 ** For a non-purgeable cache (a cache used as the storage for an in-memory
54343 ** a non-purgeable cache.
54386 ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
54398 pPage = pCache->apHash[iKey % pCache->nHash];
54399 while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
54427 pcache1EnterMutex(pCache->pGroup);
54429 assert( pPage==0 || pCache->iMaxKey>=iKey );
54430 pcache1LeaveMutex(pCache->pGroup);
54444 assert( pCache->bPurgeable || createFlag!=1 );
54445 assert( pCache->bPurgeable || pCache->nMin==0 );
54446 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
54447 assert( pCache->nMin==0 || pCache->bPurgeable );
54448 assert( pCache->nHash>0 );
54450 if( pCache->pGroup->mutex ){
54472 PGroup *pGroup = pCache->pGroup;
54474 assert( pPage->pCache==pCache );
54480 assert( pPage->pLruNext==0 );
54483 if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
54487 PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
54488 pPage->pLruPrev = &pGroup->lru;
54489 (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
54491 pCache->nRecyclable++;
54494 pcache1LeaveMutex(pCache->pGroup);
54510 assert( pPage->iKey==iOld );
54511 assert( pPage->pCache==pCache );
54514 pcache1EnterMutex(pCache->pGroup);
54517 hOld = iOld%pCache->nHash;
54518 pp = &pCache->apHash[hOld];
54520 pp = &(*pp)->pNext;
54522 *pp = pPage->pNext;
54525 hNew = iNew%pCache->nHash;
54526 pPage->iKey = iNew;
54527 pPage->pNext = pCache->apHash[hNew];
54528 pCache->apHash[hNew] = pPage;
54529 if( iNew>pCache->iMaxKey ){
54530 pCache->iMaxKey = iNew;
54533 pcache1LeaveMutex(pCache->pGroup);
54545 pcache1EnterMutex(pCache->pGroup);
54546 if( iLimit<=pCache->iMaxKey ){
54548 pCache->iMaxKey = iLimit-1;
54550 pcache1LeaveMutex(pCache->pGroup);
54560 PGroup *pGroup = pCache->pGroup;
54561 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
54563 if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
54564 assert( pGroup->nMaxPage >= pCache->nMax );
54565 pGroup->nMaxPage -= pCache->nMax;
54566 assert( pGroup->nMinPage >= pCache->nMin );
54567 pGroup->nMinPage -= pCache->nMin;
54568 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
54571 sqlite3_free(pCache->pBulk);
54572 sqlite3_free(pCache->apHash);
54632 && p->isAnchor==0
54634 nFree += pcache1MemSize(p->page.pBuf);
54658 for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
54674 ** The author disclaims copyright to this source code. In place of
54718 ** a non-zero batch number, it will see all prior INSERTs.
54746 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
54783 struct RowSetEntry *pFresh; /* Source of new entry objects */
54804 p->pChunk = 0;
54805 p->db = db;
54806 p->pEntry = 0;
54807 p->pLast = 0;
54808 p->pForest = 0;
54809 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
54810 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
54811 p->rsFlags = ROWSET_SORTED;
54812 p->iBatch = 0;
54825 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
54826 pNextChunk = pChunk->pNextChunk;
54827 sqlite3DbFree(p->db, pChunk);
54829 p->pChunk = 0;
54830 p->nFresh = 0;
54831 p->pEntry = 0;
54832 p->pLast = 0;
54833 p->pForest = 0;
54834 p->rsFlags = ROWSET_SORTED;
54844 sqlite3DbFree(((RowSet*)pArg)->db, pArg);
54852 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
54857 if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
54861 pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
54865 pNew->pNextChunk = p->pChunk;
54866 p->pChunk = pNew;
54867 p->pFresh = pNew->aEntry;
54868 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
54870 p->nFresh--;
54871 return p->pFresh++;
54885 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
54889 pEntry->v = rowid;
54890 pEntry->pRight = 0;
54891 pLast = p->pLast;
54893 if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
54896 p->rsFlags &= ~ROWSET_SORTED;
54898 pLast->pRight = pEntry;
54900 p->pEntry = pEntry;
54902 p->pLast = pEntry;
54921 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
54922 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
54923 if( pA->v<=pB->v ){
54924 if( pA->v<pB->v ) pTail = pTail->pRight = pA;
54925 pA = pA->pRight;
54927 pTail->pRight = pB;
54931 pTail = pTail->pRight = pB;
54932 pB = pB->pRight;
54934 pTail->pRight = pA;
54952 pNext = pIn->pRight;
54953 pIn->pRight = 0;
54981 if( pIn->pLeft ){
54983 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
54984 p->pRight = pIn;
54988 if( pIn->pRight ){
54989 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
54993 assert( (*ppLast)->pRight==0 );
55016 if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
55020 if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
55024 pLeft = rowSetNDeepTree(ppList, iDepth-1);
55026 if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
55031 p->pLeft = pLeft;
55032 *ppList = p->pRight;
55033 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
55036 *ppList = p->pRight;
55037 p->pLeft = p->pRight = 0;
55053 pList = p->pRight;
55054 p->pLeft = p->pRight = 0;
55058 pList = p->pRight;
55059 p->pLeft = pLeft;
55060 p->pRight = rowSetNDeepTree(&pList, iDepth);
55080 assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
55083 if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
55084 if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
55085 p->pEntry = rowSetEntrySort(p->pEntry);
55087 p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
55091 if( p->pEntry ){
55092 *pRowid = p->pEntry->v;
55093 p->pEntry = p->pEntry->pRight;
55094 if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
55109 ** on pRowSet->pEntry, then sort those entries into the forest at
55110 ** pRowSet->pForest so that they can be tested.
55116 assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
55121 if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
55122 p = pRowSet->pEntry;
55124 struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
55125 if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
55129 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
55130 ppPrevTree = &pTree->pRight;
55131 if( pTree->pLeft==0 ){
55132 pTree->pLeft = rowSetListToTree(p);
55136 rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
55137 pTree->pLeft = 0;
55144 pTree->v = 0;
55145 pTree->pRight = 0;
55146 pTree->pLeft = rowSetListToTree(p);
55149 pRowSet->pEntry = 0;
55150 pRowSet->pLast = 0;
55151 pRowSet->rsFlags |= ROWSET_SORTED;
55153 pRowSet->iBatch = iBatch;
55159 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
55160 p = pTree->pLeft;
55162 if( p->v<iRowid ){
55163 p = p->pRight;
55164 }else if( p->v>iRowid ){
55165 p = p->pLeft;
55179 ** The author disclaims copyright to this source code. In place of
55203 ** The author disclaims copyright to this source code. In place of
55211 ** This header file defines the interface to the write-ahead logging
55251 /* Connection to a write-ahead log (WAL) file.
55256 /* Open and close a connection to a write-ahead log. */
55264 ** snapshot is like a read-transaction. It is the state of the database
55273 /* Read a page from the write-ahead log, if it is present. */
55300 Wal *pWal, /* Write-ahead log connection */
55324 /* Return true if the argument is non-NULL and the WAL module is using
55325 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
55326 ** WAL module is using shared-memory, return false.
55340 ** stored in each frame (i.e. the db page-size when the WAL was created).
55407 ** (6) If a super-journal file is used, then all writes to the database file
55408 ** are synced prior to the super-journal being deleted.
55424 ** method is a no-op, but that does not change the fact the SQLite will
55435 ** (11) A database file is well-formed at the beginning and at the conclusion
55459 ** to print out file-descriptors.
55462 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
55465 #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
55473 ** OPEN <------+------+
55476 ** +---------> READER-------+ |
55479 ** |<-------WRITER_LOCKED------> ERROR
55482 ** |<------WRITER_CACHEMOD-------->|
55485 ** |<-------WRITER_DBMOD---------->|
55488 ** +<------WRITER_FINISHED-------->+
55493 ** OPEN -> READER [sqlite3PagerSharedLock]
55494 ** READER -> OPEN [pager_unlock]
55496 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
55497 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
55498 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
55499 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
55500 ** WRITER_*** -> READER [pager_end_transaction]
55502 ** WRITER_*** -> ERROR [pager_error]
55503 ** ERROR -> OPEN [pager_unlock]
55509 ** state - the file may or may not be locked and the database size is
55519 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
55520 ** was) in exclusive-locking mode, a user-level read transaction is
55524 ** it opens a read-transaction on the database and returns to state
55525 ** OPEN after the read-transaction is completed. However a connection
55527 ** this state even after the read-transaction is closed. The only way
55531 ** * A read transaction may be active (but a write-transaction cannot).
55533 ** * The dbSize variable may be trusted (even if a user-level read
55537 ** * Even if a read-transaction is not open, it is guaranteed that
55538 ** there is no hot-journal in the file-system.
55542 ** The pager moves to this state from READER when a write-transaction
55544 ** required to start a write-transaction are held, but no actual
55559 ** * If the connection is open in rollback-mode, a RESERVED or greater
55561 ** * If the connection is open in WAL-mode, a WAL write transaction
55600 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
55616 ** The ERROR state is entered when an IO or disk-full error (including
55618 ** difficult to be sure that the in-memory pager state (cache contents,
55619 ** db size etc.) are consistent with the contents of the file-system.
55621 ** Temporary pager files may enter the ERROR state, but in-memory pagers
55625 ** the contents of the page-cache may be left in an inconsistent state.
55637 ** page-cache and any other in-memory state at the same time. Everything
55638 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
55639 ** when a read-transaction is next opened on the pager (transitioning
55655 ** In other cases, the error is returned to the b-tree layer. The b-tree
55659 ** Condition (3) is necessary because it can be triggered by a read-only
55661 ** code were simply returned to the user, the b-tree layer would not
55663 ** read-only statement cannot leave the pager in an internally inconsistent
55669 ** * The pager is not an in-memory pager.
55679 ** state. There are two exceptions: immediately after exclusive-mode has
55695 ** following locking-states, according to the lock currently held on
55703 ** pagerUnlockDb() take a conservative approach - eLock is always updated
55714 ** from ERROR to OPEN state. At this point there may be a hot-journal file
55715 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
55719 ** of hot-journal detection.
55725 ** a hot-journal may be mistaken for a journal being created by an active
55732 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
55733 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
55734 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
55748 if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
55750 if( P->xCodec==0 ){ O=(char*)D; }else \
55751 if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
55753 # define CODEC1(P,D,N,X,E) /* NO-OP */
55773 ** set to 0. If a journal-header is written into the main journal while
55776 ** journal before the journal-header. This is required during savepoint
55785 Pgno iSubRec; /* Index of first record in sub-journal */
55810 ** For a real on-disk database, the current lock held on the database file -
55813 ** For a temporary or in-memory database (neither of which require any
55825 ** This boolean variable is used to make sure that the change-counter
55826 ** (the 4-byte header field at byte offset 24 of the database file) is
55829 ** It is set to true when the change-counter field is updated, which
55834 ** updating the change-counter is omitted for the current transaction.
55837 ** need only update the change-counter once, for the first transaction
55843 ** (or may not) specify a super-journal name to be written into the
55846 ** Whether or not a journal file contains a super-journal pointer affects
55849 ** If a journal file does not contain a super-journal pointer, it is
55851 ** it does contain a super-journal pointer the journal file is finalized
55855 ** Journal files that contain super-journal pointers cannot be finalized
55856 ** simply by overwriting the first journal-header with zeroes, as the
55857 ** super-journal pointer could interfere with hot-journal rollback of any
55867 ** This variables control the behavior of cache-spills (calls made by
55869 ** to the file-system in order to free up memory).
55881 ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
55882 ** is larger than the database page-size in order to prevent a journal sync
55887 ** This is a boolean variable. If true, then any required sub-journal
55888 ** is opened as an in-memory journal file. If false, then in-memory
55889 ** sub-journals are only used for in-memory pager files.
55892 ** write-transaction is opened.
55903 ** is not an integer multiple of the page-size, the value stored in
55904 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
55906 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
55909 ** During a write-transaction, if pages with page-numbers greater than
55920 ** Throughout a write-transaction, dbFileSize contains the size of
55922 ** write-transaction is first opened, and updated when VFS calls are made
55942 ** write-transaction is opened (at the same time as dbFileSize and
55945 ** size-hint passed to the method call. See pager_write_pagelist() for
55953 ** sub-codes.
55979 u8 readOnly; /* True for a read-only database */
55981 u8 memVfs; /* VFS-implemented memory database */
55994 u8 changeCountDone; /* Set after incrementing the change-counter */
55995 u8 setSuper; /* Super-jrnl name is written into jrnl */
55996 u8 doNotSpill; /* Do not spill the cache when non-zero */
55997 u8 subjInMemory; /* True to use in-memory sub-journals */
56005 int nRec; /* Pages journalled since last j-header written */
56006 u32 cksumInit; /* Quasi-random value added to every checksum */
56007 u32 nSubRec; /* Number of records written to sub-journal */
56011 sqlite3_file *sjfd; /* File descriptor for sub-journal */
56024 ** End of the routinely-changing class members
56027 u16 nExtra; /* Add this many bytes to each in-memory page */
56054 Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
56055 char *zWal; /* File name for write-ahead log */
56072 ** a non-testing build. These variables are not thread-safe.
56091 ** written, semi-random garbage data might appear in the journal
56098 ** of a 32-bit checksum on each page of data. The checksum covers both
56099 ** the page number and the pPager->pageSize bytes of data for the page.
56100 ** This cksum is initialized to a 32-bit random value that appears in the
56116 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
56122 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
56125 ** The macro MEMDB is true if we are dealing with an in-memory database.
56133 # define MEMDB pPager->memDb
56138 ** interfaces to access the database using memory-mapped I/O.
56141 # define USEFETCH(x) ((x)->bUseFetch)
56148 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
56152 ** if( isOpen(pPager->jfd) ){ ...
56156 ** if( pPager->jfd->pMethods ){ ...
56158 #define isOpen(pFd) ((pFd)->pMethods!=0)
56163 ** by the b-tree layer. This is the case if:
56170 if( pPager->fd->pMethods==0 ) return 0;
56171 if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0;
56173 if( pPager->xCodec!=0 ) return 0;
56176 if( pPager->pWal ){
56179 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
56188 # define pagerUseWal(x) ((x)->pWal!=0)
56210 assert( p->eState==PAGER_OPEN
56211 || p->eState==PAGER_READER
56212 || p->eState==PAGER_WRITER_LOCKED
56213 || p->eState==PAGER_WRITER_CACHEMOD
56214 || p->eState==PAGER_WRITER_DBMOD
56215 || p->eState==PAGER_WRITER_FINISHED
56216 || p->eState==PAGER_ERROR
56219 /* Regardless of the current state, a temp-file connection always behaves
56221 ** the change-counter field, so the changeCountDone flag is always set.
56223 assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
56224 assert( p->tempFile==0 || pPager->changeCountDone );
56226 /* If the useJournal flag is clear, the journal-mode must be "OFF".
56227 ** And if the journal-mode is "OFF", the journal file must not be open.
56229 assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
56230 assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
56232 /* Check that MEMDB implies noSync. And an in-memory journal. Since
56233 ** this means an in-memory pager performs no IO at all, it cannot encounter
56235 ** a journal file. (although the in-memory journal implementation may
56237 ** is therefore not possible for an in-memory pager to enter the ERROR
56241 assert( !isOpen(p->fd) );
56242 assert( p->noSync );
56243 assert( p->journalMode==PAGER_JOURNALMODE_OFF
56244 || p->journalMode==PAGER_JOURNALMODE_MEMORY
56246 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
56253 assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
56254 assert( p->eLock!=PENDING_LOCK );
56256 switch( p->eState ){
56259 assert( pPager->errCode==SQLITE_OK );
56260 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
56264 assert( pPager->errCode==SQLITE_OK );
56265 assert( p->eLock!=UNKNOWN_LOCK );
56266 assert( p->eLock>=SHARED_LOCK );
56270 assert( p->eLock!=UNKNOWN_LOCK );
56271 assert( pPager->errCode==SQLITE_OK );
56273 assert( p->eLock>=RESERVED_LOCK );
56275 assert( pPager->dbSize==pPager->dbOrigSize );
56276 assert( pPager->dbOrigSize==pPager->dbFileSize );
56277 assert( pPager->dbOrigSize==pPager->dbHintSize );
56278 assert( pPager->setSuper==0 );
56282 assert( p->eLock!=UNKNOWN_LOCK );
56283 assert( pPager->errCode==SQLITE_OK );
56290 assert( p->eLock>=RESERVED_LOCK );
56291 assert( isOpen(p->jfd)
56292 || p->journalMode==PAGER_JOURNALMODE_OFF
56293 || p->journalMode==PAGER_JOURNALMODE_WAL
56296 assert( pPager->dbOrigSize==pPager->dbFileSize );
56297 assert( pPager->dbOrigSize==pPager->dbHintSize );
56301 assert( p->eLock==EXCLUSIVE_LOCK );
56302 assert( pPager->errCode==SQLITE_OK );
56304 assert( p->eLock>=EXCLUSIVE_LOCK );
56305 assert( isOpen(p->jfd)
56306 || p->journalMode==PAGER_JOURNALMODE_OFF
56307 || p->journalMode==PAGER_JOURNALMODE_WAL
56308 || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
56310 assert( pPager->dbOrigSize<=pPager->dbHintSize );
56314 assert( p->eLock==EXCLUSIVE_LOCK );
56315 assert( pPager->errCode==SQLITE_OK );
56317 assert( isOpen(p->jfd)
56318 || p->journalMode==PAGER_JOURNALMODE_OFF
56319 || p->journalMode==PAGER_JOURNALMODE_WAL
56320 || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
56329 assert( pPager->errCode!=SQLITE_OK );
56330 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
56363 , p->zFilename
56364 , p->eState==PAGER_OPEN ? "OPEN" :
56365 p->eState==PAGER_READER ? "READER" :
56366 p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
56367 p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
56368 p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
56369 p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
56370 p->eState==PAGER_ERROR ? "ERROR" : "?error?"
56371 , (int)p->errCode
56372 , p->eLock==NO_LOCK ? "NO_LOCK" :
56373 p->eLock==RESERVED_LOCK ? "RESERVED" :
56374 p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
56375 p->eLock==SHARED_LOCK ? "SHARED" :
56376 p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
56377 , p->exclusiveMode ? "exclusive" : "normal"
56378 , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
56379 p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
56380 p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
56381 p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
56382 p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
56383 p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
56384 , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
56385 , p->journalOff, p->journalHdr
56386 , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
56405 if( pPager->errCode ){
56406 pPager->xGet = getPageError;
56410 && pPager->xCodec==0
56413 pPager->xGet = getPageMMap;
56416 pPager->xGet = getPageNormal;
56421 ** Return true if it is necessary to write page *pPg into the sub-journal.
56422 ** A page needs to be written into the sub-journal if there exists one
56425 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
56426 ** * The bit corresponding to the page-number is not set in
56430 Pager *pPager = pPg->pPager;
56432 Pgno pgno = pPg->pgno;
56434 for(i=0; i<pPager->nSavepoint; i++){
56435 p = &pPager->aSavepoint[i];
56436 if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
56437 for(i=i+1; i<pPager->nSavepoint; i++){
56438 pPager->aSavepoint[i].bTruncateOnRelease = 0;
56451 return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
56456 ** Read a 32-bit integer from the given file descriptor. Store the integer
56460 ** All values are stored on disk as big-endian.
56472 ** Write a 32-bit integer into a string buffer in big-endian byte order.
56478 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
56499 assert( !pPager->exclusiveMode || pPager->eLock==eLock );
56502 if( isOpen(pPager->fd) ){
56503 assert( pPager->eLock>=eLock );
56504 rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
56505 if( pPager->eLock!=UNKNOWN_LOCK ){
56506 pPager->eLock = (u8)eLock;
56510 pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */
56528 if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
56529 rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
56530 if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
56531 pPager->eLock = (u8)eLock;
56539 ** This function determines whether or not the atomic-write or
56540 ** atomic-batch-write optimizations can be used with this pager. The
56541 ** atomic-write optimization can be used if:
56551 ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
56552 ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
56564 assert( isOpen(pPager->fd) );
56565 dc = sqlite3OsDeviceCharacteristics(pPager->fd);
56571 if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
56572 return -1;
56578 int nSector = pPager->sectorSize;
56579 int szPage = pPager->pageSize;
56601 ** Return a 32-bit hash of the page data for pPage.
56612 return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
56615 pPage->pageHash = pager_pagehash(pPage);
56621 ** that the page is either dirty or still matches the calculated page-hash.
56625 Pager *pPager = pPg->pPager;
56626 assert( pPager->eState!=PAGER_ERROR );
56627 assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
56639 ** This function attempts to read a super-journal file name from the
56642 ** used to store a super-journal file name at the end of a journal file.
56646 ** enough space to write the super-journal name). If the super-journal
56648 ** nul-terminator), then this is handled as if no super-journal name
56651 ** If a super-journal file name is present at the end of the journal
56653 ** nul-terminator byte is appended to the buffer following the
56654 ** super-journal file name.
56656 ** If it is determined that no super-journal file name is present
56664 u32 len; /* Length in bytes of super-journal name */
56673 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
56675 || len>szJ-16
56677 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
56678 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
56680 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len))
56685 /* See if the checksum matches the super-journal name */
56687 cksum -= zSuper[u];
56691 ** containing the super-journal filename is corrupted. This means
56693 ** super-journal filename.
56705 ** following the value in pPager->journalOff, assuming a sector
56706 ** size of pPager->sectorSize bytes.
56711 ** ---------------------------------------
56720 i64 c = pPager->journalOff;
56722 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
56726 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
56733 ** This function is a no-op if the journal file has not been written to
56736 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
56738 ** zero the 28-byte header at the start of the journal file. In either case,
56739 ** if the pager is not in no-sync mode, sync the journal file immediately
56742 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
56753 assert( isOpen(pPager->jfd) );
56754 assert( !sqlite3JournalIsInMemory(pPager->jfd) );
56755 if( pPager->journalOff ){
56756 const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
56760 rc = sqlite3OsTruncate(pPager->jfd, 0);
56763 rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
56765 if( rc==SQLITE_OK && !pPager->noSync ){
56766 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
56777 rc = sqlite3OsFileSize(pPager->jfd, &sz);
56779 rc = sqlite3OsTruncate(pPager->jfd, iLimit);
56792 ** - 8 bytes: Magic identifying journal format.
56793 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
56794 ** - 4 bytes: Random number used for page hash.
56795 ** - 4 bytes: Initial database page count.
56796 ** - 4 bytes: Sector size used by the process that wrote this journal.
56797 ** - 4 bytes: Database page size.
56799 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
56803 char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
56804 u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
56808 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
56818 for(ii=0; ii<pPager->nSavepoint; ii++){
56819 if( pPager->aSavepoint[ii].iHdrOffset==0 ){
56820 pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
56824 pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
56827 ** Write the nRec Field - the number of page records that follow this
56830 ** if in full-sync mode), the zero is overwritten with the true number
56840 ** * When the pager is in no-sync mode. Corruption can follow a
56846 assert( isOpen(pPager->fd) || pPager->noSync );
56847 if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
56848 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
56856 /* The random check-hash initializer */
56857 sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
56858 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
56860 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
56862 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
56865 put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
56873 nHeader-(sizeof(aJournalMagic)+20));
56884 ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
56887 ** The loop is required here in case the sector-size is larger than the
56893 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
56894 rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
56895 assert( pPager->journalHdr <= pPager->journalOff );
56896 pPager->journalOff += nHeader;
56906 ** pPager->journalOff. See comments above function writeJournalHdr() for
56911 ** database before the transaction began, in pages. Also, pPager->cksumInit
56930 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
56936 pPager->journalOff = journalHdrOffset(pPager);
56937 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
56940 iHdrOff = pPager->journalOff;
56947 if( isHot || iHdrOff!=pPager->journalHdr ){
56948 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
56957 /* Read the first three 32-bit fields of the journal header: The nRec
56958 ** field, the checksum-initializer and the database size at the start
56961 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
56962 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
56963 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
56968 if( pPager->journalOff==0 ){
56969 u32 iPageSize; /* Page-size field of journal header */
56970 u32 iSectorSize; /* Sector-size field of journal header */
56972 /* Read the page-size and sector-size journal header fields. */
56973 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
56974 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
56979 /* Versions of SQLite prior to 3.5.8 set the page-size field of the
56984 iPageSize = pPager->pageSize;
56987 /* Check that the values read from the page-size and sector-size fields
56994 || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
56996 /* If the either the page-size or sector-size in the journal-header is
56997 ** invalid, then the process that wrote the journal-header must have
57004 /* Update the page-size to match the value read from the journal.
57008 rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
57011 /* Update the assumed sector-size to match the value used by
57017 pPager->sectorSize = iSectorSize;
57020 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
57026 ** Write the supplied super-journal name into the journal file for pager
57027 ** pPager at the current location. The super-journal name must be the last
57028 ** thing written to a journal file. If the pager is in full-sync mode, the
57033 ** + N bytes: super-journal filename in utf-8.
57034 ** + 4 bytes: N (length of super-journal name in bytes, no nul-terminator).
57035 ** + 4 bytes: super-journal name checksum.
57038 ** The super-journal page checksum is the sum of the bytes in thesuper-journal
57039 ** name, where each byte is interpreted as a signed 8-bit integer.
57042 ** this call is a no-op.
57051 assert( pPager->setSuper==0 );
57055 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
57056 || !isOpen(pPager->jfd)
57060 pPager->setSuper = 1;
57061 assert( pPager->journalHdr <= pPager->journalOff );
57068 /* If in full-sync mode, advance to the next disk sector before writing
57069 ** the super-journal name. This is in case the previous page written to
57072 if( pPager->fullSync ){
57073 pPager->journalOff = journalHdrOffset(pPager);
57075 iHdrOff = pPager->journalOff;
57077 /* Write the super-journal data to the end of the journal file. If
57080 if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_SJ_PGNO(pPager))))
57081 || (0 != (rc = sqlite3OsWrite(pPager->jfd, zSuper, nSuper, iHdrOff+4)))
57082 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper, nSuper)))
57083 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper+4, cksum)))
57084 || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
57089 pPager->journalOff += (nSuper+20);
57091 /* If the pager is in peristent-journal mode, then the physical
57092 ** journal-file may extend past the end of the super-journal name
57094 ** dangerous because the code to rollback a hot-journal file
57095 ** will not be able to find the super-journal name to determine
57101 if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
57102 && jrnlSize>pPager->journalOff
57104 rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
57110 ** Discard the entire contents of the in-memory page-cache.
57113 pPager->iDataVersion++;
57114 sqlite3BackupRestart(pPager->pBackup);
57115 sqlite3PcacheClear(pPager->pPCache);
57119 ** Return the pPager->iDataVersion value
57122 return pPager->iDataVersion;
57127 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
57132 for(ii=0; ii<pPager->nSavepoint; ii++){
57133 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
57135 if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
57136 sqlite3OsClose(pPager->sjfd);
57138 sqlite3_free(pPager->aSavepoint);
57139 pPager->aSavepoint = 0;
57140 pPager->nSavepoint = 0;
57141 pPager->nSubRec = 0;
57153 for(ii=0; ii<pPager->nSavepoint; ii++){
57154 PagerSavepoint *p = &pPager->aSavepoint[ii];
57155 if( pgno<=p->nOrig ){
57156 rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
57165 ** This function is a no-op if the pager is in exclusive mode and not
57169 ** If the pager is not in exclusive-access mode, the database file is
57170 ** completely unlocked. If the file is unlocked and the file-system does
57176 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
57177 ** or not, any journal file left in the file-system will be treated
57178 ** as a hot-journal and rolled back the next time a read-transaction
57183 assert( pPager->eState==PAGER_READER
57184 || pPager->eState==PAGER_OPEN
57185 || pPager->eState==PAGER_ERROR
57188 sqlite3BitvecDestroy(pPager->pInJournal);
57189 pPager->pInJournal = 0;
57193 assert( !isOpen(pPager->jfd) );
57194 sqlite3WalEndReadTransaction(pPager->pWal);
57195 pPager->eState = PAGER_OPEN;
57196 }else if( !pPager->exclusiveMode ){
57198 int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
57212 || 1!=(pPager->journalMode & 5)
57214 sqlite3OsClose(pPager->jfd);
57223 if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
57224 pPager->eLock = UNKNOWN_LOCK;
57228 ** without clearing the error code. This is intentional - the error
57231 assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
57232 pPager->eState = PAGER_OPEN;
57238 ** normal and exclusive-locking mode.
57240 assert( pPager->errCode==SQLITE_OK || !MEMDB );
57241 if( pPager->errCode ){
57242 if( pPager->tempFile==0 ){
57244 pPager->changeCountDone = 0;
57245 pPager->eState = PAGER_OPEN;
57247 pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
57249 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
57250 pPager->errCode = SQLITE_OK;
57254 pPager->journalOff = 0;
57255 pPager->journalHdr = 0;
57256 pPager->setSuper = 0;
57263 ** the error-code about to be returned by a pager API function. The
57267 ** IOERR sub-codes, the pager enters the ERROR state and the error code
57271 ** The ERROR state indicates that the contents of the pager-cache
57273 ** the contents of the pager-cache. If a transaction was active when
57276 ** it were a hot-journal).
57282 pPager->errCode==SQLITE_FULL ||
57283 pPager->errCode==SQLITE_OK ||
57284 (pPager->errCode & 0xff)==SQLITE_IOERR
57287 pPager->errCode = rc;
57288 pPager->eState = PAGER_ERROR;
57304 ** * For non-TEMP databases, always sync to disk. This is necessary
57313 if( pPager->tempFile==0 ) return 1;
57315 if( !isOpen(pPager->fd) ) return 0;
57316 return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
57322 ** after rollback of a hot-journal, or if an error occurs while opening
57323 ** the journal file or writing the very first journal-header of a
57328 ** exclusive than a RESERVED lock, it is a no-op.
57334 ** transaction. Nor will it be considered to be a hot-journal by this
57337 ** the current journal-mode (Pager.journalMode value), as follows:
57341 ** in-memory journal.
57360 ** If running in non-exclusive rollback mode, the lock on the file is
57378 ** is no write-transaction active but a RESERVED or greater lock is
57381 ** 1. After a successful hot-journal rollback, it is called with
57386 ** read-transaction, this function is called with eState==PAGER_READER
57387 ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
57390 assert( pPager->eState!=PAGER_ERROR );
57391 if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
57396 assert( isOpen(pPager->jfd) || pPager->pInJournal==0
57397 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
57399 if( isOpen(pPager->jfd) ){
57403 if( sqlite3JournalIsInMemory(pPager->jfd) ){
57404 /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
57405 sqlite3OsClose(pPager->jfd);
57406 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
57407 if( pPager->journalOff==0 ){
57410 rc = sqlite3OsTruncate(pPager->jfd, 0);
57411 if( rc==SQLITE_OK && pPager->fullSync ){
57417 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
57420 pPager->journalOff = 0;
57421 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
57422 || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
57424 rc = zeroJournalHdr(pPager, hasSuper||pPager->tempFile);
57425 pPager->journalOff = 0;
57428 ** a hot-journal was just rolled back. In this case the journal
57430 ** the database file, it will do so using an in-memory journal.
57432 int bDelete = !pPager->tempFile;
57433 assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
57434 assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
57435 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
57436 || pPager->journalMode==PAGER_JOURNALMODE_WAL
57438 sqlite3OsClose(pPager->jfd);
57440 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
57446 sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
57447 if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
57450 p->pageHash = 0;
57456 sqlite3BitvecDestroy(pPager->pInJournal);
57457 pPager->pInJournal = 0;
57458 pPager->nRec = 0;
57461 sqlite3PcacheCleanAll(pPager->pPCache);
57463 sqlite3PcacheClearWritable(pPager->pPCache);
57465 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
57469 /* Drop the WAL write-lock, if any. Also, if the connection was in
57473 rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
57475 }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
57476 /* This branch is taken when committing a transaction in rollback-journal
57482 assert( pPager->eLock==EXCLUSIVE_LOCK );
57483 rc = pager_truncate(pPager, pPager->dbSize);
57487 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
57491 if( !pPager->exclusiveMode
57492 && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
57496 pPager->eState = PAGER_READER;
57497 pPager->setSuper = 0;
57508 ** call to pager_unlock() will discard all in-memory pages, unlock
57510 ** means that there is a hot-journal left in the file-system, the next
57520 if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
57522 if( pPager->eState>=PAGER_WRITER_LOCKED ){
57526 }else if( !pPager->exclusiveMode ){
57527 assert( pPager->eState==PAGER_READER );
57535 ** Parameter aData must point to a buffer of pPager->pageSize bytes
57537 ** page of data and the current value of pPager->cksumInit.
57540 ** random initial value (pPager->cksumInit) and every 200th byte
57541 ** of the page data, starting with byte offset (pPager->pageSize%200).
57542 ** Each byte is interpreted as an 8-bit unsigned integer.
57554 u32 cksum = pPager->cksumInit; /* Checksum value to return */
57555 int i = pPager->pageSize-200; /* Loop counter */
57558 i -= 200;
57569 if( pPager->xCodecSizeChng ){
57570 pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
57571 (int)pPager->nReserve);
57575 # define pagerReportSize(X) /* No-op if we do not support a codec */
57581 ** pager as it is in the source. This comes up when a VACUUM changes the
57585 if( pDest->nReserve!=pSrc->nReserve ){
57586 pDest->nReserve = pSrc->nReserve;
57594 ** from the sub-journal (if isMainJrnl==0) and playback that page.
57598 ** The main rollback journal uses checksums - the statement journal does
57601 ** If the page number of the page record read from the (sub-)journal file
57611 ** If the page record is successfully read from the (sub-)journal file
57613 ** while reading the record from the (sub-)journal file or while writing
57615 ** is successfully read from the (sub-)journal file but appears to be
57619 ** * If the record page-number is illegal (0 or PAGER_SJ_PGNO), or
57633 int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
57645 ** the codec. It is false for pure in-memory journals. */
57646 const int jrnlEnc = (isMainJrnl || pPager->subjInMemory==0);
57651 assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
57652 assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
57654 aData = pPager->pTmpSpace;
57660 ** a hot-journal rollback. If it is a hot-journal rollback, the pager
57661 ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
57662 ** only reads from the main journal, not the sub-journal.
57664 assert( pPager->eState>=PAGER_WRITER_CACHEMOD
57665 || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
57667 assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
57669 /* Read the page number and page data from the journal or sub-journal
57672 jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
57675 rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
57677 *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
57688 if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
57692 rc = read32bits(jfd, (*pOffset)-4, &cksum);
57708 if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
57709 pPager->nReserve = ((u8*)aData)[20];
57716 ** An exception to the above rule: If the database is in no-sync mode
57726 ** a hot-journal rollback, it is guaranteed that the page-cache is empty
57743 ** 2008-04-14: When attempting to vacuum a corrupt database file, it
57753 assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
57755 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
57756 (isMainJrnl?"main-journal":"sub-journal")
57759 isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
57761 isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
57763 if( isOpen(pPager->fd)
57764 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
57767 i64 ofst = (pgno-1)*(i64)pPager->pageSize;
57768 testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
57772 ** This is usually safe even for an encrypted database - as the data
57774 ** is if the data was just read from an in-memory sub-journal. In that
57780 rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
57784 rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
57786 if( pgno>pPager->dbFileSize ){
57787 pPager->dbFileSize = pgno;
57789 if( pPager->pBackup ){
57793 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
57797 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
57801 ** the database and the page is not in-memory, there is a potential
57802 ** problem. When the page is next fetched by the b-tree layer, it
57808 ** if the page is on the free-list at the start of the transaction, then
57811 ** The solution is to add an in-memory page to the cache containing
57812 ** the data just read from the sub-journal. Mark the page as dirty
57813 ** and if the pager requires a journal-sync, then mark the page as
57814 ** requiring a journal-sync before it is written.
57817 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
57818 pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
57820 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
57821 pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
57833 pData = pPg->pData;
57834 memcpy(pData, (u8*)aData, pPager->pageSize);
57835 pPager->xReiniter(pPg);
57845 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
57850 if( jrnlEnc ){ CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT); }
57858 ** Parameter zSuper is the name of a super-journal file. A single journal
57859 ** file that referred to the super-journal file has just been rolled back.
57860 ** This routine checks if it is possible to delete the super-journal file,
57866 ** When a super-journal file is created, it is populated with the names
57867 ** of all of its child journals, one after another, formatted as utf-8
57869 ** nul-terminator byte (0x00). i.e. the entire contents of a super-journal
57872 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
57874 ** A super-journal file may only be deleted once all of its child
57877 ** This function reads the contents of the super-journal file into
57882 ** * if the child journal contains a reference to super-journal
57888 ** the file-system using sqlite3OsDelete().
57896 ** the entire contents of the super-journal file. This could be
57897 ** a couple of kilobytes or so - potentially larger than the page
57901 sqlite3_vfs *pVfs = pPager->pVfs;
57903 sqlite3_file *pSuper; /* Malloc'd super-journal file descriptor */
57904 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
57905 char *zSuperJournal = 0; /* Contents of super-journal file */
57906 i64 nSuperJournal; /* Size of super-journal file */
57908 char *zSuperPtr; /* Space to hold super-journal filename */
57913 ** If successful, open the super-journal file for reading.
57915 pSuper = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
57922 pJournal = (sqlite3_file *)(((u8 *)pSuper) + pVfs->szOsFile);
57926 /* Load the entire super-journal file into space obtained from
57928 ** sufficient space (in zSuperPtr) to hold the names of super-journal
57929 ** files extracted from regular rollback-journals.
57933 nSuperPtr = pVfs->mxPathname+1;
57948 while( (zJournal-zSuperJournal)<nSuperJournal ){
57955 /* One of the journals pointed to by the super-journal exists.
57956 ** Open it and check if it points at the super-journal. If
57957 ** so, return without deleting the super-journal file.
57977 /* We have a match. Do not delete the super-journal file. */
58000 ** file in the file-system. This only happens when committing a transaction,
58001 ** or rolling back a transaction (including rolling back a hot-journal).
58004 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
58005 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
58020 assert( pPager->eState!=PAGER_ERROR );
58021 assert( pPager->eState!=PAGER_READER );
58023 if( isOpen(pPager->fd)
58024 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
58027 int szPage = pPager->pageSize;
58028 assert( pPager->eLock==EXCLUSIVE_LOCK );
58030 rc = sqlite3OsFileSize(pPager->fd, &currentSize);
58034 rc = sqlite3OsTruncate(pPager->fd, newSize);
58036 char *pTmp = pPager->pTmpSpace;
58038 testcase( (newSize-szPage) == currentSize );
58039 testcase( (newSize-szPage) > currentSize );
58040 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &newSize);
58041 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
58044 pPager->dbFileSize = nPage;
58052 ** Return a sanitized version of the sector-size of OS file pFile. The
58071 ** super-journal pointers within created journal files.
58075 ** Otherwise, for non-temporary files, the effective sector size is
58082 ** pPager->sectorSize is to define the "blast radius" of bytes that
58090 assert( isOpen(pPager->fd) || pPager->tempFile );
58092 if( pPager->tempFile
58093 || (sqlite3OsDeviceCharacteristics(pPager->fd) &
58099 pPager->sectorSize = 512;
58101 pPager->sectorSize = sqlite3SectorSize(pPager->fd);
58112 ** (2) 4 byte big-endian integer which is the number of valid page records
58115 ** (3) 4 byte big-endian integer which is the initial value for the
58119 ** (5) 4 byte big-endian integer which is the sector size. The header
58121 ** (6) 4 byte big-endian integer which is the page size.
58125 ** + pPager->pageSize bytes of data.
58142 ** no-sync option for the journal. A power failure could lead to corruption
58146 ** If the file opened as the journal file is not a well-formed
58152 ** If an I/O or malloc() error occurs, the journal-file is not deleted
58163 sqlite3_vfs *pVfs = pPager->pVfs;
58170 char *zSuper = 0; /* Name of super-journal file if any */
58173 u32 savedPageSize = pPager->pageSize;
58178 assert( isOpen(pPager->jfd) );
58179 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
58184 /* Read the super-journal name from the journal, if it is present.
58185 ** If a super-journal file name is specified, but the file is not
58191 ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
58195 zSuper = pPager->pTmpSpace;
58196 rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);
58204 pPager->journalOff = 0;
58226 ** working in no-sync mode. This means that the rest of the journal
58231 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
58232 nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
58250 pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
58251 nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
58257 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
58262 pPager->dbSize = mxPg;
58263 if( pPager->mxPgno<mxPg ){
58264 pPager->mxPgno = mxPg;
58276 rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
58281 pPager->journalOff = szJ;
58307 rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
58311 ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
58315 sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
58319 ** malloc error that occurred after the change-counter was updated but
58320 ** before the transaction was committed, then the change-counter
58323 ** update the change-counter at all. This may lead to cache inconsistency
58327 pPager->changeCountDone = pPager->tempFile;
58330 /* Leave 4 bytes of space before the super-journal filename in memory.
58334 zSuper = &pPager->pTmpSpace[4];
58335 rc = readSuperJournal(pPager->jfd, zSuper, pPager->pVfs->mxPathname+1);
58339 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
58348 /* If there was a super-journal and this routine will return success,
58349 ** see if it is possible to delete the super-journal.
58351 assert( zSuper==&pPager->pTmpSpace[4] );
58352 memset(&zSuper[-4], 0, 4);
58358 nPlayback, pPager->zJournal);
58373 ** pPg->pData. A shared lock or greater must be held on the database
58383 Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
58389 assert( pPager->eState>=PAGER_READER && !MEMDB );
58390 assert( isOpen(pPager->fd) );
58393 rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
58397 rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
58401 i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
58402 rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
58408 if( pPg->pgno==1 ){
58415 ** pPager->dbFileVers[] with all 0xff bytes should suffice.
58422 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
58424 u8 *dbFileVers = &((u8*)pPg->pData)[24];
58425 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
58428 CODEC1(pPager, pPg->pData, pPg->pgno, 3, rc = SQLITE_NOMEM_BKPT);
58431 PAGER_INCR(pPager->nRead);
58432 IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
58434 PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
58440 ** Update the value of the change-counter at offsets 24 and 92 in
58444 ** routine which only updates the change-counter if the update is actually
58445 ** needed, as determined by the pPager->changeCountDone state variable.
58452 change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
58453 put32bits(((char*)pPg->pData)+24, change_counter);
58458 put32bits(((char*)pPg->pData)+92, change_counter);
58459 put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
58488 pPager->xReiniter(pPg);
58502 sqlite3BackupRestart(pPager->pBackup);
58521 pPager->dbSize = pPager->dbOrigSize;
58522 rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
58523 pList = sqlite3PcacheDirtyList(pPager->pPCache);
58525 PgHdr *pNext = pList->pDirty;
58526 rc = pagerUndoCallback((void *)pPager, pList->pgno);
58552 assert( pPager->pWal );
58556 for(p=pList; p && p->pDirty; p=p->pDirty){
58557 assert( p->pgno < p->pDirty->pgno );
58561 assert( pList->pDirty==0 || isCommit );
58569 for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
58570 if( p->pgno<=nTruncate ){
58571 ppNext = &p->pDirty;
58579 pPager->aStat[PAGER_STAT_WRITE] += nList;
58581 if( pList->pgno==1 ) pager_write_changecounter(pList);
58582 rc = sqlite3WalFrames(pPager->pWal,
58583 pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
58585 if( rc==SQLITE_OK && pPager->pBackup ){
58586 for(p=pList; p; p=p->pDirty){
58587 sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
58592 pList = sqlite3PcacheDirtyList(pPager->pPCache);
58593 for(p=pList; p; p=p->pDirty){
58614 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
58621 sqlite3WalEndReadTransaction(pPager->pWal);
58623 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
58626 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
58645 /* Query the WAL sub-system for the database size. The WalDbsize()
58648 ** available from the WAL sub-system if the log file is empty or
58651 assert( pPager->eState==PAGER_OPEN );
58652 assert( pPager->eLock>=SHARED_LOCK );
58653 assert( isOpen(pPager->fd) );
58654 assert( pPager->tempFile==0 );
58655 nPage = sqlite3WalDbsize(pPager->pWal);
58658 ** WAL sub-system, determine the page count based on the size of
58660 ** integer multiple of the page-size, round up the result.
58662 if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
58664 int rc = sqlite3OsFileSize(pPager->fd, &n);
58668 nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
58675 if( nPage>pPager->mxPgno ){
58676 pPager->mxPgno = (Pgno)nPage;
58685 ** Check if the *-wal file that corresponds to the database opened by pPager
58686 ** exists if the database is not empy, or verify that the *-wal file does
58689 ** If the database is not empty and the *-wal file exists, open the pager
58690 ** in WAL mode. If the database is empty or if no *-wal file exists and
58698 ** a WAL on a none-empty database, this ensures there is no race condition
58704 assert( pPager->eState==PAGER_OPEN );
58705 assert( pPager->eLock>=SHARED_LOCK );
58707 if( !pPager->tempFile ){
58710 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
58719 rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
58721 testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
58724 }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
58725 pPager->journalMode = PAGER_JOURNALMODE_DELETE;
58735 ** the entire super-journal file. The case pSavepoint==NULL occurs when
58739 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
58752 ** * Pages are then played back from the sub-journal file, starting
58766 ** (or transaction). No page with a page-number greater than this value
58771 i64 iHdrOff; /* End of first segment of main-journal records */
58775 assert( pPager->eState!=PAGER_ERROR );
58776 assert( pPager->eState>=PAGER_WRITER_LOCKED );
58780 pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
58789 pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
58790 pPager->changeCountDone = pPager->tempFile;
58796 /* Use pPager->journalOff as the effective size of the main rollback
58799 ** past pPager->journalOff is off-limits to us.
58801 szJ = pPager->journalOff;
58807 ** greater than the current database size (pPager->dbSize) but those
58812 iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
58813 pPager->journalOff = pSavepoint->iOffset;
58814 while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
58815 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
58819 pPager->journalOff = 0;
58824 ** of the main journal file. Continue to skip out-of-range pages and
58827 while( rc==SQLITE_OK && pPager->journalOff<szJ ){
58835 ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
58840 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
58842 nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
58844 for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
58845 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
58849 assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
58851 /* Finally, rollback pages from the sub-journal. Page that were
58853 ** will be skipped. Out-of-range pages are also skipped.
58857 i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
58860 rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
58862 for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
58863 assert( offset==(i64)ii*(4+pPager->pageSize) );
58871 pPager->journalOff = szJ;
58878 ** Change the maximum number of in-memory pages that are allowed
58882 sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
58886 ** Change the maximum number of in-memory pages that are allowed
58890 return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
58898 sqlite3_file *fd = pPager->fd;
58899 if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
58901 sz = pPager->szMmap;
58902 pPager->bUseFetch = (sz>0);
58904 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
58913 pPager->szMmap = szMmap;
58921 sqlite3PcacheShrink(pPager->pPCache);
58943 ** database (with some additional information - the nRec field
58944 ** of the journal header - being written in between the two
58954 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
58965 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
58981 if( pPager->tempFile ){
58982 pPager->noSync = 1;
58983 pPager->fullSync = 0;
58984 pPager->extraSync = 0;
58986 pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
58987 pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
58988 pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
58990 if( pPager->noSync ){
58991 pPager->syncFlags = 0;
58993 pPager->syncFlags = SQLITE_SYNC_FULL;
58995 pPager->syncFlags = SQLITE_SYNC_NORMAL;
58997 pPager->walSyncFlags = (pPager->syncFlags<<2);
58998 if( pPager->fullSync ){
58999 pPager->walSyncFlags |= pPager->syncFlags;
59001 if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
59002 pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
59005 pPager->doNotSpill &= ~SPILLFLAG_OFF;
59007 pPager->doNotSpill |= SPILLFLAG_OFF;
59049 rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
59057 ** The pager invokes the busy-handler if sqlite3OsLock() returns
59058 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
59062 ** (which occurs during hot-journal rollback). Summary:
59065 ** --------------------------------------------------------
59066 ** NO_LOCK -> SHARED_LOCK | Yes
59067 ** SHARED_LOCK -> RESERVED_LOCK | No
59068 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
59069 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
59071 ** If the busy-handler callback returns non-zero, the lock is
59077 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
59081 pPager->xBusyHandler = xBusyHandler;
59082 pPager->pBusyHandlerArg = pBusyHandlerArg;
59083 ap = (void **)&pPager->xBusyHandler;
59086 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
59094 ** is a no-op. The value returned is the error state error code (i.e.
59095 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
59104 ** * the database is either not an in-memory database or it is
59105 ** an in-memory database that currently consists of zero pages.
59129 ** is a no-op for that case anyhow.
59134 if( (pPager->memDb==0 || pPager->dbSize==0)
59135 && sqlite3PcacheRefCount(pPager->pPCache)==0
59136 && pageSize && pageSize!=(u32)pPager->pageSize
59141 if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
59142 rc = sqlite3OsFileSize(pPager->fd, &nByte);
59145 /* 8 bytes of zeroed overrun space is sufficient so that the b-tree
59157 rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
59160 sqlite3PageFree(pPager->pTmpSpace);
59161 pPager->pTmpSpace = pNew;
59162 pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
59163 pPager->pageSize = pageSize;
59164 pPager->lckPgno = (Pgno)(PENDING_BYTE/pageSize) + 1;
59170 *pPageSize = pPager->pageSize;
59172 if( nReserve<0 ) nReserve = pPager->nReserve;
59174 pPager->nReserve = (i16)nReserve;
59189 return pPager->pTmpSpace;
59201 pPager->mxPgno = mxPage;
59203 assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
59204 /* assert( pPager->mxPgno>=pPager->dbSize ); */
59208 return pPager->mxPgno;
59216 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
59225 sqlite3_io_error_pending = -1;
59252 assert( isOpen(pPager->fd) || pPager->tempFile );
59260 if( isOpen(pPager->fd) ){
59262 rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
59271 ** This function may only be called when a read-transaction is open on
59274 ** However, if the file is between 1 and <page-size> bytes in size, then
59278 assert( pPager->eState>=PAGER_READER );
59279 assert( pPager->eState!=PAGER_WRITER_FINISHED );
59280 *pnPage = (int)pPager->dbSize;
59286 ** a similar or greater lock is already held, this function is a no-op
59301 /* Check that this is either a no-op (because the requested lock is
59302 ** already held), or one of the transitions that the busy-handler
59306 assert( (pPager->eLock>=locktype)
59307 || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
59308 || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
59313 }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
59319 ** following is true for all dirty pages currently in the page-cache:
59325 ** be necessary to write the current content out to the sub-journal.
59334 ** sub-journal rolled back the content could not be restored and the
59340 Pager *pPager = pPg->pPager;
59341 assert( pPg->flags&PGHDR_DIRTY );
59342 if( pPg->pgno>pPager->dbSize ){ /* if (a) is false */
59343 Pgno pgno = pPg->pgno;
59345 for(i=0; i<pPg->pPager->nSavepoint; i++){
59346 PagerSavepoint *p = &pPager->aSavepoint[i];
59347 assert( p->nOrig<pgno || sqlite3BitvecTestNotNull(p->pInSavepoint,pgno) );
59352 sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
59359 ** Truncate the in-memory database file image to nPage pages. This
59370 assert( pPager->dbSize>=nPage || CORRUPT_DB );
59371 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
59372 pPager->dbSize = nPage;
59387 ** This function is called before attempting a hot-journal rollback. It
59388 ** syncs the journal file to disk, then sets pPager->journalHdr to the
59392 ** Syncing a hot-journal to disk before attempting to roll it back ensures
59393 ** that if a power-failure occurs during the rollback, the process that
59402 if( !pPager->noSync ){
59403 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
59406 rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
59430 if( pPager->pMmapFreelist ){
59431 *ppPage = p = pPager->pMmapFreelist;
59432 pPager->pMmapFreelist = p->pDirty;
59433 p->pDirty = 0;
59434 assert( pPager->nExtra>=8 );
59435 memset(p->pExtra, 0, 8);
59437 *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
59439 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
59442 p->pExtra = (void *)&p[1];
59443 p->flags = PGHDR_MMAP;
59444 p->nRef = 1;
59445 p->pPager = pPager;
59448 assert( p->pExtra==(void *)&p[1] );
59449 assert( p->pPage==0 );
59450 assert( p->flags==PGHDR_MMAP );
59451 assert( p->pPager==pPager );
59452 assert( p->nRef==1 );
59454 p->pgno = pgno;
59455 p->pData = pData;
59456 pPager->nMmapOut++;
59467 Pager *pPager = pPg->pPager;
59468 pPager->nMmapOut--;
59469 pPg->pDirty = pPager->pMmapFreelist;
59470 pPager->pMmapFreelist = pPg;
59472 assert( pPager->fd->pMethods->iVersion>=3 );
59473 sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
59482 for(p=pPager->pMmapFreelist; p; p=pNext){
59483 pNext = p->pDirty;
59490 ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
59497 if( pPager->tempFile ) return SQLITE_OK;
59498 if( pPager->dbSize==0 ) return SQLITE_OK;
59499 assert( pPager->zFilename && pPager->zFilename[0] );
59500 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
59502 /* If the HAS_MOVED file-control is unimplemented, assume that the file
59528 u8 *pTmp = (u8*)pPager->pTmpSpace;
59534 /* pPager->errCode = 0; */
59535 pPager->exclusiveMode = 0;
59539 assert( db || pPager->pWal==0 );
59540 if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
59545 sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
59546 pPager->pWal = 0;
59561 ** back or finalize it. The next database user will have to do hot-journal
59564 if( isOpen(pPager->jfd) ){
59573 sqlite3OsClose(pPager->jfd);
59574 sqlite3OsClose(pPager->fd);
59576 sqlite3PcacheClose(pPager->pPCache);
59579 if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
59582 assert( !pPager->aSavepoint && !pPager->pInJournal );
59583 assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
59594 return pPg->pgno;
59608 ** disk and can be restored in the event of a hot-journal rollback.
59610 ** If the Pager.noSync flag is set, then this function is a no-op.
59611 ** Otherwise, the actions required depend on the journal-mode and the
59612 ** device characteristics of the file-system, as follows:
59614 ** * If the journal file is an in-memory journal file, no action need
59620 ** been written following it. If the pager is operating in full-sync
59626 ** Or, in pseudo-code:
59628 ** if( NOT <in-memory journal> ){
59630 ** if( <full-sync mode> ) xSync(<journal file>);
59643 assert( pPager->eState==PAGER_WRITER_CACHEMOD
59644 || pPager->eState==PAGER_WRITER_DBMOD
59652 if( !pPager->noSync ){
59653 assert( !pPager->tempFile );
59654 if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
59655 const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
59656 assert( isOpen(pPager->jfd) );
59660 ** that wrote to this database was operating in persistent-journal
59663 ** file happens to be a journal-header (written as part of the
59664 ** previous connection's transaction), and a crash or power-failure
59668 ** hot-journal rollback following recovery. It may roll back all
59670 ** out-of-date data that follows it. Database corruption.
59686 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
59689 rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
59692 rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
59699 ** full-synchronous mode, sync the journal first. This ensures that
59709 if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
59712 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
59715 IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
59717 pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
59724 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
59725 (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
59730 pPager->journalHdr = pPager->journalOff;
59732 pPager->nRec = 0;
59737 pPager->journalHdr = pPager->journalOff;
59745 sqlite3PcacheClearSyncFlags(pPager->pPCache);
59746 pPager->eState = PAGER_WRITER_DBMOD;
59754 ** in-memory pages in the list to the database file. The argument may
59756 ** a no-op.
59763 ** If the pager is a temp-file pager and the actual file-system file
59788 assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
59789 assert( pPager->eLock==EXCLUSIVE_LOCK );
59790 assert( isOpen(pPager->fd) || pList->pDirty==0 );
59792 /* If the file is a temp-file has not yet been opened, open it now. It
59794 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
59796 if( !isOpen(pPager->fd) ){
59797 assert( pPager->tempFile && rc==SQLITE_OK );
59798 rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
59804 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
59806 && pPager->dbHintSize<pPager->dbSize
59807 && (pList->pDirty || pList->pgno>pPager->dbHintSize)
59809 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
59810 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
59811 pPager->dbHintSize = pPager->dbSize;
59815 Pgno pgno = pList->pgno;
59819 ** make the file smaller (presumably by auto-vacuum code). Do not write
59825 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
59826 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
59829 assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
59830 if( pList->pgno==1 ) pager_write_changecounter(pList);
59833 CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
59836 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
59843 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
59845 if( pgno>pPager->dbFileSize ){
59846 pPager->dbFileSize = pgno;
59848 pPager->aStat[PAGER_STAT_WRITE]++;
59851 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
59861 pList = pList->pDirty;
59868 ** Ensure that the sub-journal file is open. If it is already open, this
59869 ** function is a no-op.
59877 if( !isOpen(pPager->sjfd) ){
59882 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
59883 nStmtSpill = -1;
59885 rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
59891 ** Append a record of the current state of page pPg to the sub-journal.
59893 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
59897 ** error code if the attempt to write to the sub-journal fails, or
59903 Pager *pPager = pPg->pPager;
59904 if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
59906 /* Open the sub-journal, if it has not already been opened */
59907 assert( pPager->useJournal );
59908 assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
59909 assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
59912 || pPg->pgno>pPager->dbOrigSize
59916 /* If the sub-journal was opened successfully (or was already open),
59919 void *pData = pPg->pData;
59920 i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
59924 if( !pPager->subjInMemory ){
59925 CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
59929 PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
59930 rc = write32bits(pPager->sjfd, offset, pPg->pgno);
59932 rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
59937 pPager->nSubRec++;
59938 assert( pPager->nSavepoint>0 );
59939 rc = addToSavepointBitvecs(pPager, pPg->pgno);
59954 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
59974 assert( pPg->pPager==pPager );
59975 assert( pPg->flags&PGHDR_DIRTY );
59993 if( NEVER(pPager->errCode) ) return SQLITE_OK;
59994 testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
59995 testcase( pPager->doNotSpill & SPILLFLAG_OFF );
59996 testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
59997 if( pPager->doNotSpill
59998 && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
59999 || (pPg->flags & PGHDR_NEED_SYNC)!=0)
60004 pPager->aStat[PAGER_STAT_SPILL]++;
60005 pPg->pDirty = 0;
60015 if( pPager->tempFile==0 ){
60016 rc = sqlite3JournalCreate(pPager->jfd);
60022 if( pPg->flags&PGHDR_NEED_SYNC
60023 || pPager->eState==PAGER_WRITER_CACHEMOD
60030 assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
60037 PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
60048 int rc = pPager->errCode;
60050 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
60053 PgHdr *pNext = pList->pDirty;
60054 if( pList->nRef==0 ){
60070 ** If zFilename is NULL then a randomly-named temporary file is created
60074 ** This can be used to implement an in-memory database.
60100 int nExtra, /* Extra bytes append to each in-memory page */
60108 int tempFile = 0; /* True for temp files (incl. in-memory files) */
60109 int memDb = 0; /* True if this is an in-memory file */
60115 int readOnly = 0; /* True if this is a read-only file */
60126 /* Figure out how much space is required for each journal file-handle
60127 ** (there are two of them, the main journal and the sub-journal). */
60151 nPathname = pVfs->mxPathname+1;
60174 nUriByte = (int)(&z[1] - zUri);
60176 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
60178 ** the database being opened will be more than pVfs->mxPathname
60181 ** check for a hot-journal before reading.
60197 ** Database file handle (pVfs->szOsFile bytes)
60198 ** Sub-journal file handle (journalFileSize bytes)
60208 ** Some 3rd-party software, over which we have no control, depends on
60212 ** misuse of SQLite and a bug in the 3rd-party software, but the 3rd-party
60215 ** filename format expected by 3rd-party software should be as follows:
60217 ** - Main Database Path
60218 ** - \0
60219 ** - Multiple URI components consisting of:
60220 ** - Key
60221 ** - \0
60222 ** - Value
60223 ** - \0
60224 ** - \0
60225 ** - Journal Path
60226 ** - \0
60227 ** - WAL Path (zWALName)
60228 ** - \0
60238 ROUND8(pVfs->szOsFile) + /* The main db file */
60256 pPager->pPCache = (PCache*)pPtr; pPtr += ROUND8(pcacheSize);
60257 pPager->fd = (sqlite3_file*)pPtr; pPtr += ROUND8(pVfs->szOsFile);
60258 pPager->sjfd = (sqlite3_file*)pPtr; pPtr += journalFileSize;
60259 pPager->jfd = (sqlite3_file*)pPtr; pPtr += journalFileSize;
60260 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
60265 pPager->zFilename = (char*)pPtr;
60278 pPager->zJournal = (char*)pPtr;
60280 memcpy(pPtr, "-journal",8); pPtr += 8 + 1;
60282 sqlite3FileSuffix3(zFilename,pPager->zJournal);
60283 pPtr = (u8*)(pPager->zJournal + sqlite3Strlen30(pPager->zJournal)+1);
60286 pPager->zJournal = 0;
60292 pPager->zWal = (char*)pPtr;
60294 memcpy(pPtr, "-wal", 4); pPtr += 4 + 1;
60296 sqlite3FileSuffix3(zFilename, pPager->zWal);
60297 pPtr = (u8*)(pPager->zWal + sqlite3Strlen30(pPager->zWal)+1);
60300 pPager->zWal = 0;
60306 pPager->pVfs = pVfs;
60307 pPager->vfsFlags = vfsFlags;
60313 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
60316 pPager->memVfs = memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
60329 int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
60333 if( szPageDflt<pPager->sectorSize ){
60334 if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
60337 szPageDflt = (u32)pPager->sectorSize;
60354 pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, "nolock", 0);
60356 || sqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){
60366 ** This branch is also run for an in-memory database. An in-memory
60367 ** database is the same as a temp-file that is never written out to
60368 ** disk and uses an in-memory rollback journal.
60374 pPager->eState = PAGER_READER; /* Pretend we already have a lock */
60375 pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
60376 pPager->noLock = 1; /* Do no locking */
60384 assert( pPager->memDb==0 );
60385 rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
60394 !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
60400 sqlite3OsClose(pPager->fd);
60401 sqlite3PageFree(pPager->pTmpSpace);
60406 PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
60407 IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
60409 pPager->useJournal = (u8)useJournal;
60410 /* pPager->stmtOpen = 0; */
60411 /* pPager->stmtInUse = 0; */
60412 /* pPager->nRef = 0; */
60413 /* pPager->stmtSize = 0; */
60414 /* pPager->stmtJSize = 0; */
60415 /* pPager->nPage = 0; */
60416 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
60417 /* pPager->state = PAGER_UNLOCK; */
60418 /* pPager->errMask = 0; */
60419 pPager->tempFile = (u8)tempFile;
60423 pPager->exclusiveMode = (u8)tempFile;
60424 pPager->changeCountDone = pPager->tempFile;
60425 pPager->memDb = (u8)memDb;
60426 pPager->readOnly = (u8)readOnly;
60427 assert( useJournal || pPager->tempFile );
60428 pPager->noSync = pPager->tempFile;
60429 if( pPager->noSync ){
60430 assert( pPager->fullSync==0 );
60431 assert( pPager->extraSync==0 );
60432 assert( pPager->syncFlags==0 );
60433 assert( pPager->walSyncFlags==0 );
60435 pPager->fullSync = 1;
60436 pPager->extraSync = 0;
60437 pPager->syncFlags = SQLITE_SYNC_NORMAL;
60438 pPager->walSyncFlags = SQLITE_SYNC_NORMAL | (SQLITE_SYNC_NORMAL<<2);
60440 /* pPager->pFirst = 0; */
60441 /* pPager->pFirstSynced = 0; */
60442 /* pPager->pLast = 0; */
60443 pPager->nExtra = (u16)nExtra;
60444 pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
60445 assert( isOpen(pPager->fd) || tempFile );
60448 pPager->journalMode = PAGER_JOURNALMODE_OFF;
60450 pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
60452 /* pPager->xBusyHandler = 0; */
60453 /* pPager->pBusyHandlerArg = 0; */
60454 pPager->xReiniter = xReinit;
60456 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
60457 /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
60470 while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
60471 zName--;
60473 pPager = *(Pager**)(zName - 4 - sizeof(Pager*));
60474 return pPager->fd;
60481 ** the file-system for the given pager. A hot journal is one that
60482 ** needs to be played back. According to this function, a hot-journal
60496 ** This routine does not check if there is a super-journal filename
60497 ** at the end of the file. If there is, and that super-journal file
60499 ** case this routine will return a false-positive. The pager_playback()
60503 ** If a hot-journal file is found to exist, *pExists is set to 1 and
60504 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
60506 ** to determine whether or not a hot-journal file exists, the IO error
60510 sqlite3_vfs * const pVfs = pPager->pVfs;
60513 int jrnlOpen = !!isOpen(pPager->jfd);
60515 assert( pPager->useJournal );
60516 assert( isOpen(pPager->fd) );
60517 assert( pPager->eState==PAGER_OPEN );
60519 assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
60525 rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
60535 ** in fact there is none. This results in a false-positive which will
60538 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
60542 assert( pPager->tempFile==0 );
60556 sqlite3OsDelete(pVfs, pPager->zJournal, 0);
60557 if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
60563 ** at least one non-zero bytes at the start of the journal file.
60569 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
60573 rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
60578 sqlite3OsClose(pPager->jfd);
60605 ** has been successfully called. If a shared-lock is already held when
60606 ** this function is called, it is a no-op.
60613 ** the SHARED lock, the file-system is checked for a hot-journal,
60614 ** which is played back if present. Following any hot-journal
60616 ** the 'change-counter' field of the database file header and
60619 ** 2) If the pager is running in exclusive-mode, and there are currently
60626 ** occurs while locking the database, checking for a hot-journal file or
60632 /* This routine is only called from b-tree and only when there are no
60636 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
60638 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
60639 assert( pPager->errCode==SQLITE_OK );
60641 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
60642 int bHotJournal = 1; /* True if there exists a hot journal-file */
60645 assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
60649 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
60656 if( pPager->eLock<=SHARED_LOCK ){
60663 if( pPager->readOnly ){
60673 ** hot-journal back.
60690 ** in exclusive-access mode the file descriptor will be kept open
60691 ** and possibly used for a transaction later on. Also, write-access
60698 ** may mean that the pager was in the error-state when this
60701 if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
60702 sqlite3_vfs * const pVfs = pPager->pVfs;
60705 pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
60709 assert( !pPager->tempFile );
60710 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
60711 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
60714 sqlite3OsClose(pPager->jfd);
60721 ** playing back the hot-journal so that we don't end up with
60727 if( isOpen(pPager->jfd) ){
60731 rc = pager_playback(pPager, !pPager->tempFile);
60732 pPager->eState = PAGER_OPEN;
60734 }else if( !pPager->exclusiveMode ){
60740 ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
60759 assert( pPager->eState==PAGER_OPEN );
60760 assert( (pPager->eLock==SHARED_LOCK)
60761 || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
60765 if( !pPager->tempFile && pPager->hasHeldSharedLock ){
60766 /* The shared-lock has just been acquired then check to
60770 ** single unnecessary sqlite3OsRead() call at the start-up.
60774 ** a 32-bit counter that is incremented with each change. The
60782 char dbFileVers[sizeof(pPager->dbFileVers)];
60785 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
60793 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
60803 sqlite3OsUnfetch(pPager->fd, 0, 0);
60808 /* If there is a WAL file in the file-system, open this database in WAL
60809 ** mode. Otherwise, the following function call is a no-op.
60813 assert( pPager->pWal==0 || rc==SQLITE_OK );
60822 if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
60823 rc = pagerPagecount(pPager, &pPager->dbSize);
60830 assert( pPager->eState==PAGER_OPEN );
60832 pPager->eState = PAGER_READER;
60833 pPager->hasHeldSharedLock = 1;
60844 ** nothing to rollback, so this routine is a no-op.
60847 if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
60848 assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
60861 ** getPageNormal() -- The normal getter
60862 ** getPageError() -- Used if the pager is in an error state
60863 ** getPageMmap() -- Used if memory-mapped I/O is enabled
60885 ** a) When reading a free-list leaf page from the database, and
60903 ** to find a page in the in-memory cache first. If the page is not already
60905 ** just returns 0. This routine acquires a read-lock the first time it
60921 assert( pPager->errCode==SQLITE_OK );
60922 assert( pPager->eState>=PAGER_READER );
60924 assert( pPager->hasHeldSharedLock==1 );
60927 pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
60930 rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
60937 pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
60939 assert( pPg->pgno==pgno );
60940 assert( pPg->pPager==pPager || pPg->pPager==0 );
60943 if( pPg->pPager && !noContent ){
60947 pPager->aStat[PAGER_STAT_HIT]++;
60962 pPg->pPager = pPager;
60964 assert( !isOpen(pPager->fd) || !MEMDB );
60965 if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
60966 if( pgno>pPager->mxPgno ){
60971 /* Failure to set the bits in the InJournal bit-vectors is benign.
60978 if( pgno<=pPager->dbOrigSize ){
60979 TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
60986 memset(pPg->pData, 0, pPager->pageSize);
60989 assert( pPg->pPager==pPager );
60990 pPager->aStat[PAGER_STAT_MISS]++;
61011 /* The page getter for when memory-mapped I/O is enabled */
61022 /* It is acceptable to use a read-only (mmap) page for any page except
61023 ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
61025 ** temporary or in-memory database. */
61027 && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
61032 assert( pPager->xCodec==0 );
61042 assert( pPager->eState>=PAGER_READER );
61044 assert( pPager->hasHeldSharedLock==1 );
61045 assert( pPager->errCode==SQLITE_OK );
61048 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
61056 rc = sqlite3OsFetch(pPager->fd,
61057 (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
61060 if( pPager->eState>PAGER_READER || pPager->tempFile ){
61066 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
61092 assert( pPager->errCode!=SQLITE_OK );
61094 return pPager->errCode;
61107 return pPager->xGet(pPager, pgno, ppPage, flags);
61111 ** Acquire a page if it is already in the in-memory cache. Do
61125 assert( pPager->pPCache!=0 );
61126 pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
61127 assert( pPage==0 || pPager->hasHeldSharedLock );
61129 return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
61145 TESTONLY( Pager *pPager = pPg->pPager; )
61147 if( pPg->flags & PGHDR_MMAP ){
61148 assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
61154 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
61162 assert( pPg->pgno==1 );
61163 assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
61164 pPager = pPg->pPager;
61175 ** to the start of it. If there are active savepoints, open the sub-journal
61193 sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
61195 assert( pPager->eState==PAGER_WRITER_LOCKED );
61197 assert( pPager->pInJournal==0 );
61199 /* If already in the error state, this function is a no-op. But on
61202 if( NEVER(pPager->errCode) ) return pPager->errCode;
61204 if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
61205 pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
61206 if( pPager->pInJournal==0 ){
61211 if( !isOpen(pPager->jfd) ){
61212 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
61213 sqlite3MemJournalOpen(pPager->jfd);
61218 if( pPager->tempFile ){
61232 pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
61236 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
61241 ** the sub-journal if necessary.
61245 pPager->nRec = 0;
61246 pPager->journalOff = 0;
61247 pPager->setSuper = 0;
61248 pPager->journalHdr = 0;
61254 sqlite3BitvecDestroy(pPager->pInJournal);
61255 pPager->pInJournal = 0;
61256 pPager->journalOff = 0;
61258 assert( pPager->eState==PAGER_WRITER_LOCKED );
61259 pPager->eState = PAGER_WRITER_CACHEMOD;
61266 ** Begin a write-transaction on the specified pager object. If a
61267 ** write-transaction has already been opened, this function is a no-op.
61274 ** If the subjInMemory argument is non-zero, then any sub-journal opened
61275 ** within this transaction will be opened as an in-memory file. This
61276 ** has no effect if the sub-journal is already opened (as it may be when
61278 ** sub-journal. If the subjInMemory argument is zero, then any required
61279 ** sub-journal is implemented in-memory if pPager is an in-memory database,
61285 if( pPager->errCode ) return pPager->errCode;
61286 assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
61287 pPager->subjInMemory = (u8)subjInMemory;
61289 if( pPager->eState==PAGER_READER ){
61290 assert( pPager->pInJournal==0 );
61296 if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
61301 (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
61306 ** The busy-handler is not invoked if another connection already
61307 ** holds the write-lock. If possible, the upper layer will call it.
61309 rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
61313 ** busy-handler callback can be used when upgrading to the EXCLUSIVE
61328 ** transactions may copy data from the sub-journal into the database
61332 pPager->eState = PAGER_WRITER_LOCKED;
61333 pPager->dbHintSize = pPager->dbSize;
61334 pPager->dbFileSize = pPager->dbSize;
61335 pPager->dbOrigSize = pPager->dbSize;
61336 pPager->journalOff = 0;
61339 assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
61340 assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
61352 Pager *pPager = pPg->pPager;
61356 i64 iOff = pPager->journalOff;
61361 assert( pPg->pgno!=PAGER_SJ_PGNO(pPager) );
61363 assert( pPager->journalHdr<=pPager->journalOff );
61364 CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
61368 ** page in the block above, set the need-sync flag for the page.
61374 pPg->flags |= PGHDR_NEED_SYNC;
61376 rc = write32bits(pPager->jfd, iOff, pPg->pgno);
61378 rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
61380 rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
61383 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
61384 pPager->journalOff, pPager->pageSize));
61387 PAGERID(pPager), pPg->pgno,
61388 ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
61390 pPager->journalOff += 8 + pPager->pageSize;
61391 pPager->nRec++;
61392 assert( pPager->pInJournal!=0 );
61393 rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
61396 rc |= addToSavepointBitvecs(pPager, pPg->pgno);
61403 ** main journal or sub-journal as required. If the page is written into
61409 Pager *pPager = pPg->pPager;
61412 /* This routine is not called unless a write-transaction has already
61416 assert( pPager->eState==PAGER_WRITER_LOCKED
61417 || pPager->eState==PAGER_WRITER_CACHEMOD
61418 || pPager->eState==PAGER_WRITER_DBMOD
61421 assert( pPager->errCode==0 );
61422 assert( pPager->readOnly==0 );
61426 ** obtained the necessary locks to begin the write-transaction, but the
61434 if( pPager->eState==PAGER_WRITER_LOCKED ){
61438 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
61448 assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
61449 if( pPager->pInJournal!=0
61450 && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
61453 if( pPg->pgno<=pPager->dbOrigSize ){
61459 if( pPager->eState!=PAGER_WRITER_DBMOD ){
61460 pPg->flags |= PGHDR_NEED_SYNC;
61463 PAGERID(pPager), pPg->pgno,
61464 ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
61468 /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
61473 pPg->flags |= PGHDR_WRITEABLE;
61478 if( pPager->nSavepoint>0 ){
61483 if( pPager->dbSize<pPg->pgno ){
61484 pPager->dbSize = pPg->pgno;
61507 Pager *pPager = pPg->pPager; /* The pager that owns pPg */
61508 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
61515 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
61516 pPager->doNotSpill |= SPILLFLAG_NOSYNC;
61518 /* This trick assumes that both the page-size and sector-size are
61522 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
61524 nPageCount = pPager->dbSize;
61525 if( pPg->pgno>nPageCount ){
61526 nPage = (pPg->pgno - pg1)+1;
61527 }else if( (pg1+nPagePerSector-1)>nPageCount ){
61528 nPage = nPageCount+1-pg1;
61533 assert(pg1<=pPg->pgno);
61534 assert((pg1+nPage)>pPg->pgno);
61539 if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
61544 if( pPage->flags&PGHDR_NEED_SYNC ){
61551 if( pPage->flags&PGHDR_NEED_SYNC ){
61569 pPage->flags |= PGHDR_NEED_SYNC;
61575 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
61576 pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
61588 ** fit on a single disk sector. In this case all co-resident pages
61595 Pager *pPager = pPg->pPager;
61596 assert( (pPg->flags & PGHDR_MMAP)==0 );
61597 assert( pPager->eState>=PAGER_WRITER_LOCKED );
61599 if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
61600 if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
61602 }else if( pPager->errCode ){
61603 return pPager->errCode;
61604 }else if( pPager->sectorSize > (u32)pPager->pageSize ){
61605 assert( pPager->tempFile==0 );
61619 return pPg->flags & PGHDR_WRITEABLE;
61637 ** This optimization cannot be used with a temp-file, as the page may
61644 Pager *pPager = pPg->pPager;
61645 if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
61646 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
61647 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
61648 pPg->flags |= PGHDR_DONT_WRITE;
61649 pPg->flags &= ~PGHDR_WRITEABLE;
61650 testcase( pPg->flags & PGHDR_NEED_SYNC );
61657 ** change-counter, stored as a 4-byte big-endian integer starting at
61661 ** But this only happens if the pPager->changeCountDone flag is false.
61671 ** The isDirectMode flag may only be non-zero if the library was compiled
61673 ** if isDirect is non-zero, then the database file is updated directly
61680 assert( pPager->eState==PAGER_WRITER_CACHEMOD
61681 || pPager->eState==PAGER_WRITER_DBMOD
61686 ** atomic-write optimization is enabled in this build, then isDirect
61690 ** The idea is that if the atomic-write optimization is not
61703 if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
61706 assert( !pPager->tempFile && isOpen(pPager->fd) );
61713 ** operating in direct-mode, make page 1 writable. When not in
61715 ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
61728 assert( pPager->dbFileSize>0 );
61729 CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
61731 rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
61732 pPager->aStat[PAGER_STAT_WRITE]++;
61735 /* Update the pager's copy of the change-counter. Otherwise, the
61737 ** flushed (as the change-counter values will not match). */
61739 memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
61740 pPager->changeCountDone = 1;
61743 pPager->changeCountDone = 1;
61754 ** Sync the database file to disk. This is a no-op for in-memory databases
61757 ** If successful, or if called on a pager for which it is a no-op, this
61763 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
61765 if( rc==SQLITE_OK && !pPager->noSync ){
61767 rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
61773 ** This function may only be called while a write-transaction is active in
61774 ** rollback. If the connection is in WAL mode, this call is a no-op.
61784 int rc = pPager->errCode;
61787 assert( pPager->eState==PAGER_WRITER_CACHEMOD
61788 || pPager->eState==PAGER_WRITER_DBMOD
61789 || pPager->eState==PAGER_WRITER_LOCKED
61801 ** of a super-journal file that should be written into the individual
61803 ** super-journal (a single database transaction).
61807 ** * The database file change-counter is updated,
61808 ** * the journal is synced (unless the atomic-write optimization is used),
61815 ** delete the super-journal file if specified).
61820 ** If the final parameter - noSync - is true, then the database file itself
61827 const char *zSuper, /* If not NULL, the super-journal name */
61832 assert( pPager->eState==PAGER_WRITER_LOCKED
61833 || pPager->eState==PAGER_WRITER_CACHEMOD
61834 || pPager->eState==PAGER_WRITER_DBMOD
61835 || pPager->eState==PAGER_ERROR
61840 if( NEVER(pPager->errCode) ) return pPager->errCode;
61846 pPager->zFilename, zSuper, pPager->dbSize));
61849 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
61851 assert( MEMDB==0 || pPager->tempFile );
61852 assert( isOpen(pPager->fd) || pPager->tempFile );
61854 /* If this is an in-memory db, or no pages have been written to, or this
61855 ** function has already been called, it is mostly a no-op. However, any
61857 sqlite3BackupRestart(pPager->pBackup);
61862 pList = sqlite3PcacheDirtyList(pPager->pPCache);
61865 ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
61868 pList->pDirty = 0;
61872 rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
61876 sqlite3PcacheCleanAll(pPager->pPCache);
61879 /* The bBatch boolean is true if the batch-atomic-write commit method
61880 ** should be used. No rollback journal is created if batch-atomic-write
61884 sqlite3_file *fd = pPager->fd;
61887 && !pPager->noSync
61888 && sqlite3JournalIsInMemory(pPager->jfd);
61894 /* The following block updates the change-counter. Exactly how it
61895 ** does this depends on whether or not the atomic-update optimization
61899 ** * The file-system supports the atomic-write property for
61900 ** blocks of size page-size, and
61901 ** * This commit is not part of a multi-file transaction, and
61906 ** counter in 'indirect-mode'. If the optimization is compiled in but
61909 ** pager_incr_changecounter() to update the change-counter in indirect
61913 ** then call pager_incr_changecounter() to update the change-counter
61919 assert( isOpen(pPager->jfd)
61920 || pPager->journalMode==PAGER_JOURNALMODE_OFF
61921 || pPager->journalMode==PAGER_JOURNALMODE_WAL
61923 if( !zSuper && isOpen(pPager->jfd)
61924 && pPager->journalOff==jrnlBufferSize(pPager)
61925 && pPager->dbSize>=pPager->dbOrigSize
61926 && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
61928 /* Update the db file change counter via the direct-write method. The
61929 ** following call will modify the in-memory representation of page 1
61931 ** directly to the database file. Because of the atomic-write
61932 ** property of the host file-system, this is safe.
61936 rc = sqlite3JournalCreate(pPager->jfd);
61945 rc = sqlite3JournalCreate(pPager->jfd);
61954 /* Write the super-journal name into the journal file. If a
61955 ** super-journal file name has already been written to the journal file,
61956 ** or if zSuper is NULL (no super-journal), then this call is a no-op.
61962 ** If the atomic-update optimization is being used, this sync will not
61965 ** Because the change-counter page was just modified, unless the
61966 ** atomic-update optimization is used it is almost certain that the
61970 ** xSync() call will be changed to a no-op by the OS anyhow.
61975 pList = sqlite3PcacheDirtyList(pPager->pPCache);
61990 rc = sqlite3JournalCreate(pPager->jfd);
61992 sqlite3OsClose(pPager->jfd);
61997 sqlite3OsClose(pPager->jfd);
62009 sqlite3PcacheCleanAll(pPager->pPCache);
62014 ** last page in the db image moved to the free-list. In this case the
62017 if( pPager->dbSize>pPager->dbFileSize ){
62018 Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_SJ_PGNO(pPager));
62019 assert( pPager->eState==PAGER_WRITER_DBMOD );
62034 pPager->eState = PAGER_WRITER_FINISHED;
62043 ** synced to disk. The journal file still exists in the file-system
62045 ** be used as a hot-journal and the current transaction rolled back.
62049 ** for hot-journal rollback. Once this is done the transaction is
62061 if( NEVER(pPager->errCode) ) return pPager->errCode;
62062 pPager->iDataVersion++;
62064 assert( pPager->eState==PAGER_WRITER_LOCKED
62065 || pPager->eState==PAGER_WRITER_FINISHED
62066 || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
62071 ** this transaction, the pager is running in exclusive-mode and is
62072 ** using persistent journals, then this function is a no-op.
62076 ** a hot-journal during hot-journal rollback, 0 changes will be made
62081 if( pPager->eState==PAGER_WRITER_LOCKED
62082 && pPager->exclusiveMode
62083 && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
62085 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
62086 pPager->eState = PAGER_READER;
62091 rc = pager_end_transaction(pPager, pPager->setSuper, 1);
62097 ** transaction are reverted and the current write-transaction is closed.
62107 ** in-memory cache pages to the state they were in when the transaction
62116 ** In WAL mode, all cache-entries containing data modified within the
62118 ** their pre-transaction state by re-reading data from the database or
62125 /* PagerRollback() is a no-op if called in READER or OPEN state. If
62130 if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
62131 if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
62135 rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
62136 rc2 = pager_end_transaction(pPager, pPager->setSuper, 0);
62138 }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
62139 int eState = pPager->eState;
62146 pPager->errCode = SQLITE_ABORT;
62147 pPager->eState = PAGER_ERROR;
62155 assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
62168 ** Return TRUE if the database file is opened read-only. Return FALSE
62172 return pPager->readOnly;
62180 return sqlite3PcacheRefCount(pPager->pPCache);
62189 int perPageSize = pPager->pageSize + pPager->nExtra
62191 return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
62193 + pPager->pageSize;
62209 a[0] = sqlite3PcacheRefCount(pPager->pPCache);
62210 a[1] = sqlite3PcachePagecount(pPager->pPCache);
62211 a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
62212 a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
62213 a[4] = pPager->eState;
62214 a[5] = pPager->errCode;
62215 a[6] = pPager->aStat[PAGER_STAT_HIT];
62216 a[7] = pPager->aStat[PAGER_STAT_MISS];
62217 a[8] = 0; /* Used to be pPager->nOvfl */
62218 a[9] = pPager->nRead;
62219 a[10] = pPager->aStat[PAGER_STAT_WRITE];
62232 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
62248 eStat -= SQLITE_DBSTATUS_CACHE_HIT;
62249 *pnVal += pPager->aStat[eStat];
62251 pPager->aStat[eStat] = 0;
62256 ** Return true if this is an in-memory or temp-file backed pager.
62259 return pPager->tempFile || pPager->memVfs;
62266 ** equal to nSavepoint, then this function is a no-op.
62269 ** occurs while opening the sub-journal file, then an IO error code is
62274 int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
62278 assert( pPager->eState>=PAGER_WRITER_LOCKED );
62280 assert( nSavepoint>nCurrent && pPager->useJournal );
62287 pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
62292 memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
62293 pPager->aSavepoint = aNew;
62297 aNew[ii].nOrig = pPager->dbSize;
62298 if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
62299 aNew[ii].iOffset = pPager->journalOff;
62303 aNew[ii].iSubRec = pPager->nSubRec;
62304 aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
62310 sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
62312 pPager->nSavepoint = ii+1;
62314 assert( pPager->nSavepoint==nSavepoint );
62319 assert( pPager->eState>=PAGER_WRITER_LOCKED );
62322 if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
62342 ** (the first created). A value of (Pager.nSavepoint-1) means operate
62344 ** (Pager.nSavepoint-1), then this function is a no-op.
62361 int rc = pPager->errCode;
62370 if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
62379 for(ii=nNew; ii<pPager->nSavepoint; ii++){
62380 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
62382 pPager->nSavepoint = nNew;
62384 /* Truncate the sub-journal so that it only includes the parts
62387 PagerSavepoint *pRel = &pPager->aSavepoint[nNew];
62388 if( pRel->bTruncateOnRelease && isOpen(pPager->sjfd) ){
62389 /* Only truncate if it is an in-memory sub-journal. */
62390 if( sqlite3JournalIsInMemory(pPager->sjfd) ){
62391 i64 sz = (pPager->pageSize+4)*(i64)pRel->iSubRec;
62392 rc = sqlite3OsTruncate(pPager->sjfd, sz);
62395 pPager->nSubRec = pRel->iSubRec;
62399 ** If this is a temp-file, it is possible that the journal file has
62403 else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
62404 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
62415 pPager->journalMode==PAGER_JOURNALMODE_OFF
62416 && pPager->eState>=PAGER_WRITER_CACHEMOD
62418 pPager->errCode = SQLITE_ABORT;
62419 pPager->eState = PAGER_ERROR;
62431 ** Except, if the pager is in-memory only, then return an empty string if
62435 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
62436 ** participate in shared-cache.
62443 return (nullIfMemDb && pPager->memDb) ? &zFake[4] : pPager->zFilename;
62450 return pPager->pVfs;
62459 return pPager->fd;
62468 return pPager->jfd;
62470 return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
62478 return pPager->zJournal;
62492 if( pPager->xCodecFree ){
62493 pPager->xCodecFree(pPager->pCodec);
62497 pPager->xCodec = pPager->memDb ? 0 : xCodec;
62498 pPager->xCodecSizeChng = xCodecSizeChng;
62499 pPager->xCodecFree = xCodecFree;
62500 pPager->pCodec = pCodec;
62505 return pPager->pCodec;
62517 CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
62533 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
62541 ** If the fourth argument, isCommit, is non-zero, then this page is being
62551 Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
62555 assert( pPg->nRef>0 );
62556 assert( pPager->eState==PAGER_WRITER_CACHEMOD
62557 || pPager->eState==PAGER_WRITER_DBMOD
62561 /* In order to be able to rollback, an in-memory database must journal
62564 assert( pPager->tempFile || !MEMDB );
62565 if( pPager->tempFile ){
62572 ** sub-journal now. This is required to handle the following scenario:
62580 ** If page X were not written to the sub-journal here, it would not
62584 ** subjournalPage() may need to allocate space to store pPg->pgno into
62588 if( (pPg->flags & PGHDR_DIRTY)!=0
62595 PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
62596 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
62598 /* If the journal needs to be sync()ed before page pPg->pgno can
62599 ** be written to, store pPg->pgno in local variable needSyncPgno.
62602 ** the journal needs to be sync()ed before database page pPg->pgno
62605 if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
62606 needSyncPgno = pPg->pgno;
62607 assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
62608 pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
62609 assert( pPg->flags&PGHDR_DIRTY );
62612 /* If the cache contains a page with page-number pgno, remove it
62617 pPg->flags &= ~PGHDR_NEED_SYNC;
62619 assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB );
62621 if( NEVER(pPgOld->nRef>1) ){
62625 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
62626 if( pPager->tempFile ){
62627 /* Do not discard pages from an in-memory database since we might
62629 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
62635 origPgno = pPg->pgno;
62639 /* For an in-memory database, make sure the original page continues
62643 if( pPager->tempFile && pPgOld ){
62649 /* If needSyncPgno is non-zero, then the journal file needs to be
62651 ** Currently, no such page exists in the page-cache and the
62653 ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
62656 ** If the attempt to load the page into the page-cache fails, (due
62666 if( needSyncPgno<=pPager->dbOrigSize ){
62667 assert( pPager->pTmpSpace!=0 );
62668 sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
62672 pPgHdr->flags |= PGHDR_NEED_SYNC;
62688 assert( pPg->pgno!=iNew );
62689 pPg->flags = flags;
62697 assert( pPg->nRef>0 || pPg->pPager->memDb );
62698 return pPg->pData;
62706 return pPg->pExtra;
62710 ** Get/set the locking-mode for this pager. Parameter eMode must be one
62713 ** the locking-mode is set to the value specified.
62717 ** locking-mode.
62725 assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
62726 if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
62727 pPager->exclusiveMode = (u8)eMode;
62729 return (int)pPager->exclusiveMode;
62733 ** Set the journal-mode for this pager. Parameter eMode must be one of:
62745 ** * An in-memory database can only have its journal_mode set to _OFF
62750 ** The returned indicate the current (possibly updated) journal-mode.
62753 u8 eOld = pPager->journalMode; /* Prior journalmode */
62767 assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
62769 /* Do allow the journalmode of an in-memory database to be set to
62782 assert( pPager->eState!=PAGER_ERROR );
62783 pPager->journalMode = (u8)eMode;
62796 assert( isOpen(pPager->fd) || pPager->exclusiveMode );
62797 if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
62806 sqlite3OsClose(pPager->jfd);
62807 if( pPager->eLock>=RESERVED_LOCK ){
62808 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
62811 int state = pPager->eState;
62816 if( pPager->eState==PAGER_READER ){
62821 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
62828 assert( state==pPager->eState );
62831 sqlite3OsClose(pPager->jfd);
62836 return (int)pPager->journalMode;
62843 return (int)pPager->journalMode;
62853 if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
62854 if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
62859 ** Get/set the size-limit used for persistent journal files.
62861 ** Setting the size limit to -1 means no limit is enforced.
62862 ** An attempt to set a limit smaller than -1 is a no-op.
62865 if( iLimit>=-1 ){
62866 pPager->journalSizeLimit = iLimit;
62867 sqlite3WalLimit(pPager->pWal, iLimit);
62869 return pPager->journalSizeLimit;
62873 ** Return a pointer to the pPager->pBackup variable. The backup module
62879 return &pPager->pBackup;
62884 ** Unless this is an in-memory or temporary database, clear the pager cache.
62887 assert( MEMDB==0 || pPager->tempFile );
62888 if( pPager->tempFile==0 ) pager_reset(pPager);
62909 if( pPager->pWal==0 && pPager->journalMode==PAGER_JOURNALMODE_WAL ){
62921 if( pPager->pWal ){
62922 rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
62923 (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
62924 pPager->pBusyHandlerArg,
62925 pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
62933 return sqlite3WalCallback(pPager->pWal);
62938 ** primitives necessary for write-ahead logging.
62941 const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
62942 if( pPager->noLock ) return 0;
62943 return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
62953 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
62966 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
62967 ** lock on the database file and use heap-memory to store the wal-index
62968 ** in. Otherwise, use the normal shared-memory.
62973 assert( pPager->pWal==0 && pPager->tempFile==0 );
62974 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
62976 /* If the pager is already in exclusive-mode, the WAL module will use
62977 ** heap-memory for the wal-index instead of the VFS shared-memory
62981 if( pPager->exclusiveMode ){
62989 rc = sqlite3WalOpen(pPager->pVfs,
62990 pPager->fd, pPager->zWal, pPager->exclusiveMode,
62991 pPager->journalSizeLimit, &pPager->pWal
63005 ** file (not a temp file or an in-memory database), and the WAL file
63011 ** If the pager is open on a temp-file (or in-memory database), or if
63017 int *pbOpen /* OUT: Set to true if call is a no-op */
63022 assert( pPager->eState==PAGER_OPEN || pbOpen );
63023 assert( pPager->eState==PAGER_READER || !pbOpen );
63025 assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
63027 if( !pPager->tempFile && !pPager->pWal ){
63031 sqlite3OsClose(pPager->jfd);
63035 pPager->journalMode = PAGER_JOURNALMODE_WAL;
63036 pPager->eState = PAGER_OPEN;
63057 assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
63059 /* If the log file is not already open, but does exist in the file-system,
63063 if( !pPager->pWal ){
63068 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
63077 ** the database file, the log and log-summary files will be deleted.
63079 if( rc==SQLITE_OK && pPager->pWal ){
63082 rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
63083 pPager->pageSize, (u8*)pPager->pTmpSpace);
63084 pPager->pWal = 0;
63086 if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
63094 ** If pager pPager is a wal-mode database not in exclusive locking mode,
63101 if( pagerUseWal(pPager) && pPager->exclusiveMode==0 ){
63102 rc = sqlite3WalWriteLock(pPager->pWal, bLock);
63113 sqlite3WalDb(pPager->pWal, db);
63125 if( pPager->pWal ){
63126 rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
63141 if( pPager->pWal ){
63142 sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
63155 if( pPager->pWal ){
63156 rc = sqlite3WalSnapshotRecover(pPager->pWal);
63177 if( pPager->pWal ){
63178 rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);
63190 assert( pPager->pWal );
63191 sqlite3WalSnapshotUnlock(pPager->pWal);
63199 ** A read-lock must be held on the pager when this function is called. If
63206 assert( pPager->eState>=PAGER_READER );
63207 return sqlite3WalFramesize(pPager->pWal);
63218 ** The author disclaims copyright to this source code. In place of
63227 ** This file contains the implementation of a write-ahead log (WAL) used in
63230 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
63249 ** big-endian 32-bit unsigned integer values:
63255 ** 16: Salt-1, random integer incremented with each checkpoint
63256 ** 20: Salt-2, a different random integer changing with each ckpt
63257 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
63258 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
63260 ** Immediately following the wal-header are zero or more frames. Each
63261 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
63262 ** of page data. The frame-header is six big-endian 32-bit unsigned
63268 ** 8: Salt-1 (copied from the header)
63269 ** 12: Salt-2 (copied from the header)
63270 ** 16: Checksum-1.
63271 ** 20: Checksum-2.
63276 ** (1) The salt-1 and salt-2 values in the frame-header match
63277 ** salt values in the wal-header
63279 ** (2) The checksum values in the final 8 bytes of the frame-header
63284 ** The checksum is computed using 32-bit big-endian integers if the
63286 ** is computed using little-endian if the magic number is 0x377f0682.
63288 ** big-endian format regardless of which byte order is used to compute
63290 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
63293 ** for i from 0 to n-1 step 2:
63300 ** of the sequence being summed.) The s1 value spans all 32-bit
63303 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
63304 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
63305 ** The VFS.xSync operations serve as write barriers - all writes launched
63309 ** After each checkpoint, the salt-1 value is incremented and the salt-2
63338 ** data structure called the wal-index is maintained to expedite the
63341 ** WAL-INDEX FORMAT
63343 ** Conceptually, the wal-index is shared memory, though VFS implementations
63344 ** might choose to implement the wal-index using a mmapped file. Because
63345 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
63349 ** In the default unix and windows implementation, the wal-index is a mmapped
63350 ** file whose name is the database name with a "-shm" suffix added. For that
63351 ** reason, the wal-index is sometimes called the "shm" file.
63353 ** The wal-index is transient. After a crash, the wal-index can (and should
63355 ** to either truncate or zero the header of the wal-index when the last
63356 ** connection to it closes. Because the wal-index is transient, it can
63357 ** use an architecture-specific format; it does not have to be cross-platform.
63359 ** as big endian, the wal-index can store multi-byte values in the native
63362 ** The purpose of the wal-index is to answer this question quickly: Given
63367 ** The wal-index consists of a header region, followed by an one or
63370 ** The wal-index header contains the total number of frames within the WAL
63376 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
63378 ** wal-index. The values are:
63383 ** Each index block contains two sections, a page-mapping that contains the
63384 ** database page number associated with each wal frame, and a hash-table
63386 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
63387 ** for the first index block) 32-bit page numbers. The first entry in the
63388 ** first index-block contains the database page number corresponding to the
63393 ** The last index block in a wal-index usually contains less than the full
63394 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
63396 ** allocated size of the page-mapping array - the page-mapping array merely
63400 ** can be found by scanning the page-mapping sections of each index block
63406 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
63411 ** 1-based index of an entry in the mapping section of the same
63412 ** index block. Let K be the 1-based index of the largest entry in
63427 ** wrap-around.) Because the hash table is never more than half full,
63432 ** current index block. Otherwise the iMax-th mapping entry of the
63450 ** and to the wal-index) might be using a different value K1, where K1>K0.
63456 ** in the first place - which is what reader one wants. Meanwhile, the
63479 ** The maximum (and only) versions of the wal and wal-index formats
63483 ** values in the wal-header are correct and (b) the version field is not
63486 ** Similarly, if a client successfully reads a wal-index header (i.e. the
63488 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
63503 ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
63513 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
63523 ** The following object holds a copy of the wal-index header content.
63525 ** The actual header in the wal-index consists of two copies of this
63532 ** Or it can be 1 to represent a 65536-byte page. The latter case was
63536 u32 iVersion; /* Wal-index version */
63540 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
63550 ** A copy of the following object occurs in the wal-index immediately
63573 ** holds read-lock K, then the value in aReadMark[K] is no greater than
63576 ** a special case; its value is never used and it exists as a place-holder
63605 ** We assume that 32-bit loads are atomic and so no locks are needed in
63618 ** This is a schematic view of the complete 136-byte header of the
63619 ** wal-index file (also known as the -shm file):
63621 ** +-----------------------------+
63623 ** +-----------------------------+ |
63625 ** +-----------------------------+ |
63627 ** +-------+-------+-------------+ |
63629 ** +-------+-------+-------------+ |
63631 ** +-----------------------------+ | WalIndexHdr object
63633 ** +-----------------------------+ |
63636 ** +-----------------------------+ |
63639 ** +-----------------------------+ |
63642 ** +-----------------------------+
63644 ** +-----------------------------+ |
63646 ** +-----------------------------+ |
63648 ** +-------+-------+-------------+ |
63650 ** +-------+-------+-------------+ | Second copy of the
63652 ** +-----------------------------+ |
63654 ** +-----------------------------+ |
63657 ** +-----------------------------+ |
63660 ** +-----------------------------+ |
63663 ** +-----------------------------+
63665 ** +-----------------------------+
63671 ** +-------+-------+------+------+
63673 ** +-------+-------+------+------+ ) 8 lock bytes
63675 ** +-------+-------+------+------+
63677 ** +-----------------------------+
63679 ** +-----------------------------+
63684 ** only support mandatory file-locks, we do not read or write data
63697 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
63698 ** big-endian format in the first 4 bytes of a WAL file.
63701 ** file are calculated by treating all data as an array of 32-bit
63702 ** big-endian words. Otherwise, they are calculated by interpreting
63703 ** all data as 32-bit little-endian words.
63708 ** Return the offset of frame iFrame in the write-ahead log file,
63710 ** is to the start of the write-ahead log frame-header.
63713 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
63717 ** An open write-ahead log file is represented by an instance of the
63728 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
63730 i16 readLock; /* Which read lock is being held. -1 for none */
63732 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
63739 u8 bShmUnreliable; /* SHM content is read-only and unreliable */
63740 WalIndexHdr hdr; /* Wal-index header for current transaction */
63744 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
63771 ** Each page of the wal-index mapping contains a hash-table made up of
63785 ** walIteratorInit() - Create a new iterator,
63786 ** walIteratorNext() - Step an iterator,
63787 ** walIteratorFree() - Free an iterator.
63800 } aSegment[1]; /* One for every 32KB page in the wal-index */
63804 ** Define the parameters of the hash tables in the wal-index file. There
63805 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
63806 ** wal-index.
63808 ** Changing any of these constants will alter the wal-index format and
63816 ** The block of page numbers associated with the first hash-table in a
63817 ** wal-index is smaller than usual. This is so that there is a complete
63818 ** hash-table on each aligned 32KB page of the wal-index.
63820 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
63822 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
63828 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
63829 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
63832 ** If the wal-index is currently smaller the iPage pages then the size
63833 ** of the wal-index might be increased, but only if it is safe to do
63834 ** so. It is safe to enlarge the wal-index if pWal->writeLock is true
63835 ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
63839 ** (1) rc==SQLITE_OK and *ppPage==Requested-Wal-Index-Page
63843 ** Scenario (3) can only occur when pWal->writeLock is false and iPage==0
63852 /* Enlarge the pWal->apWiData[] array if required */
63853 if( pWal->nWiData<=iPage ){
63856 apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);
63861 memset((void*)&apNew[pWal->nWiData], 0,
63862 sizeof(u32*)*(iPage+1-pWal->nWiData));
63863 pWal->apWiData = apNew;
63864 pWal->nWiData = iPage+1;
63868 assert( pWal->apWiData[iPage]==0 );
63869 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
63870 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
63871 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
63873 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
63874 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
63876 assert( pWal->apWiData[iPage]!=0
63878 || (pWal->writeLock==0 && iPage==0) );
63879 testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
63883 pWal->readOnly |= WAL_SHM_RDONLY;
63890 *ppPage = pWal->apWiData[iPage];
63899 if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
63906 ** Return a pointer to the WalCkptInfo structure in the wal-index.
63909 assert( pWal->nWiData>0 && pWal->apWiData[0] );
63910 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
63914 ** Return a pointer to the WalIndexHdr structure in the wal-index.
63917 assert( pWal->nWiData>0 && pWal->apWiData[0] );
63918 return (volatile WalIndexHdr*)pWal->apWiData[0];
63922 ** The argument to this macro must be of type u32. On a little-endian
63924 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
63926 ** of the input value as a little-endian integer.
63943 int nativeCksum, /* True for native byte-order, false for non-native */
63986 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
63987 sqlite3OsShmBarrier(pWal->pDbFd);
63992 ** Add the SQLITE_NO_TSAN as part of the return-type of a function
63994 ** might give false-positive TSAN warnings.
63996 ** See tag-20200519-1.
64005 ** Write the header information in pWal->hdr into the wal-index.
64007 ** The checksum on pWal->hdr is updated before it is written.
64013 assert( pWal->writeLock );
64014 pWal->hdr.isInit = 1;
64015 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
64016 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
64017 /* Possible TSAN false-positive. See tag-20200519-1 */
64018 memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
64020 memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
64025 ** supplied by the caller. A frame-header is made up of a series of
64026 ** 4-byte big-endian integers, as follows:
64031 ** 8: Salt-1 (copied from the wal-header)
64032 ** 12: Salt-2 (copied from the wal-header)
64033 ** 16: Checksum-1.
64034 ** 20: Checksum-2.
64037 Wal *pWal, /* The write-ahead log */
64039 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
64043 int nativeCksum; /* True for native byte-order checksums */
64044 u32 *aCksum = pWal->hdr.aFrameCksum;
64048 if( pWal->iReCksum==0 ){
64049 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
64051 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
64053 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
64068 Wal *pWal, /* The write-ahead log */
64074 int nativeCksum; /* True for native byte-order checksums */
64075 u32 *aCksum = pWal->hdr.aFrameCksum;
64079 /* A frame is only valid if the salt values in the frame-header
64080 ** match the salt values in the wal-header.
64082 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
64094 ** all prior frams, the first 16 bytes of this frame-header,
64095 ** and the frame-data matches the checksum in the last 8
64096 ** bytes of this frame-header.
64098 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
64100 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
64124 return "WRITE-LOCK";
64126 return "CKPT-LOCK";
64128 return "RECOVER-LOCK";
64131 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
64132 lockIdx-WAL_READ_LOCK(0));
64141 ** A lock cannot be moved directly between shared and exclusive - it must go
64144 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
64148 if( pWal->exclusiveMode ) return SQLITE_OK;
64149 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
64151 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
64153 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
64157 if( pWal->exclusiveMode ) return;
64158 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
64160 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
64164 if( pWal->exclusiveMode ) return SQLITE_OK;
64165 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
64167 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
64169 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
64173 if( pWal->exclusiveMode ) return;
64174 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
64176 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
64182 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
64187 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
64188 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
64191 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
64196 ** of a page hash table in the wal-index. This becomes the return value
64201 volatile ht_slot *aHash; /* Start of the wal-index hash table */
64208 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
64211 ** Set output variable pLoc->aHash to point to the start of the hash table
64212 ** in the wal-index file. Set pLoc->iZero to one less than the frame
64215 ** (pLoc->iZero+N) in the log.
64217 ** Finally, set pLoc->aPgno so that pLoc->aPgno[0] is the page number of the
64218 ** first frame indexed by the hash table, frame (pLoc->iZero).
64227 rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
64230 if( pLoc->aPgno ){
64231 pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
64233 pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
64234 pLoc->iZero = 0;
64236 pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
64245 ** Return the number of the wal-index page that contains the hash-table
64246 ** and page-number array that contain entries corresponding to WAL frame
64247 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
64251 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
64268 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
64270 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
64275 ** than pWal->hdr.mxFrame.
64277 ** This function is called whenever pWal->hdr.mxFrame is decreased due
64280 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
64282 ** pWal->hdr.mxFrame advances to the point where those hash tables are
64291 assert( pWal->writeLock );
64292 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
64293 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
64294 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
64296 if( pWal->hdr.mxFrame==0 ) return;
64298 /* Obtain pointers to the hash-table and page-number array containing
64299 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
64300 ** that the page said hash-table and array reside on is already mapped.(1)
64302 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
64303 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
64304 i = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
64305 if( NEVER(i) ) return; /* Defense-in-depth, in case (1) above is wrong */
64307 /* Zero all hash-table entries that correspond to frame numbers greater
64308 ** than pWal->hdr.mxFrame.
64310 iLimit = pWal->hdr.mxFrame - sLoc.iZero;
64319 ** frame numbers greater than pWal->hdr.mxFrame.
64321 nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit]);
64344 ** Set an entry in the wal-index that will map database page number
64349 WalHashLoc sLoc; /* Wal-index hash table location */
64353 /* Assuming the wal-index file was successfully mapped, populate the
64358 int idx; /* Value to write to hash-table slot */
64361 idx = iFrame - sLoc.iZero;
64364 /* If this is the first entry to be added to this hash-table, zero the
64368 int nByte = (int)((u8*)&sLoc.aHash[HASHTABLE_NSLOT] - (u8*)sLoc.aPgno);
64377 ** the hash-table before writing any new entries.
64379 if( sLoc.aPgno[idx-1] ){
64381 assert( !sLoc.aPgno[idx-1] );
64384 /* Write the aPgno[] array entry and the hash-table slot. */
64387 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
64389 sLoc.aPgno[idx-1] = iPage;
64405 ** thing to check, so only do this occasionally - not on every
64427 ** Recover the wal-index by reading the write-ahead log file.
64430 ** wal-index to prevent other threads/processes from doing anything
64431 ** with the WAL or wal-index while recovery is running. The
64448 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
64451 assert( pWal->writeLock );
64452 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
64453 rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
64460 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
64462 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
64469 u32 *aPrivate = 0; /* Heap copy of *-shm hash being populated */
64477 u32 iPg; /* Current 32KB wal-index page */
64481 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
64494 || szPage&(szPage-1)
64500 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
64501 pWal->szPage = szPage;
64502 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
64503 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
64506 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
64507 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
64509 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
64510 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
64534 iLastFrame = (nSize - WAL_HDRSIZE) / szFrame;
64539 u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE);
64544 pWal->apWiData[iPg] = aPrivate;
64552 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
64559 /* If nTruncate is non-zero, this is a commit record. */
64561 pWal->hdr.mxFrame = iFrame;
64562 pWal->hdr.nPage = nTruncate;
64563 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
64566 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
64567 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
64570 pWal->apWiData[iPg] = aShare;
64582 memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ-nHdr);
64611 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
64612 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
64615 /* Reset the checkpoint-header. This is safe because this thread is
64617 ** checkpointers. Then set the values of read-mark slots 1 through N.
64620 pInfo->nBackfill = 0;
64621 pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
64622 pInfo->aReadMark[0] = 0;
64626 if( i==1 && pWal->hdr.mxFrame ){
64627 pInfo->aReadMark[i] = pWal->hdr.mxFrame;
64629 pInfo->aReadMark[i] = READMARK_NOT_USED;
64642 if( pWal->hdr.nPage ){
64645 pWal->hdr.mxFrame, pWal->zWalName
64652 walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
64657 ** Close an open wal-index.
64660 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
64662 for(i=0; i<pWal->nWiData; i++){
64663 sqlite3_free((void *)pWal->apWiData[i]);
64664 pWal->apWiData[i] = 0;
64667 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
64668 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
64679 ** client from unlinking the WAL or wal-index file. If another process
64688 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
64691 int bNoShm, /* True to run in heap-memory mode */
64703 ** of these constants would result in an incompatible on-disk format
64704 ** for the -shm file. Any change that causes one of these asserts to
64708 ** This table also serves as a helpful cross-reference when trying to
64709 ** interpret hex dumps of the -shm file.
64733 /* In the amalgamation, the os_unix.c and os_win.c source files come before
64734 ** this source file. Verify that the #defines of the locking byte offsets
64749 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
64754 pRet->pVfs = pVfs;
64755 pRet->pWalFd = (sqlite3_file *)&pRet[1];
64756 pRet->pDbFd = pDbFd;
64757 pRet->readLock = -1;
64758 pRet->mxWalSize = mxWalSize;
64759 pRet->zWalName = zWalName;
64760 pRet->syncHeader = 1;
64761 pRet->padToSectorBoundary = 1;
64762 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
64764 /* Open file handle on the write-ahead log file. */
64766 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
64768 pRet->readOnly = WAL_RDONLY;
64773 sqlite3OsClose(pRet->pWalFd);
64777 if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
64779 pRet->padToSectorBoundary = 0;
64791 if( pWal ) pWal->mxWalSize = iLimit;
64813 iMin = p->iPrior;
64815 for(i=p->nSegment-1; i>=0; i--){
64816 struct WalSegment *pSegment = &p->aSegment[i];
64817 while( pSegment->iNext<pSegment->nEntry ){
64818 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
64822 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
64826 pSegment->iNext++;
64830 *piPage = p->iPrior = iRet;
64858 const u32 *aContent, /* Pages in wal - keys for the sort */
64922 ht_slot *aList; /* Pointer to sub-list content */
64930 struct Sublist aSub[13]; /* Array of sub-lists */
64934 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
64943 assert( p->aList && p->nList<=(1<<iSub) );
64944 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
64945 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
64956 assert( p->nList<=(1<<iSub) );
64957 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
64958 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
64968 assert( aContent[aList[i]] > aContent[aList[i-1]] );
64984 ** nBackfill or earlier may be included - excluding them is an optimization
65000 ht_slot *aTmp; /* Temp space used by merge-sort */
65006 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
65007 iLast = pWal->hdr.mxFrame;
65012 + (nSegment-1)*sizeof(struct WalSegment)
65019 p->nSegment = nSegment;
65021 /* Allocate temporary space used by the merge-sort routine. This block
65041 nEntry = (int)(iLast - sLoc.iZero);
65043 nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
65045 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
65052 p->aSegment[i].iZero = sLoc.iZero;
65053 p->aSegment[i].nEntry = nEntry;
65054 p->aSegment[i].aIndex = aIndex;
65055 p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
65072 ** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
65077 if( pWal->db ){
65078 int tmout = pWal->db->busyTimeout;
65082 pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout
65095 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);
65109 assert( pWal->readLock<0 || bLock==0 );
65111 assert( pWal->db );
65115 pWal->writeLock = 1;
65119 }else if( pWal->writeLock ){
65121 pWal->writeLock = 0;
65130 pWal->db = db;
65154 ** busy-handler function. Invoke it and retry the lock until either the
65155 ** lock is successfully obtained or the busy-handler returns 0.
65178 ** The cache of the wal-index header must be valid to call this function.
65179 ** Return the page-size in bytes used by the database.
65182 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
65191 ** file - there are no readers that may attempt to read a frame from
65194 ** This function updates the shared-memory structures so that the next
65199 ** new wal-index header. It should be passed a pseudo-random value (i.e.
65205 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
65206 pWal->nCkpt++;
65207 pWal->hdr.mxFrame = 0;
65209 memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
65211 AtomicStore(&pInfo->nBackfill, 0);
65212 pInfo->nBackfillAttempted = 0;
65213 pInfo->aReadMark[1] = 0;
65214 for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
65215 assert( pInfo->aReadMark[0]==0 );
65227 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
65233 ** in the WAL and can be recovered following a power-loss or hard reset.
65240 ** This routine uses and updates the nBackfill field of the wal-index header.
65259 int szPage; /* Database page-size */
65272 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
65274 /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
65283 mxSafeFrame = pWal->hdr.mxFrame;
65284 mxPage = pWal->hdr.nPage;
65286 u32 y = AtomicLoad(pInfo->aReadMark+i);
65288 assert( y<=pWal->hdr.mxFrame );
65292 AtomicStore(pInfo->aReadMark+i, iMark);
65304 if( pInfo->nBackfill<mxSafeFrame ){
65305 rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
65312 u32 nBackfill = pInfo->nBackfill;
65314 pInfo->nBackfillAttempted = mxSafeFrame;
65317 rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
65325 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);
65326 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
65328 if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){
65331 ** maximum size of the pending-byte page (65536 bytes), then
65335 sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq);
65345 if( AtomicLoad(&db->u1.isInterrupted) ){
65346 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
65354 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
65356 iOffset = (iDbpage-1)*(i64)szPage;
65358 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
65361 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);
65365 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
65366 i64 szDb = pWal->hdr.nPage*(i64)szPage;
65368 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
65370 rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
65374 AtomicStore(&pInfo->nBackfill, mxSafeFrame);
65395 assert( pWal->writeLock );
65396 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
65401 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
65402 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
65405 /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
65411 ** wal-index header in shared memory, as all subsequent reader or
65415 ** the wal-index header do not match the contents of the
65416 ** file-system. To avoid this, update the wal-index header to
65419 rc = sqlite3OsTruncate(pWal->pWalFd, 0);
65421 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
65439 rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
65441 rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
65445 sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
65461 int isDelete = 0; /* True to unlink wal and wal-index files */
65464 ** ordinary, rollback-mode locking methods, this guarantees that the
65467 ** the wal and wal-index files.
65472 && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
65474 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
65475 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
65481 int bPersist = -1;
65483 pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
65487 ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
65490 }else if( pWal->mxWalSize>=0 ){
65494 ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
65503 sqlite3OsClose(pWal->pWalFd);
65506 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
65510 sqlite3_free((void *)pWal->apWiData);
65517 ** Try to read the wal-index header. Return 0 on success and 1 if
65520 ** The wal-index is in shared memory. Another thread or process might
65527 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
65530 ** If the checksum cannot be verified return non-zero. If the header
65538 /* The first page of the wal-index must be mapped at this point. */
65539 assert( pWal->nWiData>0 && pWal->apWiData[0] );
65544 ** from the file. If this happens, return non-zero.
65546 ** tag-20200519-1:
65547 ** There are two copies of the header at the beginning of the wal-index.
65551 ** give false-positive warnings about these accesses because the tools do not
65552 ** account for the double-read and the memory barrier. The use of mutexes
65558 memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */
65566 return 1; /* Malformed header - probably all zeros */
65568 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
65573 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
65575 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
65576 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
65577 testcase( pWal->szPage<=32768 );
65578 testcase( pWal->szPage>=65536 );
65589 #define WAL_RETRY (-1)
65592 ** Read the wal-index header from the wal-index and into pWal->hdr.
65593 ** If the wal-header appears to be corrupt, try to reconstruct the
65594 ** wal-index from the WAL before returning.
65596 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
65597 ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
65600 ** If the wal-index header is successfully read, return SQLITE_OK.
65606 volatile u32 *page0; /* Chunk of wal-index containing header */
65608 /* Ensure that page 0 of the wal-index (the page that contains the
65609 ** wal-index header) is mapped. Return early if an error occurs here.
65616 /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
65618 ** confirm that another write-capable connection has the shared-memory
65619 ** open, and hence the content of the shared-memory is unreliable,
65620 ** since the shared-memory might be inconsistent with the WAL file
65623 assert( pWal->writeLock==0 );
65624 assert( pWal->readOnly & WAL_SHM_RDONLY );
65625 pWal->bShmUnreliable = 1;
65626 pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
65629 return rc; /* Any other non-OK return is just an error */
65632 /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
65636 assert( page0!=0 || pWal->writeLock==0 );
65638 /* If the first page of the wal-index has been mapped, try to read the
65639 ** wal-index header immediately, without holding any lock. This usually
65640 ** works, but may fail if the wal-index header is corrupt or currently
65649 if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
65655 int bWriteLock = pWal->writeLock;
65657 pWal->writeLock = 1;
65661 /* If the wal-index header is still malformed even while holding
65670 pWal->writeLock = 0;
65678 ** sure the wal-index was not constructed with some future format that
65681 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
65684 if( pWal->bShmUnreliable ){
65687 pWal->bShmUnreliable = 0;
65688 assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
65694 pWal->exclusiveMode = WAL_NORMAL_MODE;
65701 ** Open a transaction in a connection where the shared-memory is read-only
65702 ** and where we cannot verify that there is a separate write-capable connection
65703 ** on hand to keep the shared-memory up-to-date with the WAL file.
65705 ** This can happen, for example, when the shared-memory is implemented by
65706 ** memory-mapping a *-shm file, where a prior writer has shut down and
65707 ** left the *-shm file on disk, and now the present connection is trying
65708 ** to use that database but lacks write permission on the *-shm file.
65713 ** The *-wal file has been read and an appropriate wal-index has been
65714 ** constructed in pWal->apWiData[] using heap memory instead of shared
65721 ** WAL_RETRY, then the heap memory wal-index has been discarded and
65723 ** beginning (including attempting to map the *-shm file).
65736 u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
65738 assert( pWal->bShmUnreliable );
65739 assert( pWal->readOnly & WAL_SHM_RDONLY );
65740 assert( pWal->nWiData>0 && pWal->apWiData[0] );
65750 pWal->readLock = 0;
65752 /* Check to see if a separate writer has attached to the shared-memory area,
65753 ** thus making the shared-memory "reliable" again. Do this by invoking
65757 ** If the shared-memory is now "reliable" return WAL_RETRY, which will
65758 ** cause the heap-memory WAL-index to be discarded and the actual
65770 ** even if some external agent does a "chmod" to make the shared-memory
65774 rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
65775 assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
65781 /* We reach this point only if the real shared-memory is still unreliable.
65782 ** Assume the in-memory WAL-index substitute is correct and load it
65783 ** into pWal->hdr.
65785 memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
65790 rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
65795 /* If the wal file is too small to contain a wal-header and the
65796 ** wal-index header has mxFrame==0, then it must be safe to proceed
65802 rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
65807 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
65811 if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
65813 ** Return WAL_RETRY which will cause the in-memory WAL-index to be
65820 assert( (pWal->szPage & (pWal->szPage-1))==0 );
65821 assert( pWal->szPage>=512 && pWal->szPage<=65536 );
65822 szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
65831 ** wal file since the heap-memory wal-index was created. If so, the
65832 ** heap-memory wal-index is discarded and WAL_RETRY returned to
65834 aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
65835 aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
65836 for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->szPage);
65844 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
65848 /* If nTruncate is non-zero, then a complete transaction has been
65856 pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
65857 pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
65863 for(i=0; i<pWal->nWiData; i++){
65864 sqlite3_free((void*)pWal->apWiData[i]);
65865 pWal->apWiData[i] = 0;
65867 pWal->bShmUnreliable = 0;
65886 ** to make a copy of the wal-index header into pWal->hdr. If the
65887 ** wal-index header has changed, *pChanged is set to 1 (as an indication
65889 ** flushed.) When useWal==1, the wal-index header is assumed to already
65900 ** bad luck when there is lots of contention for the wal-index, but that
65904 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
65905 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
65908 ** including frame number aReadMark[pWal->readLock]. The reader will
65909 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
65910 ** Or if pWal->readLock==0, then the reader will ignore the WAL
65913 ** this routine will always set pWal->readLock>0 on success.
65915 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
65925 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
65932 assert( pWal->readLock<0 ); /* Not currently locked */
65935 assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
65943 ** paged out or take a page-fault that is time-consuming to resolve,
65957 VVA_ONLY( pWal->lockError = 1; )
65960 if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
65961 sqlite3OsSleep(pWal->pVfs, nDelay);
65966 if( pWal->bShmUnreliable==0 ){
65978 if( pWal->apWiData[0]==0 ){
65983 ** code that determines whether or not the shared-memory region
65997 else if( pWal->bShmUnreliable ){
66002 assert( pWal->nWiData>0 );
66003 assert( pWal->apWiData[0]!=0 );
66005 if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
66007 && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0)
66016 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
66033 pWal->readLock = 0;
66043 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
66047 mxFrame = pWal->hdr.mxFrame;
66049 if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
66050 mxFrame = pWal->pSnapshot->mxFrame;
66054 u32 thisMark = AtomicLoad(pInfo->aReadMark+i);
66061 if( (pWal->readOnly & WAL_SHM_RDONLY)==0
66067 AtomicStore(pInfo->aReadMark+i,mxFrame);
66078 assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
66086 /* Now that the read-lock has been obtained, check that neither the
66087 ** value in the aReadMark[] array or the contents of the wal-index
66090 ** It is necessary to check that the wal-index header did not change
66091 ** between the time it was read and when the shared-lock was obtained
66094 ** that occur later in the log than pWal->hdr.mxFrame may have been
66097 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
66100 ** Before checking that the live wal-index header has not changed
66103 ** to read any frames earlier than minFrame from the wal file - they
66107 ** nBackfill and checking that the wal-header in shared-memory still
66108 ** matches the one cached in pWal->hdr, it is guaranteed that the
66109 ** checkpointer that set nBackfill was not working with a wal-index
66110 ** header newer than that cached in pWal->hdr. If it were, that could
66112 ** a version of page X that lies before pWal->minFrame (call that version
66115 ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
66118 ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
66120 pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1;
66122 if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
66123 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
66128 assert( mxReadMark<=pWal->hdr.mxFrame );
66129 pWal->readLock = (i16)mxI;
66143 ** This is only really safe if the file-system is such that any page
66157 assert( pWal->readLock>=0 );
66161 int szPage = (int)pWal->szPage;
66164 rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
66171 u32 i = pInfo->nBackfillAttempted;
66172 for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){
66180 assert( i - sLoc.iZero - 1 >=0 );
66181 pgno = sLoc.aPgno[i-sLoc.iZero-1];
66182 iDbOff = (i64)(pgno-1) * szPage;
66186 rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
66189 rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
66197 pInfo->nBackfillAttempted = i-1;
66215 ** it takes a snapshot of the state of the WAL and wal-index for the current
66217 ** Other threads might append new content to the WAL and wal-index but
66230 WalIndexHdr *pSnapshot = pWal->pSnapshot;
66233 assert( pWal->ckptLock==0 );
66237 if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
66245 ** has not yet set the pInfo->nBackfillAttempted variable to indicate
66248 ** before checking pInfo->nBackfillAttempted. */
66256 pWal->ckptLock = 1;
66270 if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
66272 ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
66273 ** is populated with the wal-index header corresponding to the head
66281 ** pSnapshot->mxFrame into the database file. Note that the
66286 assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
66287 assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
66291 ** frames beyond pSnapshot->mxFrame. If either of these conditions are
66292 ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
66295 if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
66296 && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
66298 assert( pWal->readLock>0 );
66299 memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
66305 /* A client using a non-current snapshot may not ignore any frames
66311 pWal->minFrame = 1;
66320 if( pWal->ckptLock ){
66323 pWal->ckptLock = 0;
66331 ** read-lock.
66335 if( pWal->readLock>=0 ){
66336 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
66337 pWal->readLock = -1;
66355 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
66360 assert( pWal->readLock>=0 || pWal->lockError );
66362 /* If the "last page" field of the wal-index header snapshot is 0, then
66364 ** in this case as an optimization. Likewise, if pWal->readLock==0,
66368 if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
66378 ** that adds entries to the wal-index (and possibly to this hash
66382 ** read transaction was opened may have been written incorrectly -
66389 ** if we had exclusive access to the hash-table:
66392 ** This condition filters out normal hash-table collisions.
66396 ** table after the current read-transaction had started.
66398 iMinHash = walFramePage(pWal->minFrame);
66399 for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
66414 if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){
66418 if( (nCollide--)==0 ){
66428 ** of the wal-index file content. Make sure the results agree with the
66433 assert( pWal->bShmUnreliable || pWal->minFrame>0 );
66434 for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
66461 sz = pWal->hdr.szPage;
66467 return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
66474 if( pWal && ALWAYS(pWal->readLock>=0) ){
66475 return pWal->hdr.nPage;
66498 /* If the write-lock is already held, then it was obtained before the
66499 ** read-transaction was even opened, making this call a no-op.
66501 if( pWal->writeLock ){
66502 assert( !memcmp(&pWal->hdr,(void *)walIndexHdr(pWal),sizeof(WalIndexHdr)) );
66509 assert( pWal->readLock>=0 );
66510 assert( pWal->writeLock==0 && pWal->iReCksum==0 );
66512 if( pWal->readOnly ){
66523 pWal->writeLock = 1;
66529 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
66531 pWal->writeLock = 0;
66543 if( pWal->writeLock ){
66545 pWal->writeLock = 0;
66546 pWal->iReCksum = 0;
66547 pWal->truncateOnCommit = 0;
66554 ** function moves the write-pointer back to the start of the transaction.
66566 if( ALWAYS(pWal->writeLock) ){
66567 Pgno iMax = pWal->hdr.mxFrame;
66570 /* Restore the clients cache of the wal-index header to the state it
66573 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
66575 for(iFrame=pWal->hdr.mxFrame+1;
66581 ** (b) has an outstanding reference, then xUndo is either a no-op
66593 if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
66605 assert( pWal->writeLock );
66606 aWalData[0] = pWal->hdr.mxFrame;
66607 aWalData[1] = pWal->hdr.aFrameCksum[0];
66608 aWalData[2] = pWal->hdr.aFrameCksum[1];
66609 aWalData[3] = pWal->nCkpt;
66621 assert( pWal->writeLock );
66622 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
66624 if( aWalData[3]!=pWal->nCkpt ){
66625 /* This savepoint was opened immediately after the write-transaction
66630 aWalData[3] = pWal->nCkpt;
66633 if( aWalData[0]<pWal->hdr.mxFrame ){
66634 pWal->hdr.mxFrame = aWalData[0];
66635 pWal->hdr.aFrameCksum[0] = aWalData[1];
66636 pWal->hdr.aFrameCksum[1] = aWalData[2];
66648 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
66652 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
66659 if( pWal->readLock==0 ){
66661 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
66662 if( pInfo->nBackfill>0 ){
66665 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
66670 ** wal-index header to reflect this.
66673 ** at this point. But updating the actual wal-index header is also
66677 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
66683 pWal->readLock = -1;
66699 ** the next fsync should occur - passed from sqlite3WalFrames() into
66712 ** Do a sync when crossing the p->iSyncPoint boundary.
66725 if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
66726 int iFirstAmt = (int)(p->iSyncPoint - iOffset);
66727 rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
66730 iAmt -= iFirstAmt;
66732 assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
66733 rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
66736 rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
66751 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
66755 pData = pPage->pData;
66757 walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
66761 rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
66774 const int szPage = pWal->szPage;/* Database page size */
66777 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
66787 ** wal-file header. Otherwise, read them from the frame header of the
66789 assert( pWal->iReCksum>0 );
66790 if( pWal->iReCksum==1 ){
66793 iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
66795 rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
66796 pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
66797 pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
66799 iRead = pWal->iReCksum;
66800 pWal->iReCksum = 0;
66803 rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
66810 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
66819 ** Write a set of frames to the log. The caller must hold the write-lock
66824 int szPage, /* Database page-size in bytes */
66842 assert( pWal->writeLock );
66849 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
66851 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
66856 if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
66857 iFirst = pLive->mxFrame+1;
66861 ** log file, instead of appending to it at pWal->hdr.mxFrame.
66869 ** this source file for a description of the WAL header format.
66871 iFrame = pWal->hdr.mxFrame;
66873 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
66874 u32 aCksum[2]; /* Checksum for wal-header */
66879 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
66880 if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
66881 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
66882 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
66886 pWal->szPage = szPage;
66887 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
66888 pWal->hdr.aFrameCksum[0] = aCksum[0];
66889 pWal->hdr.aFrameCksum[1] = aCksum[1];
66890 pWal->truncateOnCommit = 1;
66892 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
66893 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
66900 ** an out-of-order write following a WAL restart could result in
66905 if( pWal->syncHeader ){
66906 rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
66910 assert( (int)pWal->szPage==szPage );
66914 w.pFd = pWal->pWalFd;
66922 for(p=pList; p; p=p->pDirty){
66927 ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
66929 if( iFirst && (p->pDirty || isCommit==0) ){
66931 VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
66936 if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
66937 pWal->iReCksum = iWrite;
66942 pData = p->pData;
66944 rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
66946 p->flags &= ~PGHDR_WAL_APPEND;
66953 nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
66958 p->flags |= PGHDR_WAL_APPEND;
66962 if( isCommit && pWal->iReCksum ){
66983 if( pWal->padToSectorBoundary ){
66984 int sectorSize = sqlite3SectorSize(pWal->pWalFd);
66985 w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
67006 if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
67007 i64 sz = pWal->mxWalSize;
67008 if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
67012 pWal->truncateOnCommit = 0;
67015 /* Append data to the wal-index. It is not necessary to lock the
67016 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
67020 iFrame = pWal->hdr.mxFrame;
67021 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
67022 if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
67024 rc = walIndexAppend(pWal, iFrame, p->pgno);
67029 nExtra--;
67030 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
67035 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
67038 pWal->hdr.mxFrame = iFrame;
67040 pWal->hdr.iChange++;
67041 pWal->hdr.nPage = nTruncate;
67043 /* If this is a commit, update the wal-index header too. */
67046 pWal->iCallback = iFrame;
67061 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
67077 int isChanged = 0; /* True if a new wal-index header is loaded */
67081 assert( pWal->ckptLock==0 );
67082 assert( pWal->writeLock==0 );
67084 /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
67088 if( pWal->readOnly ) return SQLITE_READONLY;
67092 ** enabled, set xBusy2=0 so that the busy-handler is never invoked. */
67096 /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
67098 ** EVIDENCE-OF: R-10421-19736 If any other process is running a
67101 ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
67108 pWal->ckptLock = 1;
67110 /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
67114 ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
67115 ** immediately, and a busy-handler is configured, it is invoked and the
67116 ** writer lock retried until either the busy-handler returns 0 or the
67122 pWal->writeLock = 1;
67132 /* Read the wal-index header. */
67137 if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
67138 sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
67145 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
67153 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
67154 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
67159 /* If a new wal-index header was loaded before the checkpoint was
67160 ** performed, then the pager-cache associated with pWal is now
67161 ** out of date. So zero the cached wal-index header to ensure that
67165 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
67173 if( pWal->ckptLock ){
67175 pWal->ckptLock = 0;
67192 ret = pWal->iCallback;
67193 pWal->iCallback = 0;
67204 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
67206 ** transition out of exclusive-mode is successful, return 1. This
67211 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
67213 ** WAL is already in exclusive-locking mode - meaning that this
67214 ** routine is a no-op. The pager must already hold the exclusive lock
67217 ** If op is negative, then do a dry-run of the op==1 case but do
67224 assert( pWal->writeLock==0 );
67225 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
67227 /* pWal->readLock is usually set, but might be -1 if there was a
67228 ** prior error while attempting to acquire are read-lock. This cannot
67231 ** upgrade to exclusive-mode following such an error.
67233 assert( pWal->readLock>=0 || pWal->lockError );
67234 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
67237 if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
67238 pWal->exclusiveMode = WAL_NORMAL_MODE;
67239 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
67240 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
67242 rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
67248 assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
67249 assert( pWal->readLock>=0 );
67250 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
67251 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
67254 rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
67260 ** Return true if the argument is non-NULL and the WAL module is using
67261 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
67262 ** WAL module is using shared-memory, return false.
67265 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
67278 assert( pWal->readLock>=0 && pWal->writeLock==0 );
67280 if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
67288 memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
67295 /* Try to open on pSnapshot when the next read-transaction starts
67301 pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
67305 ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
67314 if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
67315 if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
67316 if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
67317 if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
67337 if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
67338 || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
67362 ** read-lock. This function returns the database page-size if it is known,
67366 assert( pWal==0 || pWal->readLock>=0 );
67367 return (pWal ? pWal->szPage : 0);
67374 return pWal->pWalFd;
67384 ** The author disclaims copyright to this source code. In place of
67403 ** The author disclaims copyright to this source code. In place of
67411 ** This file implements an external (disk-based) database using BTrees.
67415 ** "Sorting And Searching", pages 473-480. Addison-Wesley
67421 ** ----------------------------------------------------------------
67422 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
67423 ** ----------------------------------------------------------------
67428 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
67450 ** page, or a pointer-map page.
67469 ** 40 60 15 4-byte meta values passed to higher layers
67474 ** 52 4 Largest root-page (auto/incr_vacuum)
67475 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
67478 ** 68 4 Application-ID
67480 ** 92 4 The version-valid-for number
67483 ** All of the integer values are big-endian (most significant byte first).
67491 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
67506 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
67509 ** |----------------|
67511 ** |----------------|
67513 ** |----------------|
67517 ** |----------------|
67520 ** |----------------| ^ Grows upwards
67523 ** |----------------|
67542 ** The cell pointer array contains zero or more 2-byte numbers which are
67573 ** appears first. A variable-length integer may not be more than 9 bytes long.
67575 ** allows a 64-bit integer to be encoded in 9 bytes.
67598 ** filled with data (pagesize - 4 bytes). The last page can have as little
67621 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
67628 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
67639 ** You can change this value at compile-time by specifying a
67640 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
67641 ** header must be exactly 16 bytes including the zero-terminator so
67653 ** first byte of on-disk image of every BTree page.
67663 ** is derived from the raw on-disk page content.
67670 ** stored in MemPage.pBt->mutex.
67674 u8 intKey; /* True if table b-trees. False for index b-trees */
67687 int nFree; /* Number of free bytes on the page. -1 for unknown */
67690 u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
67691 ** non-overflow cell */
67695 u8 *aDataEnd; /* One byte past the end of the entire page - not just
67697 ** corruption-induced buffer overflow. */
67753 u32 iBDataVersion; /* Combines with pBt->pPager->iDataVersion */
67767 ** If the shared-data extension is enabled, there may be multiple users
67779 # error wrong numeric code for no-transaction
67782 # error wrong numeric code for read-transaction
67785 # error wrong numeric code for write-transaction
67808 ** If a BtShared client fails to obtain a write-lock on a database
67809 ** table (because there exists one or more read-locks on the table),
67810 ** the shared-cache enters 'pending-lock' state and isPending is
67813 ** The shared-cache leaves the 'pending lock' state when either of
67819 ** while in the 'pending-lock' state, no connection may start a new
67822 ** This feature is included to help prevent writer-starvation.
67831 u8 autoVacuum; /* True if auto-vacuum is enabled */
67832 u8 incrVacuum; /* True if incr-vacuum is enabled */
67836 u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
67839 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
67840 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
67849 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
67850 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
67854 BtLock *pLock; /* List of locks held on this shared-btree struct */
67870 #define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
67872 #define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
67884 u16 nSize; /* Size of the cell content on the main b-tree page */
67888 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
67891 ** root-node and 3 for all other internal nodes.
67900 ** b-tree within a database file.
67910 ** found at self->pBt->mutex.
67918 ** SKIPNEXT sqlite3BtreeNext() is a no-op if skipNext>0 and
67919 ** sqlite3BtreePrevious() is no-op if skipNext<0.
67944 u8 curIntKey; /* Value of apPage[0]->intKey */
67946 u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
67949 MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
67975 ** Cursor is valid except that the Cursor.skipNext field is non-zero
67977 ** operation should be a no-op.
68002 #define PENDING_BYTE_PAGE(pBt) ((Pgno)((PENDING_BYTE/((pBt)->pageSize))+1))
68005 ** These macros define the location of the pointer-map entry for a
68010 ** PTRMAP_PAGENO returns the database page number of the pointer-map
68014 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
68016 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
68020 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
68037 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
68040 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
68048 ** overflow pages. The page-number identifies the previous
68051 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
68064 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
68065 assert( p->pBt->inTransaction>=p->inTrans );
68070 ** if the database supports auto-vacuum or not. Because it is used
68076 #define ISAUTOVACUUM (pBt->autoVacuum)
68087 ** the database. As the integrity-check proceeds, for each page used in
68088 ** the database the corresponding bit is set. This allows integrity-check to
68095 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
68105 u32 *heap; /* Min-heap used for analyzing cell coverage */
68110 ** Routines to read or write a two- and four-byte big-endian integer values.
68119 ** two-byte aligned address. get2bytea() is only used for accessing the
68138 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
68140 ** p->locked boolean to true.
68143 assert( p->locked==0 );
68144 assert( sqlite3_mutex_notheld(p->pBt->mutex) );
68145 assert( sqlite3_mutex_held(p->db->mutex) );
68147 sqlite3_mutex_enter(p->pBt->mutex);
68148 p->pBt->db = p->db;
68149 p->locked = 1;
68153 ** Release the BtShared mutex associated with B-Tree handle p and
68154 ** clear the p->locked boolean.
68157 BtShared *pBt = p->pBt;
68158 assert( p->locked==1 );
68159 assert( sqlite3_mutex_held(pBt->mutex) );
68160 assert( sqlite3_mutex_held(p->db->mutex) );
68161 assert( p->db==pBt->db );
68163 sqlite3_mutex_leave(pBt->mutex);
68164 p->locked = 0;
68174 ** and this routine is a no-op. The underlying mutex is non-recursive.
68179 ** by all database connections. The p->pNext is a list of other
68182 ** p, then first unlock all of the others on p->pNext, then wait
68191 assert( p->pNext==0 || p->pNext->pBt>p->pBt );
68192 assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
68193 assert( p->pNext==0 || p->pNext->db==p->db );
68194 assert( p->pPrev==0 || p->pPrev->db==p->db );
68195 assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
68198 assert( !p->locked || p->wantToLock>0 );
68199 assert( p->sharable || p->wantToLock==0 );
68202 assert( sqlite3_mutex_held(p->db->mutex) );
68206 assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
68208 if( !p->sharable ) return;
68209 p->wantToLock++;
68210 if( p->locked ) return;
68227 if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
68228 p->pBt->db = p->db;
68229 p->locked = 1;
68238 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
68239 assert( pLater->sharable );
68240 assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
68241 assert( !pLater->locked || pLater->wantToLock>0 );
68242 if( pLater->locked ){
68247 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
68248 if( pLater->wantToLock ){
68259 assert( sqlite3_mutex_held(p->db->mutex) );
68260 if( p->sharable ){
68261 assert( p->wantToLock>0 );
68262 p->wantToLock--;
68263 if( p->wantToLock==0 ){
68272 ** B-Tree is not marked as sharable.
68277 assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
68278 assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
68279 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
68280 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
68282 return (p->sharable==0 || p->locked);
68294 ** There is a corresponding leave-all procedures.
68305 assert( sqlite3_mutex_held(db->mutex) );
68306 for(i=0; i<db->nDb; i++){
68307 p = db->aDb[i].pBt;
68308 if( p && p->sharable ){
68313 db->noSharedCache = skipOk;
68316 if( db->noSharedCache==0 ) btreeEnterAll(db);
68321 assert( sqlite3_mutex_held(db->mutex) );
68322 for(i=0; i<db->nDb; i++){
68323 p = db->aDb[i].pBt;
68328 if( db->noSharedCache==0 ) btreeLeaveAll(db);
68340 if( !sqlite3_mutex_held(db->mutex) ){
68343 for(i=0; i<db->nDb; i++){
68345 p = db->aDb[i].pBt;
68346 if( p && p->sharable &&
68347 (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
68358 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
68362 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
68370 if( db->pVfs==0 && db->nDb==0 ) return 1;
68372 assert( iDb>=0 && iDb<db->nDb );
68373 if( !sqlite3_mutex_held(db->mutex) ) return 0;
68375 p = db->aDb[iDb].pBt;
68377 return p->sharable==0 || p->locked==1;
68385 ** these two routines, all mutex operations are no-ops in that case and
68389 ** the ones below, are no-ops and are null #defines in btree.h.
68393 p->pBt->db = p->db;
68397 for(i=0; i<db->nDb; i++){
68398 Btree *p = db->aDb[i].pBt;
68400 p->pBt->db = p->db;
68415 sqlite3BtreeEnter(pCur->pBtree);
68419 sqlite3BtreeLeave(pCur->pBtree);
68431 ** The author disclaims copyright to this source code. In place of
68439 ** This file implements an external (disk-based) database using BTrees.
68463 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
68468 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
68471 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
68484 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
68529 ** shared-cache table level locks. If the library is compiled with the
68530 ** shared-cache feature disabled, then there is only ever one user
68532 ** So define the lock related functions as no-ops.
68547 u64 n = pBt->nSeek;
68548 pBt->nSeek = 0;
68559 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
68567 (int)p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
68578 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
68590 ** For example, when writing to a table with root-page iRoot via
68603 ** hold a write-lock on the schema table (root page 1). This is also
68608 Pgno iRoot, /* Root page of b-tree */
68609 int isIndex, /* True if iRoot is the root of an index b-tree */
68612 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
68617 ** and has the read-uncommitted flag set, then no lock is required.
68620 if( (pBtree->sharable==0)
68621 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
68628 ** the correct locks are held. So do not bother - just return true.
68631 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
68635 /* Figure out the root-page that the lock should be held on. For table
68636 ** b-trees, this is just the root page of the b-tree being read or
68637 ** written. For index b-trees, it is the root page of the associated
68642 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
68644 if( pIdx->tnum==iRoot ){
68651 iTab = pIdx->pTable->tnum;
68659 /* Search for the required lock. Either a write-lock on root-page iTab, a
68660 ** write-lock on the schema table, or (if the client is reading) a
68661 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
68662 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
68663 if( pLock->pBtree==pBtree
68664 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
68665 && pLock->eLock>=eLockType
68687 ** read-uncommitted flag set, then it is OK for the other object to
68697 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
68698 if( p->pgnoRoot==iRoot
68699 && p->pBtree!=pBtree
68700 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
68711 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
68716 BtShared *pBt = p->pBt;
68721 assert( p->db!=0 );
68722 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
68724 /* If requesting a write-lock, then the Btree must have an open write
68728 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
68729 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
68731 /* This routine is a no-op if the shared-cache is not enabled */
68732 if( !p->sharable ){
68739 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
68740 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
68744 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
68745 /* The condition (pIter->eLock!=eLock) in the following if(...)
68748 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
68754 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
68755 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
68756 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
68757 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
68759 assert( p==pBt->pWriter );
68760 pBt->btsFlags |= BTS_PENDING;
68771 ** Add a lock on the table with root-page iTable to the shared-btree used
68788 BtShared *pBt = p->pBt;
68794 assert( p->db!=0 );
68796 /* A connection with the read-uncommitted flag set will never try to
68797 ** obtain a read-lock using this function. The only read-lock obtained
68798 ** by a connection in read-uncommitted mode is on the sqlite_schema
68800 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
68802 /* This function should only be called on a sharable b-tree after it
68803 ** has been determined that no other b-tree holds a conflicting lock. */
68804 assert( p->sharable );
68808 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
68809 if( pIter->iTable==iTable && pIter->pBtree==p ){
68823 pLock->iTable = iTable;
68824 pLock->pBtree = p;
68825 pLock->pNext = pBt->pLock;
68826 pBt->pLock = pLock;
68830 ** and the requested lock. This means if a write-lock was already held
68831 ** and a read-lock requested, we don't incorrectly downgrade the lock.
68834 if( eLock>pLock->eLock ){
68835 pLock->eLock = eLock;
68852 BtShared *pBt = p->pBt;
68853 BtLock **ppIter = &pBt->pLock;
68856 assert( p->sharable || 0==*ppIter );
68857 assert( p->inTrans>0 );
68861 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
68862 assert( pLock->pBtree->inTrans>=pLock->eLock );
68863 if( pLock->pBtree==p ){
68864 *ppIter = pLock->pNext;
68865 assert( pLock->iTable!=1 || pLock==&p->lock );
68866 if( pLock->iTable!=1 ){
68870 ppIter = &pLock->pNext;
68874 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
68875 if( pBt->pWriter==p ){
68876 pBt->pWriter = 0;
68877 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
68878 }else if( pBt->nTransaction==2 ){
68888 pBt->btsFlags &= ~BTS_PENDING;
68893 ** This function changes all write-locks held by Btree p into read-locks.
68896 BtShared *pBt = p->pBt;
68897 if( pBt->pWriter==p ){
68899 pBt->pWriter = 0;
68900 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
68901 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
68902 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
68903 pLock->eLock = READ_LOCK;
68921 return sqlite3_mutex_held(p->pBt->mutex);
68925 ** database connetion. This is important in shared-cache mode. If the database
68926 ** connection pointers get out-of-sync, it is possible for routines like
68929 ** statements only and for the purpose of double-checking that the btree code
68930 ** does keep the database connection pointers up-to-date.
68934 return (p->pBtree->db==p->pBt->db);
68942 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
68945 ** Invalidate the overflow page-list cache for all cursors opened
68950 assert( sqlite3_mutex_held(pBt->mutex) );
68951 for(p=pBt->pCursor; p; p=p->pNext){
68964 ** cursors open on any row within the table with root-page pgnoRoot.
68977 assert( pBtree->hasIncrblobCur );
68979 pBtree->hasIncrblobCur = 0;
68980 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
68981 if( (p->curFlags & BTCF_Incrblob)!=0 ){
68982 pBtree->hasIncrblobCur = 1;
68983 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
68984 p->eState = CURSOR_INVALID;
68997 ** when a page that previously contained data becomes a free-list leaf
69002 ** free-list leaf pages:
69005 ** a free-list leaf page, the page is not written to the database
69006 ** (as free-list leaf pages contain no meaningful data). Sometimes
69010 ** 2) When a free-list leaf page is reused, its content is not read
69016 ** a page is moved to the free-list and then reused within the same
69018 ** it is moved to the free-list and it is also not journalled when it
69019 ** is extracted from the free-list and reused, then the original data
69024 ** moved to become a free-list leaf page, the corresponding bit is
69025 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
69032 if( !pBt->pHasContent ){
69033 assert( pgno<=pBt->nPage );
69034 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
69035 if( !pBt->pHasContent ){
69039 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
69040 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
69048 ** This function is called when a free-list leaf page is removed from the
69049 ** free-list for reuse. It returns false if it is safe to retrieve the
69050 ** page from the pager layer with the 'no-content' flag set. True otherwise.
69053 Bitvec *p = pBt->pHasContent;
69059 ** invoked at the conclusion of each write-transaction.
69062 sqlite3BitvecDestroy(pBt->pHasContent);
69063 pBt->pHasContent = 0;
69071 if( pCur->iPage>=0 ){
69072 for(i=0; i<pCur->iPage; i++){
69073 releasePageNotNull(pCur->apPage[i]);
69075 releasePageNotNull(pCur->pPage);
69076 pCur->iPage = -1;
69083 ** function saves the current cursor key in variables pCur->nKey and
69084 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
69088 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
69089 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
69090 ** set to point to a malloced buffer pCur->nKey bytes in size containing
69095 assert( CURSOR_VALID==pCur->eState );
69096 assert( 0==pCur->pKey );
69099 if( pCur->curIntKey ){
69101 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
69106 ** up to the size of 1 varint plus 1 8-byte value when the cursor
69110 pCur->nKey = sqlite3BtreePayloadSize(pCur);
69111 pKey = sqlite3Malloc( pCur->nKey + 9 + 8 );
69113 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
69115 memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
69116 pCur->pKey = pKey;
69124 assert( !pCur->curIntKey || !pCur->pKey );
69138 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
69139 assert( 0==pCur->pKey );
69142 if( pCur->curFlags & BTCF_Pinned ){
69145 if( pCur->eState==CURSOR_SKIPNEXT ){
69146 pCur->eState = CURSOR_VALID;
69148 pCur->skipNext = 0;
69154 pCur->eState = CURSOR_REQUIRESEEK;
69157 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
69166 ** the table with root-page iRoot. "Saving the cursor position" means that
69177 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
69187 assert( sqlite3_mutex_held(pBt->mutex) );
69188 assert( pExcept==0 || pExcept->pBt==pBt );
69189 for(p=pBt->pCursor; p; p=p->pNext){
69190 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
69193 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
69208 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
69209 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
69215 testcase( p->iPage>=0 );
69219 p = p->pNext;
69229 sqlite3_free(pCur->pKey);
69230 pCur->pKey = 0;
69231 pCur->eState = CURSOR_INVALID;
69250 KeyInfo *pKeyInfo = pCur->pKeyInfo;
69255 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
69260 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
69279 assert( pCur->eState>=CURSOR_REQUIRESEEK );
69280 if( pCur->eState==CURSOR_FAULT ){
69281 return pCur->skipNext;
69283 pCur->eState = CURSOR_INVALID;
69287 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
69290 sqlite3_free(pCur->pKey);
69291 pCur->pKey = 0;
69292 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
69293 if( skipNext ) pCur->skipNext = skipNext;
69294 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
69295 pCur->eState = CURSOR_SKIPNEXT;
69302 (p->eState>=CURSOR_REQUIRESEEK ? \
69322 assert( sizeof(pCur->eState)==1 );
69354 assert( pCur->eState!=CURSOR_VALID );
69360 if( pCur->eState!=CURSOR_VALID ){
69384 pCur->hints = x;
69391 ** number for the pointer-map page that contains the entry for the
69401 assert( sqlite3_mutex_held(pBt->mutex) );
69403 nPagesPerMapPage = (pBt->usableSize/5)+1;
69404 iPtrMap = (pgno-2)/nPagesPerMapPage;
69418 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
69419 ** a no-op. If an error occurs, the appropriate error code is written
69431 assert( sqlite3_mutex_held(pBt->mutex) );
69432 /* The super-journal page number must never be used as a pointer map page */
69435 assert( pBt->autoVacuum );
69441 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
69458 assert( offset <= (int)pBt->usableSize-5 );
69462 TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
69488 assert( sqlite3_mutex_held(pBt->mutex) );
69491 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
69502 assert( offset <= (int)pBt->usableSize-5 );
69524 ** 4-byte child pointer found on interior pages, if there is one.
69529 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
69531 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
69537 ** on a single B-tree page. Make necessary adjustments to the CellInfo
69558 minLocal = pPage->minLocal;
69559 maxLocal = pPage->maxLocal;
69560 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
69564 pInfo->nLocal = (u16)surplus;
69566 pInfo->nLocal = (u16)minLocal;
69568 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
69577 maxLocal = pPage->maxLocal;
69583 minLocal = pPage->minLocal;
69584 surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize-4);
69608 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
69609 assert( pPage->leaf==0 );
69610 assert( pPage->childPtrSize==4 );
69614 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
69615 pInfo->nPayload = 0;
69616 pInfo->nLocal = 0;
69617 pInfo->pPayload = 0;
69629 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
69630 assert( pPage->leaf==0 || pPage->leaf==1 );
69631 assert( pPage->intKeyLeaf );
69632 assert( pPage->childPtrSize==0 );
69653 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
69656 ** This routine is a high-runner.
69686 pInfo->nKey = *(i64*)&iKey;
69687 pInfo->nPayload = nPayload;
69688 pInfo->pPayload = pIter;
69689 testcase( nPayload==pPage->maxLocal );
69690 testcase( nPayload==(u32)pPage->maxLocal+1 );
69691 if( nPayload<=pPage->maxLocal ){
69695 pInfo->nSize = nPayload + (u16)(pIter - pCell);
69696 if( pInfo->nSize<4 ) pInfo->nSize = 4;
69697 pInfo->nLocal = (u16)nPayload;
69710 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
69711 assert( pPage->leaf==0 || pPage->leaf==1 );
69712 assert( pPage->intKeyLeaf==0 );
69713 pIter = pCell + pPage->childPtrSize;
69723 pInfo->nKey = nPayload;
69724 pInfo->nPayload = nPayload;
69725 pInfo->pPayload = pIter;
69726 testcase( nPayload==pPage->maxLocal );
69727 testcase( nPayload==(u32)pPage->maxLocal+1 );
69728 if( nPayload<=pPage->maxLocal ){
69732 pInfo->nSize = nPayload + (u16)(pIter - pCell);
69733 if( pInfo->nSize<4 ) pInfo->nSize = 4;
69734 pInfo->nLocal = (u16)nPayload;
69744 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
69752 ** data area of the btree-page. The return number includes the cell
69761 u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
69771 pPage->xParseCell(pPage, pCell, &debuginfo);
69783 testcase( nSize==pPage->maxLocal );
69784 testcase( nSize==(u32)pPage->maxLocal+1 );
69785 if( nSize<=pPage->maxLocal ){
69786 nSize += (u32)(pIter - pCell);
69789 int minLocal = pPage->minLocal;
69790 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
69791 testcase( nSize==pPage->maxLocal );
69792 testcase( nSize==(u32)pPage->maxLocal+1 );
69793 if( nSize>pPage->maxLocal ){
69796 nSize += 4 + (u16)(pIter - pCell);
69811 pPage->xParseCell(pPage, pCell, &debuginfo);
69816 assert( pPage->childPtrSize==4 );
69819 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
69820 return (u16)(pIter - pCell);
69833 pPage->xParseCell(pPage, pCell, &debuginfo);
69845 /* pIter now points at the 64-bit integer key value, a variable length
69856 testcase( nSize==pPage->maxLocal );
69857 testcase( nSize==(u32)pPage->maxLocal+1 );
69858 if( nSize<=pPage->maxLocal ){
69859 nSize += (u32)(pIter - pCell);
69862 int minLocal = pPage->minLocal;
69863 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
69864 testcase( nSize==pPage->maxLocal );
69865 testcase( nSize==(u32)pPage->maxLocal+1 );
69866 if( nSize>pPage->maxLocal ){
69869 nSize += 4 + (u16)(pIter - pCell);
69880 return pPage->xCellSize(pPage, findCell(pPage, iCell));
69888 ** pointer to an overflow page, insert an entry into the pointer-map for
69895 pPage->xParseCell(pPage, pCell, &info);
69898 if( SQLITE_WITHIN(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
69903 ovfl = get4byte(&pCell[info.nSize-4]);
69904 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
69912 ** page so that there are no free-blocks on the free-block list.
69917 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
69918 ** b-tree page so that there are no freeblocks or fragment bytes, all
69924 int pc; /* Address of the i-th cell */
69933 unsigned char *src; /* Source of content */
69938 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
69939 assert( pPage->pBt!=0 );
69940 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
69941 assert( pPage->nOverflow==0 );
69942 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
69943 data = pPage->aData;
69944 hdr = pPage->hdrOffset;
69945 cellOffset = pPage->cellOffset;
69946 nCell = pPage->nCell;
69949 usableSize = pPage->pBt->usableSize;
69954 ** offsets to each pointer in the cell-pointer array than it is to
69958 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
69961 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
69975 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
69982 assert( cbrk+(iFree-top) <= usableSize );
69983 memmove(&data[cbrk], &data[top], iFree-top);
69995 iCellLast = usableSize - 4;
69998 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
69999 memcpy(&temp[iCellStart], &data[iCellStart], usableSize - iCellStart);
70002 u8 *pAddr; /* The i-th cell pointer */
70014 size = pPage->xCellSize(pPage, &src[pc]);
70015 cbrk -= size;
70029 assert( pPage->nFree>=0 );
70030 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
70037 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
70038 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
70043 ** Search the free-list on page pPg for space to store a cell nByte bytes in
70045 ** from the free-list.
70047 ** If no suitable space can be found on the free-list, return NULL.
70057 const int hdr = pPg->hdrOffset; /* Offset to page header */
70058 u8 * const aData = pPg->aData; /* Page data */
70063 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
70068 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
70069 ** freeblock form a big-endian integer which is the size of the freeblock
70070 ** in bytes, including the 4-byte header. */
70073 if( (x = size - nByte)>=0 ){
70077 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
70081 /* Remove the slot from the free-list. Update the number of
70091 /* The slot remains on the free-list. Reduce its size to account
70108 if( pc>maxPC+nByte-4 ){
70116 ** Allocate nByte bytes of space from within the B-Tree page passed
70117 ** as the first argument. Write into *pIdx the index into pPage->aData[]
70129 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
70130 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
70136 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
70137 assert( pPage->pBt );
70138 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
70140 assert( pPage->nFree>=nByte );
70141 assert( pPage->nOverflow==0 );
70142 assert( nByte < (int)(pPage->pBt->usableSize-8) );
70144 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
70145 gap = pPage->cellOffset + 2*pPage->nCell;
70147 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
70150 ** However, that integer is too large to be stored in a 2-byte unsigned
70154 assert( top<=(int)pPage->pBt->usableSize ); /* by btreeComputeFreeSpace() */
70156 if( top==0 && pPage->pBt->usableSize==65536 ){
70174 assert( pSpace+nByte<=data+pPage->pBt->usableSize );
70175 *pIdx = g2 = (int)(pSpace-data);
70191 assert( pPage->nCell>0 || CORRUPT_DB );
70192 assert( pPage->nFree>=0 );
70193 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
70206 top -= nByte;
70208 assert( top+nByte <= (int)pPage->pBt->usableSize );
70214 ** Return a section of the pPage->aData to the freelist.
70215 ** The first byte of the new free block is pPage->aData[iStart]
70234 unsigned char *data = pPage->aData; /* Page content */
70237 assert( pPage->pBt!=0 );
70238 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
70239 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
70240 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
70241 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
70243 assert( iStart<=pPage->pBt->usableSize-4 );
70248 hdr = pPage->hdrOffset;
70260 if( iFreeBlk>pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
70272 nFrag = iFreeBlk - iEnd;
70275 if( iEnd > pPage->pBt->usableSize ){
70278 iSize = iEnd - iStart;
70290 nFrag += iStart - iPtrEnd;
70291 iSize = iEnd - iPtr;
70296 data[hdr+7] -= nFrag;
70312 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
70319 pPage->nFree += iOrigSize;
70336 BtShared *pBt; /* A copy of pPage->pBt */
70338 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
70339 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
70340 pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
70342 pPage->childPtrSize = 4-4*pPage->leaf;
70343 pBt = pPage->pBt;
70345 /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
70346 ** interior table b-tree page. */
70348 /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
70349 ** leaf table b-tree page. */
70351 pPage->intKey = 1;
70352 if( pPage->leaf ){
70353 pPage->intKeyLeaf = 1;
70354 pPage->xCellSize = cellSizePtrTableLeaf;
70355 pPage->xParseCell = btreeParseCellPtr;
70357 pPage->intKeyLeaf = 0;
70358 pPage->xCellSize = cellSizePtrNoPayload;
70359 pPage->xParseCell = btreeParseCellPtrNoPayload;
70361 pPage->maxLocal = pBt->maxLeaf;
70362 pPage->minLocal = pBt->minLeaf;
70364 /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
70365 ** interior index b-tree page. */
70367 /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
70368 ** leaf index b-tree page. */
70370 pPage->intKey = 0;
70371 pPage->intKeyLeaf = 0;
70372 pPage->xCellSize = cellSizePtr;
70373 pPage->xParseCell = btreeParseCellPtrIndex;
70374 pPage->maxLocal = pBt->maxLocal;
70375 pPage->minLocal = pBt->minLocal;
70377 /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
70379 pPage->intKey = 0;
70380 pPage->intKeyLeaf = 0;
70381 pPage->xCellSize = cellSizePtr;
70382 pPage->xParseCell = btreeParseCellPtrIndex;
70385 pPage->max1bytePayload = pBt->max1bytePayload;
70391 ** in the pPage->nFree field.
70394 int pc; /* Address of a freeblock within pPage->aData[] */
70396 u8 *data; /* Equal to pPage->aData */
70403 assert( pPage->pBt!=0 );
70404 assert( pPage->pBt->db!=0 );
70405 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
70406 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
70407 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
70408 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
70409 assert( pPage->isInit==1 );
70410 assert( pPage->nFree<0 );
70412 usableSize = pPage->pBt->usableSize;
70413 hdr = pPage->hdrOffset;
70414 data = pPage->aData;
70415 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
70419 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
70420 iCellLast = usableSize - 4;
70423 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
70427 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
70431 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
70458 ** of the cell-content area plus the number of free bytes within
70459 ** the cell-content area. If this is greater than the usable-size
70461 ** serves to verify that the offset to the start of the cell-content
70467 pPage->nFree = (u16)(nFree - iCellFirst);
70480 int pc; /* Address of a freeblock within pPage->aData[] */
70481 u8 *data; /* Equal to pPage->aData */
70485 iCellFirst = pPage->cellOffset + 2*pPage->nCell;
70486 usableSize = pPage->pBt->usableSize;
70487 iCellLast = usableSize - 4;
70488 data = pPage->aData;
70489 cellOffset = pPage->cellOffset;
70490 if( !pPage->leaf ) iCellLast--;
70491 for(i=0; i<pPage->nCell; i++){
70498 sz = pPage->xCellSize(pPage, &data[pc]);
70511 ** not contain a well-formed database page, then return
70513 ** guarantee that the page is well-formed. It only shows that
70517 u8 *data; /* Equal to pPage->aData */
70520 assert( pPage->pBt!=0 );
70521 assert( pPage->pBt->db!=0 );
70522 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
70523 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
70524 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
70525 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
70526 assert( pPage->isInit==0 );
70528 pBt = pPage->pBt;
70529 data = pPage->aData + pPage->hdrOffset;
70530 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
70531 ** the b-tree page type. */
70535 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
70536 pPage->maskPage = (u16)(pBt->pageSize - 1);
70537 pPage->nOverflow = 0;
70538 pPage->cellOffset = pPage->hdrOffset + 8 + pPage->childPtrSize;
70539 pPage->aCellIdx = data + pPage->childPtrSize + 8;
70540 pPage->aDataEnd = pPage->aData + pBt->pageSize;
70541 pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
70542 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
70544 pPage->nCell = get2byte(&data[3]);
70545 if( pPage->nCell>MX_CELL(pBt) ){
70549 testcase( pPage->nCell==MX_CELL(pBt) );
70550 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
70554 assert( pPage->nCell>0
70555 || get2byteNotZero(&data[5])==(int)pBt->usableSize
70557 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
70558 pPage->isInit = 1;
70559 if( pBt->db->flags & SQLITE_CellSizeCk ){
70570 unsigned char *data = pPage->aData;
70571 BtShared *pBt = pPage->pBt;
70572 u8 hdr = pPage->hdrOffset;
70575 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB );
70576 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
70577 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
70578 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
70579 assert( sqlite3_mutex_held(pBt->mutex) );
70580 if( pBt->btsFlags & BTS_FAST_SECURE ){
70581 memset(&data[hdr], 0, pBt->usableSize - hdr);
70587 put2byte(&data[hdr+5], pBt->usableSize);
70588 pPage->nFree = (u16)(pBt->usableSize - first);
70590 pPage->cellOffset = first;
70591 pPage->aDataEnd = &data[pBt->pageSize];
70592 pPage->aCellIdx = &data[first];
70593 pPage->aDataOfst = &data[pPage->childPtrSize];
70594 pPage->nOverflow = 0;
70595 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
70596 pPage->maskPage = (u16)(pBt->pageSize - 1);
70597 pPage->nCell = 0;
70598 pPage->isInit = 1;
70608 if( pgno!=pPage->pgno ){
70609 pPage->aData = sqlite3PagerGetData(pDbPage);
70610 pPage->pDbPage = pDbPage;
70611 pPage->pBt = pBt;
70612 pPage->pgno = pgno;
70613 pPage->hdrOffset = pgno==1 ? 100 : 0;
70615 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
70640 assert( sqlite3_mutex_held(pBt->mutex) );
70641 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
70654 assert( sqlite3_mutex_held(pBt->mutex) );
70655 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
70664 ** error, return ((unsigned int)-1).
70667 return pBt->nPage;
70671 return btreePagecount(p->pBt);
70679 ** And if the fetch fails, this routine must decrement pCur->iPage.
70681 ** The page is fetched as read-write unless pCur is not NULL and is
70682 ** a read-only cursor.
70692 int bReadOnly /* True for a read-only page */
70696 assert( sqlite3_mutex_held(pBt->mutex) );
70697 assert( pCur==0 || ppPage==&pCur->pPage );
70698 assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
70699 assert( pCur==0 || pCur->iPage>0 );
70705 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
70710 if( (*ppPage)->isInit==0 ){
70717 assert( (*ppPage)->pgno==pgno || CORRUPT_DB );
70718 assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
70722 if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
70732 pCur->iPage--;
70733 pCur->pPage = pCur->apPage[pCur->iPage];
70747 assert( pPage->aData );
70748 assert( pPage->pBt );
70749 assert( pPage->pDbPage!=0 );
70750 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
70751 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
70752 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
70753 sqlite3PagerUnrefNotNull(pPage->pDbPage);
70760 assert( pPage->aData );
70761 assert( pPage->pBt );
70762 assert( pPage->pDbPage!=0 );
70763 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
70764 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
70765 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
70766 sqlite3PagerUnrefPageOne(pPage->pDbPage);
70786 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
70791 (*ppPage)->isInit = 0;
70811 if( pPage->isInit ){
70812 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
70813 pPage->isInit = 0;
70820 ** the call for every page that comes in for re-initing. */
70831 assert( pBt->db );
70832 assert( sqlite3_mutex_held(pBt->db->mutex) );
70833 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
70841 ** be exclusively in memory, or it might use a disk-based memory cache.
70845 ** If zFilename is ":memory:" then an in-memory database is created
70858 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
70875 /* Set the variable isMemdb to true for an in-memory database, or
70876 ** false for a file-based database.
70888 assert( sqlite3_mutex_held(db->mutex) );
70907 p->inTrans = TRANS_NONE;
70908 p->db = db;
70910 p->lock.pBtree = p;
70911 p->lock.iTable = 1;
70922 int nFullPathname = pVfs->mxPathname+1;
70926 p->sharable = 1;
70952 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
70953 assert( pBt->nRef>0 );
70954 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
70955 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
70957 for(iDb=db->nDb-1; iDb>=0; iDb--){
70958 Btree *pExisting = db->aDb[iDb].pBt;
70959 if( pExisting && pExisting->pBt==pBt ){
70967 p->pBt = pBt;
70968 pBt->nRef++;
70982 p->sharable = 1;
71004 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
71007 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
71008 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
71013 pBt->openFlags = (u8)flags;
71014 pBt->db = db;
71015 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
71016 p->pBt = pBt;
71018 pBt->pCursor = 0;
71019 pBt->pPage1 = 0;
71020 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
71022 pBt->btsFlags |= BTS_SECURE_DELETE;
71024 pBt->btsFlags |= BTS_OVERWRITE;
71026 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
71027 ** determined by the 2-byte integer located at an offset of 16 bytes from
71029 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
71030 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
71031 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
71032 pBt->pageSize = 0;
71034 /* If the magic name ":memory:" will create an in-memory database, then
71035 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
71038 ** regular file-name. In this case the auto-vacuum applies as per normal.
71041 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
71042 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
71047 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
71048 ** determined by the one-byte unsigned integer found at an offset of 20
71051 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
71053 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
71054 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
71057 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
71059 pBt->usableSize = pBt->pageSize - nReserve;
71060 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
71065 pBt->nRef = 1;
71066 if( p->sharable ){
71070 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
71071 if( pBt->mutex==0 ){
71077 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
71089 if( p->sharable ){
71092 for(i=0; i<db->nDb; i++){
71093 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
71094 while( pSib->pPrev ){ pSib = pSib->pPrev; }
71095 if( (uptr)p->pBt<(uptr)pSib->pBt ){
71096 p->pNext = pSib;
71097 p->pPrev = 0;
71098 pSib->pPrev = p;
71100 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
71101 pSib = pSib->pNext;
71103 p->pNext = pSib->pNext;
71104 p->pPrev = pSib;
71105 if( p->pNext ){
71106 p->pNext->pPrev = p;
71108 pSib->pNext = p;
71119 if( pBt && pBt->pPager ){
71120 sqlite3PagerClose(pBt->pPager, 0);
71128 /* If the B-Tree was successfully opened, set the pager-cache size to the
71129 ** default value. Except, when opening on an existing shared pager-cache,
71130 ** do not change the pager-cache size.
71136 pFile = sqlite3PagerFile(pBt->pPager);
71137 if( pFile->pMethods ){
71138 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
71161 assert( sqlite3_mutex_notheld(pBt->mutex) );
71164 pBt->nRef--;
71165 if( pBt->nRef<=0 ){
71167 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
71170 while( ALWAYS(pList) && pList->pNext!=pBt ){
71171 pList=pList->pNext;
71174 pList->pNext = pBt->pNext;
71178 sqlite3_mutex_free(pBt->mutex);
71190 ** Make sure pBt->pTmpSpace points to an allocation of
71191 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
71196 assert( pBt->pTmpSpace==0 );
71199 assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 );
71200 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
71201 if( pBt->pTmpSpace==0 ){
71202 BtCursor *pCur = pBt->pCursor;
71203 pBt->pCursor = pCur->pNext; /* Unlink the cursor */
71208 /* One of the uses of pBt->pTmpSpace is to format cells before
71221 ** left-child pointer to the beginning of a cell.
71223 memset(pBt->pTmpSpace, 0, 8);
71224 pBt->pTmpSpace += 4;
71229 ** Free the pBt->pTmpSpace allocation
71232 if( pBt->pTmpSpace ){
71233 pBt->pTmpSpace -= 4;
71234 sqlite3PageFree(pBt->pTmpSpace);
71235 pBt->pTmpSpace = 0;
71243 BtShared *pBt = p->pBt;
71246 assert( sqlite3_mutex_held(p->db->mutex) );
71252 BtCursor *pCur = pBt->pCursor;
71255 pCur = pCur->pNext;
71256 assert( pTmp->pBtree!=p );
71263 ** The call to sqlite3BtreeRollback() drops any table-locks held by
71269 /* If there are still other outstanding references to the shared-btree
71271 ** up the shared-btree.
71273 assert( p->wantToLock==0 && p->locked==0 );
71274 if( !p->sharable || removeFromSharingList(pBt) ){
71280 assert( !pBt->pCursor );
71281 sqlite3PagerClose(pBt->pPager, p->db);
71282 if( pBt->xFreeSchema && pBt->pSchema ){
71283 pBt->xFreeSchema(pBt->pSchema);
71285 sqlite3DbFree(0, pBt->pSchema);
71291 assert( p->wantToLock==0 );
71292 assert( p->locked==0 );
71293 if( p->pPrev ) p->pPrev->pNext = p->pNext;
71294 if( p->pNext ) p->pNext->pPrev = p->pPrev;
71309 BtShared *pBt = p->pBt;
71310 assert( sqlite3_mutex_held(p->db->mutex) );
71312 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
71328 BtShared *pBt = p->pBt;
71330 assert( sqlite3_mutex_held(p->db->mutex) );
71332 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
71343 BtShared *pBt = p->pBt;
71344 assert( sqlite3_mutex_held(p->db->mutex) );
71346 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
71357 ** is a very low but non-zero probability of damage. Level 3 reduces the
71365 BtShared *pBt = p->pBt;
71366 assert( sqlite3_mutex_held(p->db->mutex) );
71368 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
71397 BtShared *pBt = p->pBt;
71400 pBt->nReserveWanted = nReserve;
71401 x = pBt->pageSize - pBt->usableSize;
71403 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
71409 ((pageSize-1)&pageSize)==0 ){
71411 assert( !pBt->pCursor );
71413 pBt->pageSize = (u32)pageSize;
71416 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
71417 pBt->usableSize = pBt->pageSize - (u16)nReserve;
71418 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
71427 return p->pBt->pageSize;
71432 ** may only be called if it is guaranteed that the b-tree mutex is already
71436 ** known that the shared b-tree mutex is held, but the mutex on the
71443 assert( sqlite3_mutex_held(p->pBt->mutex) );
71444 n = p->pBt->pageSize - p->pBt->usableSize;
71455 ** The amount of reserve can only grow - never shrink.
71460 n1 = (int)p->pBt->nReserveWanted;
71475 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
71486 ** newFlag==(-1) No changes
71491 ** freelist leaf pages are not written back to the database. Thus in-page
71505 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
71506 p->pBt->btsFlags |= BTS_SECURE_DELETE*newFlag;
71508 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
71514 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
71515 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
71516 ** is disabled. The default value for the auto-vacuum property is
71523 BtShared *pBt = p->pBt;
71528 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
71531 pBt->autoVacuum = av ?1:0;
71532 pBt->incrVacuum = av==2 ?1:0;
71540 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
71550 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
71551 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
71560 ** If the user has not set the safety-level for this database connection
71561 ** using "PRAGMA synchronous", and if the safety-level is not already
71570 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
71571 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
71572 if( pDb->bSyncSet==0
71573 && pDb->safety_level!=safety_level
71574 && pDb!=&db->aDb[1]
71576 pDb->safety_level = safety_level;
71577 sqlite3PagerSetFlags(pBt->pPager,
71578 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
71595 ** well-formed database file, then SQLITE_CORRUPT is returned.
71605 assert( sqlite3_mutex_held(pBt->mutex) );
71606 assert( pBt->pPage1==0 );
71607 rc = sqlite3PagerSharedLock(pBt->pPager);
71615 nPage = get4byte(28+(u8*)pPage1->aData);
71616 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
71617 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
71620 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
71626 u8 *page1 = pPage1->aData;
71628 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
71637 pBt->btsFlags |= BTS_READ_ONLY;
71644 pBt->btsFlags |= BTS_READ_ONLY;
71655 ** may not be the latest version - there may be a newer one in the log
71658 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
71660 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
71676 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
71685 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
71686 ** determined by the 2-byte integer located at an offset of 16 bytes from
71689 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
71691 if( ((pageSize-1)&pageSize)!=0
71697 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
71699 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
71703 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
71704 ** determined by the one-byte unsigned integer found at an offset of 20
71706 usableSize = pageSize - page1[20];
71707 if( (u32)pageSize!=pBt->pageSize ){
71709 ** of BtShared.pageSize, we have discovered that the page-size is
71710 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
71712 ** again with the correct page-size.
71715 pBt->usableSize = usableSize;
71716 pBt->pageSize = pageSize;
71718 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
71719 pageSize-usableSize);
71723 if( sqlite3WritableSchema(pBt->db)==0 ){
71730 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
71736 pBt->pageSize = pageSize;
71737 pBt->usableSize = usableSize;
71739 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
71740 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
71746 ** cells can will fit on one page. We assume a 10-byte page header.
71748 ** 2-byte pointer to the cell
71749 ** 4-byte child pointer
71750 ** 9-byte nKey value
71751 ** 4-byte nData value
71752 ** 4-byte overflow page pointer
71753 ** So a cell consists of a 2-byte pointer, a header which is as much as
71757 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
71758 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
71759 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
71760 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
71761 if( pBt->maxLocal>127 ){
71762 pBt->max1bytePayload = 127;
71764 pBt->max1bytePayload = (u8)pBt->maxLocal;
71766 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
71767 pBt->pPage1 = pPage1;
71768 pBt->nPage = nPage;
71773 pBt->pPage1 = 0;
71793 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
71794 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
71795 && pCur->eState!=CURSOR_FAULT ) r++;
71807 ** If there is a transaction in progress, this routine is a no-op.
71810 assert( sqlite3_mutex_held(pBt->mutex) );
71811 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
71812 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
71813 MemPage *pPage1 = pBt->pPage1;
71814 assert( pPage1->aData );
71815 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
71816 pBt->pPage1 = 0;
71831 assert( sqlite3_mutex_held(pBt->mutex) );
71832 if( pBt->nPage>0 ){
71835 pP1 = pBt->pPage1;
71837 data = pP1->aData;
71838 rc = sqlite3PagerWrite(pP1->pDbPage);
71842 data[16] = (u8)((pBt->pageSize>>8)&0xff);
71843 data[17] = (u8)((pBt->pageSize>>16)&0xff);
71846 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
71847 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
71851 memset(&data[24], 0, 100-24);
71853 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
71855 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
71856 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
71857 put4byte(&data[36 + 4*4], pBt->autoVacuum);
71858 put4byte(&data[36 + 7*4], pBt->incrVacuum);
71860 pBt->nPage = 1;
71873 p->pBt->nPage = 0;
71874 rc = newDatabase(p->pBt);
71880 ** Attempt to start a new transaction. A write-transaction
71881 ** is started if the second argument is nonzero, otherwise a read-
71885 ** upgraded to exclusive by calling this routine a second time - the
71888 ** A write-transaction must be started before attempting any
71902 ** if there is one. But if there was previously a read-lock, do not
71903 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
71904 ** returned when there is already a read-lock in order to avoid a deadlock.
71915 BtShared *pBt = p->pBt;
71916 Pager *pPager = pBt->pPager;
71922 /* If the btree is already in a write-transaction, or it
71923 ** is already in a read-transaction and a read-transaction
71924 ** is requested, this is a no-op.
71926 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
71929 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
71931 if( (p->db->flags & SQLITE_ResetDatabase)
71934 pBt->btsFlags &= ~BTS_READ_ONLY;
71937 /* Write transactions are not possible on a read-only database */
71938 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
71947 ** on this shared-btree structure and a second write transaction is
71950 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
71951 || (pBt->btsFlags & BTS_PENDING)!=0
71953 pBlock = pBt->pWriter->db;
71956 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
71957 if( pIter->pBtree!=p ){
71958 pBlock = pIter->pBtree->db;
71964 sqlite3ConnectionBlocked(p->db, pBlock);
71971 /* Any read-only or read-write transaction implies a read-lock on
71972 ** page 1. So if some other shared-cache client already has a write-lock
71977 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
71978 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
71980 sqlite3PagerWalDb(pPager, p->db);
71985 if( pBt->pPage1==0 && wrflag ){
71986 assert( pBt->inTransaction==TRANS_NONE );
71992 /* Call lockBtree() until either pBt->pPage1 is populated or
71994 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
71995 ** reading page 1 it discovers that the page-size of the database
71996 ** file is not pBt->pageSize. In this case lockBtree() will update
71997 ** pBt->pageSize to the page-size of the file on disk.
71999 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
72002 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
72005 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
72008 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
72021 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
72029 if( p->inTrans==TRANS_NONE ){
72030 pBt->nTransaction++;
72032 if( p->sharable ){
72033 assert( p->lock.pBtree==p && p->lock.iTable==1 );
72034 p->lock.eLock = READ_LOCK;
72035 p->lock.pNext = pBt->pLock;
72036 pBt->pLock = &p->lock;
72040 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
72041 if( p->inTrans>pBt->inTransaction ){
72042 pBt->inTransaction = p->inTrans;
72045 MemPage *pPage1 = pBt->pPage1;
72047 assert( !pBt->pWriter );
72048 pBt->pWriter = p;
72049 pBt->btsFlags &= ~BTS_EXCLUSIVE;
72050 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
72053 /* If the db-size header field is incorrect (as it may be if an old
72056 ** re-read the database size from page 1 if a savepoint or transaction
72059 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
72060 rc = sqlite3PagerWrite(pPage1->pDbPage);
72062 put4byte(&pPage1->aData[28], pBt->nPage);
72071 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
72076 ** the sub-journal is not already open, then it will be opened here.
72078 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
72090 ** Set the pointer-map entries for all children of page pPage. Also, if
72098 BtShared *pBt = pPage->pBt;
72099 Pgno pgno = pPage->pgno;
72101 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72102 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
72104 nCell = pPage->nCell;
72111 if( !pPage->leaf ){
72117 if( !pPage->leaf ){
72118 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
72130 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
72133 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
72136 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
72140 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72141 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
72144 if( get4byte(pPage->aData)!=iFrom ){
72147 put4byte(pPage->aData, iTo);
72153 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
72155 nCell = pPage->nCell;
72161 pPage->xParseCell(pPage, pCell, &info);
72163 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
72166 if( iFrom==get4byte(pCell+info.nSize-4) ){
72167 put4byte(pCell+info.nSize-4, iTo);
72172 if( pCell+4 > pPage->aData+pPage->pBt->usableSize ){
72184 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
72187 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
72199 ** the journal needs to be sync()ed before database page pDbPage->pgno
72207 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
72212 Pgno iDbPage = pDbPage->pgno;
72213 Pager *pPager = pBt->pPager;
72218 assert( sqlite3_mutex_held(pBt->mutex) );
72219 assert( pDbPage->pBt==pBt );
72225 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
72229 pDbPage->pgno = iFreePage;
72231 /* If pDbPage was a btree-page, then it may have child pages and/or cells
72245 Pgno nextOvfl = get4byte(pDbPage->aData);
72263 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
72281 ** Perform a single step of an incremental-vacuum. If successful, return
72286 ** More specifically, this function attempts to re-organize the database so
72292 ** If the bCommit parameter is non-zero, this function assumes that the
72294 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
72298 Pgno nFreeList; /* Number of pages still on the free-list */
72301 assert( sqlite3_mutex_held(pBt->mutex) );
72308 nFreeList = get4byte(&pBt->pPage1->aData[36]);
72323 /* Remove the page from the files free-list. This is not required
72324 ** if bCommit is non-zero. In that case, the free-list will be
72352 ** looping until a free-page located within the first nFin pages
72385 iLastPg--;
72387 pBt->bDoTruncate = 1;
72388 pBt->nPage = iLastPg;
72394 ** The database opened by the first argument is an auto-vacuum database
72396 ** size of the database in pages following an auto-vacuum operation.
72403 nEntry = pBt->usableSize/5;
72404 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
72405 nFin = nOrig - nFree - nPtrmap;
72407 nFin--;
72410 nFin--;
72417 ** A write-transaction must be opened before calling this function.
72426 BtShared *pBt = p->pBt;
72429 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
72430 if( !pBt->autoVacuum ){
72434 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
72446 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
72447 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
72459 ** is committed for an auto-vacuum database.
72469 pBt = p->pBt;
72470 pPager = pBt->pPager;
72473 assert( sqlite3_mutex_held(pBt->mutex) );
72475 assert(pBt->autoVacuum);
72476 if( !pBt->incrVacuum ){
72486 ** is either a pointer-map page or the pending-byte page. If one
72492 nFree = get4byte(&pBt->pPage1->aData[36]);
72493 db = p->db;
72494 if( db->xAutovacPages ){
72496 for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
72497 if( db->aDb[iDb].pBt==p ) break;
72499 nVac = db->xAutovacPages(
72500 db->pAutovacPagesArg,
72501 db->aDb[iDb].zDbSName,
72504 pBt->pageSize
72520 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
72524 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
72526 put4byte(&pBt->pPage1->aData[32], 0);
72527 put4byte(&pBt->pPage1->aData[36], 0);
72529 put4byte(&pBt->pPage1->aData[28], nFin);
72530 pBt->bDoTruncate = 1;
72531 pBt->nPage = nFin;
72547 ** This routine does the first phase of a two-phase commit. This routine
72559 ** This call is a no-op if no write-transaction is currently active on pBt.
72562 ** the name of a super-journal file that should be written into the
72563 ** individual journal file, or is NULL, indicating no super-journal file
72566 ** When this is called, the super-journal should already have been
72570 ** the write-transaction for this database file is to delete the journal.
72574 if( p->inTrans==TRANS_WRITE ){
72575 BtShared *pBt = p->pBt;
72578 if( pBt->autoVacuum ){
72585 if( pBt->bDoTruncate ){
72586 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
72589 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
72600 BtShared *pBt = p->pBt;
72601 sqlite3 *db = p->db;
72605 pBt->bDoTruncate = 0;
72607 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
72609 ** handle, downgrade to a read-only transaction. The other statements
72612 p->inTrans = TRANS_READ;
72618 if( p->inTrans!=TRANS_NONE ){
72620 pBt->nTransaction--;
72621 if( 0==pBt->nTransaction ){
72622 pBt->inTransaction = TRANS_NONE;
72628 p->inTrans = TRANS_NONE;
72638 ** This routine implements the second phase of a 2-phase commit. The
72650 ** is non-zero then this b-tree transaction is part of a multi-file
72652 ** (by deleting a super-journal file) and the caller will ignore this
72654 ** reset the b-tree objects internal state to indicate that the write
72663 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
72667 /* If the handle has a write-transaction open, commit the shared-btrees
72670 if( p->inTrans==TRANS_WRITE ){
72672 BtShared *pBt = p->pBt;
72673 assert( pBt->inTransaction==TRANS_WRITE );
72674 assert( pBt->nTransaction>0 );
72675 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
72680 p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */
72681 pBt->inTransaction = TRANS_READ;
72715 ** flag is true, then only write-cursors need be tripped - read-only
72719 ** rolled back modified the database schema. In this case b-tree root
72724 ** saving the current position of a read-only cursor, all cursors,
72725 ** including all read-cursors are tripped.
72737 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
72738 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
72739 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
72748 p->eState = CURSOR_FAULT;
72749 p->skipNext = errCode;
72759 ** Set the pBt->nPage field correctly, according to the current
72760 ** state of the database. Assume pBt->pPage1 is valid.
72763 int nPage = get4byte(&pPage1->aData[28]);
72765 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
72766 testcase( pBt->nPage!=(u32)nPage );
72767 pBt->nPage = nPage;
72783 BtShared *pBt = p->pBt;
72802 if( p->inTrans==TRANS_WRITE ){
72805 assert( TRANS_WRITE==pBt->inTransaction );
72806 rc2 = sqlite3PagerRollback(pBt->pPager);
72811 /* The rollback may have destroyed the pPage1->aData value. So
72813 ** sure pPage1->aData is set correctly. */
72819 pBt->inTransaction = TRANS_READ;
72839 ** A statement sub-transaction is implemented as an anonymous savepoint. The
72841 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
72842 ** are no active savepoints and no other statement-transactions open,
72848 BtShared *pBt = p->pBt;
72850 assert( p->inTrans==TRANS_WRITE );
72851 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
72853 assert( iStatement>p->db->nSavepoint );
72854 assert( pBt->inTransaction==TRANS_WRITE );
72860 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
72872 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
72879 if( p && p->inTrans==TRANS_WRITE ){
72880 BtShared *pBt = p->pBt;
72882 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
72888 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
72891 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
72892 pBt->nPage = 0;
72895 btreeSetNPage(pBt, pBt->pPage1);
72897 /* pBt->nPage might be zero if the database was corrupt when
72899 assert( CORRUPT_DB || pBt->nPage>0 );
72908 ** iTable. If a read-only cursor is requested, it is assumed that
72909 ** the caller already has at least a read-only transaction open
72910 ** on the database already. If a write-cursor is requested, then
72927 ** 3: The database must be writable (not on read-only media)
72938 ** operations on this cursor can be no-ops and all READ operations can
72939 ** return a null row (2-bytes: 0x01 0x00).
72942 ** root page of a b-tree. If it is not, then the cursor acquired
72951 int wrFlag, /* 1 to write. 0 read-only */
72955 BtShared *pBt = p->pBt; /* Shared b-tree handle */
72965 ** b-tree database, the connection is holding the required table locks,
72973 assert( p->inTrans>TRANS_NONE );
72974 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
72975 assert( pBt->pPage1 && pBt->pPage1->aData );
72976 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
72989 pCur->pgnoRoot = iTable;
72990 pCur->iPage = -1;
72991 pCur->pKeyInfo = pKeyInfo;
72992 pCur->pBtree = p;
72993 pCur->pBt = pBt;
72994 pCur->curFlags = 0;
72997 for(pX=pBt->pCursor; pX; pX=pX->pNext){
72998 if( pX->pgnoRoot==iTable ){
72999 pX->curFlags |= BTCF_Multiple;
73000 pCur->curFlags = BTCF_Multiple;
73003 pCur->eState = CURSOR_INVALID;
73004 pCur->pNext = pBt->pCursor;
73005 pBt->pCursor = pCur;
73007 pCur->curFlags |= BTCF_WriteFlag;
73008 pCur->curPagerFlags = 0;
73009 if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt);
73011 pCur->curPagerFlags = PAGER_GET_READONLY;
73018 int wrFlag, /* 1 to write. 0 read-only */
73031 int wrFlag, /* 1 to write. 0 read-only */
73035 if( p->sharable ){
73047 ** to users so they cannot do the sizeof() themselves - they must call
73060 ** of run-time by skipping the initialization of those elements.
73071 Btree *pBtree = pCur->pBtree;
73073 BtShared *pBt = pCur->pBt;
73075 assert( pBt->pCursor!=0 );
73076 if( pBt->pCursor==pCur ){
73077 pBt->pCursor = pCur->pNext;
73079 BtCursor *pPrev = pBt->pCursor;
73081 if( pPrev->pNext==pCur ){
73082 pPrev->pNext = pCur->pNext;
73085 pPrev = pPrev->pNext;
73090 sqlite3_free(pCur->aOverflow);
73091 sqlite3_free(pCur->pKey);
73092 if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
73095 assert( pBtree->sharable==0 );
73100 pCur->pBtree = 0;
73115 if( a->nKey!=b->nKey ) return 0;
73116 if( a->pPayload!=b->pPayload ) return 0;
73117 if( a->nPayload!=b->nPayload ) return 0;
73118 if( a->nLocal!=b->nLocal ) return 0;
73119 if( a->nSize!=b->nSize ) return 0;
73125 btreeParseCell(pCur->pPage, pCur->ix, &info);
73126 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
73132 if( pCur->info.nSize==0 ){
73133 pCur->curFlags |= BTCF_ValidNKey;
73134 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
73143 ** that is currently pointing to a row in a (non-empty) table.
73147 return pCur && pCur->eState==CURSOR_VALID;
73152 return pCur->eState==CURSOR_VALID;
73163 assert( pCur->eState==CURSOR_VALID );
73164 assert( pCur->curIntKey );
73166 return pCur->info.nKey;
73173 assert( (pCur->curFlags & BTCF_Pinned)==0 );
73174 pCur->curFlags |= BTCF_Pinned;
73177 assert( (pCur->curFlags & BTCF_Pinned)!=0 );
73178 pCur->curFlags &= ~BTCF_Pinned;
73188 assert( pCur->eState==CURSOR_VALID );
73190 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
73191 (i64)(pCur->info.pPayload - pCur->pPage->aData);
73200 ** The caller must guarantee that the cursor is pointing to a non-NULL
73206 assert( pCur->eState==CURSOR_VALID );
73208 return pCur->info.nPayload;
73226 assert( pCur->eState==CURSOR_VALID );
73227 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
73233 ** linked list of overflow pages. If possible, it uses the auto-vacuum
73234 ** pointer-map data instead of reading the content of page ovfl to do so.
73246 ** the pointer-map was used to obtain the value for *pPgnoNext), then
73259 assert( sqlite3_mutex_held(pBt->mutex) );
73264 ** autovacuum pointer-map pages. Guess that the next page in
73269 if( pBt->autoVacuum ){
73293 next = get4byte(pPage->aData);
73321 int eOp, /* 0 -> copy from page, 1 -> copy to page */
73354 ** the overflow page-list cache array (BtCursor.aOverflow).
73358 ** Once an overflow page-list cache has been allocated, it must be
73360 ** the cursor is moved to a different row. Additionally, in auto-vacuum
73361 ** mode, the following events may invalidate an overflow page-list cache.
73372 int eOp /* zero to read. non-zero to write. */
73377 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
73378 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
73385 assert( pCur->eState==CURSOR_VALID );
73386 if( pCur->ix>=pPage->nCell ){
73392 aPayload = pCur->info.pPayload;
73393 assert( offset+amt <= pCur->info.nPayload );
73395 assert( aPayload > pPage->aData );
73396 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
73399 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
73406 if( offset<pCur->info.nLocal ){
73408 if( a+offset>pCur->info.nLocal ){
73409 a = pCur->info.nLocal - offset;
73411 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
73414 amt -= a;
73416 offset -= pCur->info.nLocal;
73421 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
73424 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
73433 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
73434 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
73435 if( pCur->aOverflow==0
73436 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
73439 pCur->aOverflow, nOvfl*2*sizeof(Pgno)
73444 pCur->aOverflow = aNew;
73447 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
73448 pCur->curFlags |= BTCF_ValidOvfl;
73450 /* If the overflow page-list cache has been allocated and the
73454 if( pCur->aOverflow[offset/ovflSize] ){
73456 nextPage = pCur->aOverflow[iIdx];
73463 /* If required, populate the overflow page-list cache. */
73464 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
73465 assert( pCur->aOverflow[iIdx]==0
73466 || pCur->aOverflow[iIdx]==nextPage
73468 pCur->aOverflow[iIdx] = nextPage;
73474 ** page-list cache, if any, then fall back to the getOverflowPage()
73477 assert( pCur->curFlags & BTCF_ValidOvfl );
73478 assert( pCur->pBtree->db==pBt->db );
73479 if( pCur->aOverflow[iIdx+1] ){
73480 nextPage = pCur->aOverflow[iIdx+1];
73484 offset -= ovflSize;
73491 a = ovflSize - offset;
73499 ** 3) there are no dirty pages in the page-cache
73500 ** 4) the database is file-backed, and
73505 ** output buffer, bypassing the page-cache altogether. This speeds
73510 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
73511 && &pBuf[-4]>=pBufStart /* (6) */
73513 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
73515 u8 *aWrite = &pBuf[-4];
73518 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
73519 if( rc && nextPage>pBt->nPage ) rc = SQLITE_CORRUPT_BKPT;
73527 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
73538 amt -= a;
73559 ** pCur can be pointing to either a table or an index b-tree.
73561 ** pCur is pointing to an index b-tree then the key section is read.
73573 assert( pCur->eState==CURSOR_VALID );
73574 assert( pCur->iPage>=0 && pCur->pPage );
73591 if ( pCur->eState==CURSOR_INVALID ){
73599 if( pCur->eState==CURSOR_VALID ){
73611 ** the key if index btrees (pPage->intKey==0) and is the data for
73612 ** table btrees (pPage->intKey==1). The number of bytes of available
73632 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
73633 assert( pCur->eState==CURSOR_VALID );
73634 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
73636 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
73637 assert( pCur->info.nSize>0 );
73638 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
73639 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
73640 amt = pCur->info.nLocal;
73641 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
73645 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
73648 return (void*)pCur->info.pPayload;
73655 ** b-tree page. Write the number of available bytes into *pAmt.
73675 ** This function returns SQLITE_CORRUPT if the page-header flags field of
73677 ** if an intkey page appears to be the parent of a non-intkey page, or
73678 ** vice-versa).
73682 assert( pCur->eState==CURSOR_VALID );
73683 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
73684 assert( pCur->iPage>=0 );
73685 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
73688 pCur->info.nSize = 0;
73689 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
73690 pCur->aiIdx[pCur->iPage] = pCur->ix;
73691 pCur->apPage[pCur->iPage] = pCur->pPage;
73692 pCur->ix = 0;
73693 pCur->iPage++;
73694 return getAndInitPage(pCur->pBt, newPgno, &pCur->pPage, pCur,
73695 pCur->curPagerFlags);
73700 ** Page pParent is an internal (non-leaf) tree page. This function
73701 ** asserts that page number iChild is the left-child if the iIdx'th
73703 ** cells in pParent, that page number iChild is the right-child of
73709 assert( iIdx<=pParent->nCell );
73710 if( iIdx==pParent->nCell ){
73711 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
73723 ** pCur->idx is set to the cell index that contains the pointer
73725 ** right-most child page then pCur->idx is set to one more than
73731 assert( pCur->eState==CURSOR_VALID );
73732 assert( pCur->iPage>0 );
73733 assert( pCur->pPage );
73735 pCur->apPage[pCur->iPage-1],
73736 pCur->aiIdx[pCur->iPage-1],
73737 pCur->pPage->pgno
73739 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
73740 pCur->info.nSize = 0;
73741 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
73742 pCur->ix = pCur->aiIdx[pCur->iPage-1];
73743 pLeaf = pCur->pPage;
73744 pCur->pPage = pCur->apPage[--pCur->iPage];
73749 ** Move the cursor to point to the root page of its b-tree structure.
73756 ** If the b-tree structure is empty, the cursor state is set to
73762 ** page-header flags indicate that the [virtual] root-page is the expected
73763 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
73765 ** indicating a table b-tree, or if the caller did specify a KeyInfo
73767 ** b-tree).
73777 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
73778 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
73780 if( pCur->iPage>=0 ){
73781 if( pCur->iPage ){
73782 releasePageNotNull(pCur->pPage);
73783 while( --pCur->iPage ){
73784 releasePageNotNull(pCur->apPage[pCur->iPage]);
73786 pRoot = pCur->pPage = pCur->apPage[0];
73789 }else if( pCur->pgnoRoot==0 ){
73790 pCur->eState = CURSOR_INVALID;
73793 assert( pCur->iPage==(-1) );
73794 if( pCur->eState>=CURSOR_REQUIRESEEK ){
73795 if( pCur->eState==CURSOR_FAULT ){
73796 assert( pCur->skipNext!=SQLITE_OK );
73797 return pCur->skipNext;
73801 rc = getAndInitPage(pCur->pBt, pCur->pgnoRoot, &pCur->pPage,
73802 0, pCur->curPagerFlags);
73804 pCur->eState = CURSOR_INVALID;
73807 pCur->iPage = 0;
73808 pCur->curIntKey = pCur->pPage->intKey;
73810 pRoot = pCur->pPage;
73811 assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB );
73813 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
73814 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
73815 ** NULL, the caller expects a table b-tree. If this is not the case,
73820 ** if pCur->iPage>=0). But this is not so if the database is corrupted
73821 ** in such a way that page pRoot is linked into a second b-tree table
73823 assert( pRoot->intKey==1 || pRoot->intKey==0 );
73824 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
73825 return SQLITE_CORRUPT_PAGE(pCur->pPage);
73829 pCur->ix = 0;
73830 pCur->info.nSize = 0;
73831 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
73833 if( pRoot->nCell>0 ){
73834 pCur->eState = CURSOR_VALID;
73835 }else if( !pRoot->leaf ){
73837 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
73838 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
73839 pCur->eState = CURSOR_VALID;
73842 pCur->eState = CURSOR_INVALID;
73849 ** Move the cursor down to the left-most leaf entry beneath the
73852 ** The left-most leaf is the one with the smallest key - the first
73861 assert( pCur->eState==CURSOR_VALID );
73862 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
73863 assert( pCur->ix<pPage->nCell );
73864 pgno = get4byte(findCell(pPage, pCur->ix));
73871 ** Move the cursor down to the right-most leaf entry beneath the
73874 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
73875 ** finds the right-most entry beneath the *page*.
73877 ** The right-most entry is the one with the largest key - the last
73886 assert( pCur->eState==CURSOR_VALID );
73887 while( !(pPage = pCur->pPage)->leaf ){
73888 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
73889 pCur->ix = pPage->nCell;
73893 pCur->ix = pPage->nCell-1;
73894 assert( pCur->info.nSize==0 );
73895 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
73907 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
73910 assert( pCur->pPage->nCell>0 );
73914 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
73929 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
73931 /* If the cursor already points to the last entry, this is a no-op. */
73932 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
73935 ** to the last entry in the b-tree. */
73937 for(ii=0; ii<pCur->iPage; ii++){
73938 assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
73940 assert( pCur->ix==pCur->pPage->nCell-1 || CORRUPT_DB );
73941 testcase( pCur->ix!=pCur->pPage->nCell-1 );
73942 /* ^-- dbsqlfuzz b92b72e4de80b5140c30ab71372ca719b8feb618 */
73943 assert( pCur->pPage->leaf );
73951 assert( pCur->eState==CURSOR_VALID );
73955 pCur->curFlags |= BTCF_AtLast;
73957 pCur->curFlags &= ~BTCF_AtLast;
73960 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
73999 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
74001 assert( pCur->pKeyInfo==0 );
74002 assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
74006 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
74007 if( pCur->info.nKey==intKey ){
74011 if( pCur->info.nKey<intKey ){
74012 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
74013 *pRes = -1;
74020 if( pCur->info.nKey+1==intKey ){
74025 if( pCur->info.nKey==intKey ){
74036 pCur->pBtree->nSeek++; /* Performance measurement during testing */
74042 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
74043 *pRes = -1;
74048 assert( pCur->pPage );
74049 assert( pCur->pPage->isInit );
74050 assert( pCur->eState==CURSOR_VALID );
74051 assert( pCur->pPage->nCell > 0 );
74052 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
74053 assert( pCur->curIntKey );
74058 MemPage *pPage = pCur->pPage;
74061 /* pPage->nCell must be greater than zero. If this is the root-page
74063 ** not run. If this is not the root-page, then the moveToChild() routine
74065 ** be the right kind (index or table) of b-tree page. Otherwise
74067 assert( pPage->nCell>0 );
74068 assert( pPage->intKey );
74070 upr = pPage->nCell-1;
74072 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
74076 if( pPage->intKeyLeaf ){
74078 if( pCell>=pPage->aDataEnd ){
74086 if( lwr>upr ){ c = -1; break; }
74088 upr = idx-1;
74092 pCur->ix = (u16)idx;
74093 if( !pPage->leaf ){
74097 pCur->curFlags |= BTCF_ValidNKey;
74098 pCur->info.nKey = nCellKey;
74099 pCur->info.nSize = 0;
74107 assert( lwr==upr+1 || !pPage->leaf );
74108 assert( pPage->isInit );
74109 if( pPage->leaf ){
74110 assert( pCur->ix<pCur->pPage->nCell );
74111 pCur->ix = (u16)idx;
74117 if( lwr>=pPage->nCell ){
74118 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
74122 pCur->ix = (u16)lwr;
74127 pCur->info.nSize = 0;
74128 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
74133 ** Compare the "idx"-th cell on the page the cursor pCur is currently
74154 MemPage *pPage = pCur->pPage;
74160 if( nCell<=pPage->max1bytePayload ){
74161 /* This branch runs if the record-size field of the cell is a
74163 ** b-tree page. */
74164 testcase( pCell+nCell+1==pPage->aDataEnd );
74167 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
74169 /* The record-size field is a 2 byte varint and the record
74170 ** fits entirely on the main b-tree page. */
74171 testcase( pCell+nCell+2==pPage->aDataEnd );
74182 ** Return true (non-zero) if pCur is current pointing to the last
74187 assert( pCur->eState==CURSOR_VALID );
74188 for(i=0; i<pCur->iPage; i++){
74189 MemPage *pPage = pCur->apPage[i];
74190 if( pCur->aiIdx[i]<pPage->nCell ) return 0;
74218 ** The pIdxKey->eqSeen field is set to 1 if there
74230 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
74232 assert( pCur->pKeyInfo!=0 );
74235 pCur->pBtree->nSeek++; /* Performance measurement during testing */
74239 pIdxKey->errCode = 0;
74240 assert( pIdxKey->default_rc==1
74241 || pIdxKey->default_rc==0
74242 || pIdxKey->default_rc==-1
74257 if( pCur->eState==CURSOR_VALID
74258 && pCur->pPage->leaf
74262 if( pCur->ix==pCur->pPage->nCell-1
74263 && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0
74264 && pIdxKey->errCode==SQLITE_OK
74269 if( pCur->iPage>0
74271 && pIdxKey->errCode==SQLITE_OK
74273 pCur->curFlags &= ~BTCF_ValidOvfl;
74274 if( !pCur->pPage->isInit ){
74279 pIdxKey->errCode = SQLITE_OK;
74285 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
74286 *pRes = -1;
74293 assert( pCur->pPage );
74294 assert( pCur->pPage->isInit );
74295 assert( pCur->eState==CURSOR_VALID );
74296 assert( pCur->pPage->nCell > 0 );
74297 assert( pCur->curIntKey==0 );
74302 MemPage *pPage = pCur->pPage;
74305 /* pPage->nCell must be greater than zero. If this is the root-page
74307 ** not run. If this is not the root-page, then the moveToChild() routine
74309 ** be the right kind (index or table) of b-tree page. Otherwise
74311 assert( pPage->nCell>0 );
74312 assert( pPage->intKey==0 );
74314 upr = pPage->nCell-1;
74320 /* The maximum supported page-size is 65536 bytes. This means that
74321 ** the maximum number of record bytes stored on an index B-Tree
74322 ** page is less than 16384 bytes and may be stored as a 2-byte
74325 ** stored entirely within the b-tree page by inspecting the first
74329 if( nCell<=pPage->max1bytePayload ){
74330 /* This branch runs if the record-size field of the cell is a
74332 ** b-tree page. */
74333 testcase( pCell+nCell+1==pPage->aDataEnd );
74336 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
74338 /* The record-size field is a 2 byte varint and the record
74339 ** fits entirely on the main b-tree page. */
74340 testcase( pCell+nCell+2==pPage->aDataEnd );
74353 u8 * const pCellBody = pCell - pPage->childPtrSize;
74355 pPage->xParseCell(pPage, pCellBody, &pCur->info);
74356 nCell = (int)pCur->info.nKey;
74361 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
74370 pCur->ix = (u16)idx;
74373 pCur->curFlags &= ~BTCF_ValidOvfl;
74382 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
74383 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
74388 upr = idx-1;
74393 pCur->ix = (u16)idx;
74394 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
74401 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
74402 assert( pPage->isInit );
74403 if( pPage->leaf ){
74404 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
74405 pCur->ix = (u16)idx;
74410 if( lwr>=pPage->nCell ){
74411 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
74415 pCur->ix = (u16)lwr;
74420 pCur->info.nSize = 0;
74421 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
74438 return (CURSOR_VALID!=pCur->eState);
74451 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
74456 if( NEVER(pCur->eState!=CURSOR_VALID) ) return -1;
74457 if( NEVER(pCur->pPage->leaf==0) ) return -1;
74459 n = pCur->pPage->nCell;
74460 for(i=0; i<pCur->iPage; i++){
74461 n *= pCur->apPage[i]->nCell;
74492 if( pCur->eState!=CURSOR_VALID ){
74493 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
74498 if( CURSOR_INVALID==pCur->eState ){
74501 if( pCur->eState==CURSOR_SKIPNEXT ){
74502 pCur->eState = CURSOR_VALID;
74503 if( pCur->skipNext>0 ) return SQLITE_OK;
74507 pPage = pCur->pPage;
74508 idx = ++pCur->ix;
74509 if( NEVER(!pPage->isInit) || sqlite3FaultSim(412) ){
74513 if( idx>=pPage->nCell ){
74514 if( !pPage->leaf ){
74515 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
74520 if( pCur->iPage==0 ){
74521 pCur->eState = CURSOR_INVALID;
74525 pPage = pCur->pPage;
74526 }while( pCur->ix>=pPage->nCell );
74527 if( pPage->intKey ){
74533 if( pPage->leaf ){
74544 pCur->info.nSize = 0;
74545 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
74546 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
74547 pPage = pCur->pPage;
74548 if( (++pCur->ix)>=pPage->nCell ){
74549 pCur->ix--;
74552 if( pPage->leaf ){
74584 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
74585 assert( pCur->info.nSize==0 );
74586 if( pCur->eState!=CURSOR_VALID ){
74591 if( CURSOR_INVALID==pCur->eState ){
74594 if( CURSOR_SKIPNEXT==pCur->eState ){
74595 pCur->eState = CURSOR_VALID;
74596 if( pCur->skipNext<0 ) return SQLITE_OK;
74600 pPage = pCur->pPage;
74601 assert( pPage->isInit );
74602 if( !pPage->leaf ){
74603 int idx = pCur->ix;
74608 while( pCur->ix==0 ){
74609 if( pCur->iPage==0 ){
74610 pCur->eState = CURSOR_INVALID;
74615 assert( pCur->info.nSize==0 );
74616 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
74618 pCur->ix--;
74619 pPage = pCur->pPage;
74620 if( pPage->intKey && !pPage->leaf ){
74632 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
74633 pCur->info.nSize = 0;
74634 if( pCur->eState!=CURSOR_VALID
74635 || pCur->ix==0
74636 || pCur->pPage->leaf==0
74640 pCur->ix--;
74661 ** anywhere on the free-list, then it is guaranteed to be returned. If
74681 assert( sqlite3_mutex_held(pBt->mutex) );
74682 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
74683 pPage1 = pBt->pPage1;
74685 /* EVIDENCE-OF: R-21003-45125 The 4-byte big-endian integer at offset 36
74687 n = get4byte(&pPage1->aData[36]);
74688 testcase( n==mxPage-1 );
74695 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
74698 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
74699 ** shows that the page 'nearby' is somewhere on the free-list, then
74700 ** the entire-list will be searched for that page.
74707 assert( pBt->autoVacuum );
74719 /* Decrement the free-list count by 1. Set iTrunk to the index of the
74720 ** first free-list trunk page. iPrevTrunk is initially 1.
74722 rc = sqlite3PagerWrite(pPage1->pDbPage);
74724 put4byte(&pPage1->aData[36], n-1);
74727 ** is not true. Otherwise, it runs once for each trunk-page on the
74728 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
74734 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
74737 iTrunk = get4byte(&pPrevTrunk->aData[0]);
74739 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
74742 iTrunk = get4byte(&pPage1->aData[32]);
74746 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
74755 assert( pTrunk->aData!=0 );
74756 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
74758 k = get4byte(&pTrunk->aData[4]);
74764 rc = sqlite3PagerWrite(pTrunk->pDbPage);
74769 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
74772 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
74773 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
74787 rc = sqlite3PagerWrite(pTrunk->pDbPage);
74793 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
74795 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
74799 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
74803 ** pointers to free-list leaves. The first leaf becomes a trunk
74807 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
74817 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
74822 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
74823 put4byte(&pNewTrunk->aData[4], k-1);
74824 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
74827 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
74828 put4byte(&pPage1->aData[32], iNewTrunk);
74830 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
74834 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
74838 TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
74844 unsigned char *aData = pTrunk->aData;
74858 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
74860 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
74885 *pPgno, closest+1, k, pTrunk->pgno, n-1));
74886 rc = sqlite3PagerWrite(pTrunk->pDbPage);
74888 if( closest<k-1 ){
74891 put4byte(&aData[4], k-1);
74895 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
74912 ** pager layer with the 'no-content' flag set. This prevents the pager
74914 ** current transaction has already run one or more incremental-vacuum
74917 ** not set the no-content flag. This causes the pager to load and journal
74922 ** file on disk. So the effects of disabling the no-content optimization
74926 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
74928 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
74930 pBt->nPage++;
74931 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
74934 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
74935 /* If *pPgno refers to a pointer-map page, allocate two new pages
74937 ** becomes a new pointer-map page, the second is used by the caller.
74940 TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
74941 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
74942 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
74944 rc = sqlite3PagerWrite(pPg->pDbPage);
74948 pBt->nPage++;
74949 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
74952 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
74953 *pPgno = pBt->nPage;
74958 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
74971 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
74972 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
74977 ** This function is used to add page iPage to the database file free-list.
74978 ** It is assumed that the page is not already a part of the free-list.
74989 MemPage *pTrunk = 0; /* Free-list trunk page */
74990 Pgno iTrunk = 0; /* Page number of free-list trunk page */
74991 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
74994 u32 nFree; /* Initial number of pages on free-list */
74996 assert( sqlite3_mutex_held(pBt->mutex) );
74998 assert( !pMemPage || pMemPage->pgno==iPage );
75000 if( iPage<2 || iPage>pBt->nPage ){
75005 sqlite3PagerRef(pPage->pDbPage);
75011 rc = sqlite3PagerWrite(pPage1->pDbPage);
75013 nFree = get4byte(&pPage1->aData[36]);
75014 put4byte(&pPage1->aData[36], nFree+1);
75016 if( pBt->btsFlags & BTS_SECURE_DELETE ){
75021 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
75025 memset(pPage->aData, 0, pPage->pBt->pageSize);
75028 /* If the database supports auto-vacuum, write an entry in the pointer-map
75036 /* Now manipulate the actual database free-list structure. There are two
75037 ** possibilities. If the free-list is currently empty, or if the first
75038 ** trunk page in the free-list is full, then this page will become a
75039 ** new free-list trunk page. Otherwise, it will become a leaf of the
75040 ** first trunk page in the current free-list. This block tests if it
75041 ** is possible to add the page as a new free-list leaf.
75046 iTrunk = get4byte(&pPage1->aData[32]);
75056 nLeaf = get4byte(&pTrunk->aData[4]);
75057 assert( pBt->usableSize>32 );
75058 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
75062 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
75067 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
75070 ** usableSize/4 - 8 entries will be reported as corrupt. In order
75072 ** we will continue to restrict the number of entries to usableSize/4 - 8
75075 ** to read "usableSize/4-2" instead of "usableSize/4-8".
75077 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
75082 rc = sqlite3PagerWrite(pTrunk->pDbPage);
75084 put4byte(&pTrunk->aData[4], nLeaf+1);
75085 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
75086 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
75087 sqlite3PagerDontWrite(pPage->pDbPage);
75091 TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
75097 ** the page being freed as a leaf page of the first trunk in the free-list.
75098 ** Possibly because the free-list is empty, or possibly because the
75099 ** first trunk in the free-list is full. Either way, the page being freed
75100 ** will become the new first trunk page in the free-list.
75105 rc = sqlite3PagerWrite(pPage->pDbPage);
75109 put4byte(pPage->aData, iTrunk);
75110 put4byte(&pPage->aData[4], 0);
75111 put4byte(&pPage1->aData[32], iPage);
75112 TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
75116 pPage->isInit = 0;
75124 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
75142 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
75143 assert( pInfo->nLocal!=pInfo->nPayload );
75144 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
75145 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
75146 if( pCell + pInfo->nSize > pPage->aDataEnd ){
75150 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
75151 pBt = pPage->pBt;
75152 assert( pBt->usableSize > 4 );
75153 ovflPageSize = pBt->usableSize - 4;
75154 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
75156 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
75158 while( nOvfl-- ){
75173 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
75180 ** freePage2() may zero the page contents if secure-delete mode is
75191 sqlite3PagerUnref(pOvfl->pDbPage);
75206 pPage->xParseCell(pPage, pCell, &sInfo); \
75221 ** Note that pCell does not necessary need to point to the pPage->aData
75223 ** be constructed in this temporary area then copied into pPage->aData
75243 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
75247 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
75248 || sqlite3PagerIswriteable(pPage->pDbPage) );
75251 nHeader = pPage->childPtrSize;
75252 if( pPage->intKey ){
75253 nPayload = pX->nData + pX->nZero;
75254 pSrc = pX->pData;
75255 nSrc = pX->nData;
75256 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
75258 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
75260 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
75261 nSrc = nPayload = (int)pX->nKey;
75262 pSrc = pX->pKey;
75268 if( nPayload<=pPage->maxLocal ){
75279 memset(pPayload+nSrc, 0, nPayload-nSrc);
75286 mn = pPage->minLocal;
75287 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
75288 testcase( n==pPage->maxLocal );
75289 testcase( n==pPage->maxLocal+1 );
75290 if( n > pPage->maxLocal ) n = mn;
75296 pBt = pPage->pBt;
75313 pPage->xParseCell(pPage, pCell, &info);
75314 assert( nHeader==(int)(info.pPayload - pCell) );
75315 assert( info.nKey==pX->nKey );
75328 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
75332 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
75333 || sqlite3PagerIswriteable(pPage->pDbPage) );
75343 nPayload -= n;
75347 nSrc -= n;
75348 spaceLeft -= n;
75352 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
75353 if( pBt->autoVacuum ){
75363 /* If the database supports auto-vacuum, and the second or subsequent
75364 ** overflow page is being allocated, add an entry to the pointer-map
75368 ** to the pointer-map. If we write nothing to this pointer-map slot,
75373 if( pBt->autoVacuum && rc==SQLITE_OK ){
75388 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
75392 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
75393 || sqlite3PagerIswriteable(pPage->pDbPage) );
75398 pPrior = pOvfl->aData;
75400 pPayload = &pOvfl->aData[4];
75401 spaceLeft = pBt->usableSize - 4;
75409 ** Remove the i-th cell from pPage. This routine effects pPage only.
75418 u8 *data; /* pPage->aData */
75425 assert( idx<pPage->nCell );
75427 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
75428 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
75429 assert( pPage->nFree>=0 );
75430 data = pPage->aData;
75431 ptr = &pPage->aCellIdx[2*idx];
75432 assert( pPage->pBt->usableSize > (u32)(ptr-data) );
75434 hdr = pPage->hdrOffset;
75436 testcase( pc+sz==pPage->pBt->usableSize );
75437 if( pc+sz > pPage->pBt->usableSize ){
75446 pPage->nCell--;
75447 if( pPage->nCell==0 ){
75450 put2byte(&data[hdr+5], pPage->pBt->usableSize);
75451 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
75452 - pPage->childPtrSize - 8;
75454 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
75455 put2byte(&data[hdr+3], pPage->nCell);
75456 pPage->nFree += 2;
75467 ** in pPage->apOvfl[] and make it point to the cell content (either
75469 ** Allocating a new entry in pPage->aCell[] implies that
75470 ** pPage->nOverflow is incremented.
75476 int i, /* New cell becomes the i-th cell of the page */
75480 Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
75486 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
75489 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
75490 assert( MX_CELL(pPage->pBt)<=10921 );
75491 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
75492 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
75493 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
75494 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
75495 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
75496 assert( pPage->nFree>=0 );
75497 if( pPage->nOverflow || sz+2>pPage->nFree ){
75505 j = pPage->nOverflow++;
75506 /* Comparison against ArraySize-1 since we hold back one extra slot
75509 assert( j < ArraySize(pPage->apOvfl)-1 );
75510 pPage->apOvfl[j] = pCell;
75511 pPage->aiOvfl[j] = (u16)i;
75518 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
75519 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
75521 int rc = sqlite3PagerWrite(pPage->pDbPage);
75526 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
75527 data = pPage->aData;
75528 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
75534 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
75535 assert( idx+sz <= (int)pPage->pBt->usableSize );
75536 pPage->nFree -= (u16)(2 + sz);
75541 ** the source page. Make sure this does not cause problems by not
75543 memcpy(&data[idx+4], pCell+4, sz-4);
75548 pIns = pPage->aCellIdx + i*2;
75549 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
75551 pPage->nCell++;
75553 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
75554 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
75556 if( pPage->pBt->autoVacuum ){
75579 ** tunable - as if you could change them and recompile and it would all work.
75594 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
75606 ** -----------
75608 ** -----------
75611 ** --------- --------- ---------
75612 ** |Child-1| |Child-2| |Child-3|
75613 ** --------- --------- ---------
75617 ** 1. All cells from Child-1 in order
75619 ** 3. All cells from Child-2 in order
75621 ** 5. All cells from Child-3 in order
75623 ** For a table-btree (with rowids) the items 2 and 4 are empty because
75627 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
75631 ** ixNx[0] = Number of cells in Child-1.
75632 ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
75633 ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
75634 ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
75637 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
75640 ** ixNx[0] = Number of cells in Child-1.
75641 ** ixNx[1] = Number of cells in Child-1 and Child-2.
75660 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
75664 assert( idx>=0 && idx+N<=p->nCell );
75666 assert( p->apCell[idx]!=0 );
75667 if( p->szCell[idx]==0 ){
75668 p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
75671 p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
75674 N--;
75682 assert( N>=0 && N<p->nCell );
75683 assert( p->szCell[N]==0 );
75684 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
75685 return p->szCell[N];
75688 assert( N>=0 && N<p->nCell );
75689 if( p->szCell[N] ) return p->szCell[N];
75694 ** Array apCell[] contains pointers to nCell b-tree page cells. The
75712 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
75713 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
75714 const int usableSize = pPg->pBt->usableSize;
75719 u8 *pCellptr = pPg->aCellIdx;
75720 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
75722 int k; /* Current slot in pCArray->apEnd[] */
75723 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
75728 memcpy(&pTmp[j], &aData[j], usableSize - j);
75730 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
75731 pSrcEnd = pCArray->apEnd[k];
75735 u8 *pCell = pCArray->apCell[i];
75736 u16 sz = pCArray->szCell[i];
75740 pCell = &pTmp[pCell - aData];
75747 pData -= sz;
75748 put2byte(pCellptr, (pData - aData));
75752 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
75755 if( pCArray->ixNx[k]<=i ){
75757 pSrcEnd = pCArray->apEnd[k];
75761 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
75762 pPg->nCell = nCell;
75763 pPg->nOverflow = 0;
75766 put2byte(&aData[hdr+3], pPg->nCell);
75767 put2byte(&aData[hdr+5], pData - aData);
75773 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
75776 ** will fit), non-zero is returned. Otherwise, if the cells are added
75779 ** Argument pCellptr points to the first entry in the cell-pointer array
75781 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
75783 ** that it is safe to overwrite this part of the cell-pointer array.
75791 ** end of the space required by this page for the cell-pointer area (for
75792 ** all cells - not just those inserted by the current call). If the content
75794 ** cells in apCell[], then the cells do not fit and non-zero is returned.
75798 u8 *pBegin, /* End of cell-pointer array */
75799 u8 **ppData, /* IN/OUT: Page content-area pointer */
75800 u8 *pCellptr, /* Pointer to cell-pointer area */
75805 int i = iFirst; /* Loop counter - cell index to insert */
75806 u8 *aData = pPg->aData; /* Complete page */
75809 int k; /* Current slot in pCArray->apEnd[] */
75811 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
75813 for(k=0; pCArray->ixNx[k]<=i && ALWAYS(k<NB*2); k++){}
75814 pEnd = pCArray->apEnd[k];
75818 assert( pCArray->szCell[i]!=0 );
75819 sz = pCArray->szCell[i];
75821 if( (pData - pBegin)<sz ) return 1;
75822 pData -= sz;
75825 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
75828 assert( (pSlot+sz)<=pCArray->apCell[i]
75829 || pSlot>=(pCArray->apCell[i]+sz)
75831 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
75832 && (uptr)(pCArray->apCell[i])<(uptr)pEnd
75838 memmove(pSlot, pCArray->apCell[i], sz);
75839 put2byte(pCellptr, (pSlot - aData));
75843 if( pCArray->ixNx[k]<=i ){
75845 pEnd = pCArray->apEnd[k];
75853 ** The pCArray object contains pointers to b-tree cells and their sizes.
75856 ** that is currently stored within the body of pPg to the pPg free-list.
75857 ** The cell-pointers and other fields of the page are not updated.
75859 ** This function returns the total number of cells added to the free-list.
75867 u8 * const aData = pPg->aData;
75868 u8 * const pEnd = &aData[pPg->pBt->usableSize];
75869 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
75877 u8 *pCell = pCArray->apCell[i];
75883 sz = pCArray->szCell[i]; assert( sz>0 );
75886 assert( pFree>aData && (pFree - aData)<65536 );
75887 freeSpace(pPg, (u16)(pFree - aData), szFree);
75902 assert( pFree>aData && (pFree - aData)<65536 );
75903 freeSpace(pPg, (u16)(pFree - aData), szFree);
75910 ** balanced. The current page, pPg, has pPg->nCell cells starting with
75911 ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
75917 ** The pPg->nFree field is invalid when this function returns. It is the
75927 u8 * const aData = pPg->aData;
75928 const int hdr = pPg->hdrOffset;
75929 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
75930 int nCell = pPg->nCell; /* Cells stored on pPg */
75934 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
75938 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
75939 memcpy(pTmp, aData, pPg->pBt->usableSize);
75945 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
75947 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
75948 nCell -= nShift;
75951 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
75953 nCell -= nTail;
75958 if( pData>pPg->aDataEnd ) goto editpage_fail;
75962 int nAdd = MIN(nNew,iOld-iNew);
75963 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
75965 pCellptr = pPg->aCellIdx;
75975 for(i=0; i<pPg->nOverflow; i++){
75976 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
75978 pCellptr = &pPg->aCellIdx[iCell * 2];
75980 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
75993 pCellptr = &pPg->aCellIdx[nCell*2];
75996 iNew+nCell, nNew-nCell, pCArray
75999 pPg->nCell = nNew;
76000 pPg->nOverflow = 0;
76002 put2byte(&aData[hdr+3], pPg->nCell);
76003 put2byte(&aData[hdr+5], pData - aData);
76007 u8 *pCell = pCArray->apCell[i+iNew];
76008 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
76009 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
76010 pCell = &pTmp[pCell - aData];
76013 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
76028 ** a new entry is being inserted on the extreme right-end of the
76032 ** Instead of trying to balance the 3 right-most leaf pages, just add
76033 ** a new page to the right-hand side and put the one new entry in
76039 ** pPage is the leaf page which is the right-most page in the tree.
76041 ** which is also the right-most entry on the page.
76050 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
76055 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
76056 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
76057 assert( pPage->nOverflow==1 );
76059 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
76060 assert( pPage->nFree>=0 );
76061 assert( pParent->nFree>=0 );
76063 /* Allocate a new page. This page will become the right-sibling of
76072 u8 *pCell = pPage->apOvfl[0];
76073 u16 szCell = pPage->xCellSize(pPage, pCell);
76077 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
76078 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
76084 b.apEnd[0] = pPage->aDataEnd;
76091 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
76093 /* If this is an auto-vacuum database, update the pointer map
76103 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
76104 if( szCell>pNew->minLocal ){
76110 ** consists of a 4-byte page number (the page number of pPage) and
76114 ** To find the largest key value on pPage, first find the right-most
76116 ** record-length (a variable length integer at most 32-bits in size)
76118 ** The first of the while(...) loops below skips over the record-length
76122 pCell = findCell(pPage, pPage->nCell-1);
76130 insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
76131 0, pPage->pgno, &rc);
76134 /* Set the right-child pointer of pParent to point to the new page. */
76135 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
76149 ** for setting pointer-map entries.
76157 BtShared *pBt = pPage->pBt;
76158 assert( pPage->isInit );
76160 for(j=0; j<pPage->nCell; j++){
76165 pPage->xParseCell(pPage, z, &info);
76167 Pgno ovfl = get4byte(&z[info.nSize-4]);
76169 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
76171 if( !pPage->leaf ){
76174 assert( n==pPage->pgno && e==PTRMAP_BTREE );
76177 if( !pPage->leaf ){
76178 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
76180 assert( n==pPage->pgno && e==PTRMAP_BTREE );
76188 ** This function is used to copy the contents of the b-tree node stored
76190 ** the pointer-map entries for each child page are updated so that the
76206 BtShared * const pBt = pFrom->pBt;
76207 u8 * const aFrom = pFrom->aData;
76208 u8 * const aTo = pTo->aData;
76209 int const iFromHdr = pFrom->hdrOffset;
76210 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
76215 assert( pFrom->isInit );
76216 assert( pFrom->nFree>=iToHdr );
76217 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
76219 /* Copy the b-tree node content from page pFrom to page pTo. */
76221 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
76222 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
76229 pTo->isInit = 0;
76237 /* If this is an auto-vacuum database, update the pointer-map entries
76238 ** for any b-tree or overflow pages that pTo now contains the pointers to.
76280 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
76289 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
76290 int isRoot, /* True if pParent is a root-page */
76298 int nxDiv; /* Next divider slot in pParent->aCell[] */
76303 int pageFlags; /* Value of pPage->aData[0] */
76309 u8 *pRight; /* Location in parent of right-sibling pointer */
76310 u8 *apDiv[NB-1]; /* Divider cells in pParent */
76311 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
76313 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
76322 pBt = pParent->pBt;
76323 assert( sqlite3_mutex_held(pBt->mutex) );
76324 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
76331 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
76332 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
76337 assert( pParent->nFree>=0 );
76350 i = pParent->nOverflow + pParent->nCell;
76358 nxDiv = i-2+bBulk;
76360 nxDiv = iParentIdx-1;
76362 i = 2-bBulk;
76365 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
76366 pRight = &pParent->aData[pParent->hdrOffset+8];
76368 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
76379 if( apOld[i]->nFree<0 ){
76386 nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
76387 if( (i--)==0 ) break;
76389 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
76390 apDiv[i] = pParent->apOvfl[0];
76392 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
76393 pParent->nOverflow = 0;
76395 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
76397 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
76406 ** But not if we are in secure-delete mode. In secure-delete mode,
76411 if( pBt->btsFlags & BTS_FAST_SECURE ){
76416 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
76417 if( (iOff+szNew[i])<=(int)pBt->usableSize ){
76419 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
76422 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
76426 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
76436 + pBt->pageSize; /* aSpace1 */
76438 assert( szScratch<=7*(int)pBt->pageSize );
76465 leafCorrection = b.pRef->leaf*4;
76466 leafData = b.pRef->intKeyLeaf;
76469 int limit = pOld->nCell;
76470 u8 *aData = pOld->aData;
76471 u16 maskPage = pOld->maskPage;
76472 u8 *piCell = aData + pOld->cellOffset;
76476 /* Verify that all sibling pages are of the same "type" (table-leaf,
76477 ** table-interior, index-leaf, or index-interior).
76479 if( pOld->aData[0]!=apOld[0]->aData[0] ){
76501 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
76502 if( pOld->nOverflow>0 ){
76503 if( NEVER(limit<pOld->aiOvfl[0]) ){
76507 limit = pOld->aiOvfl[0];
76513 for(k=0; k<pOld->nOverflow; k++){
76514 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
76515 b.apCell[b.nCell] = pOld->apOvfl[k];
76519 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
76526 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
76529 if( i<nOld-1 && !leafData){
76536 assert( sz<=pBt->maxLocal+23 );
76537 assert( iSpace1 <= (int)pBt->pageSize );
76541 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
76542 if( !pOld->leaf ){
76544 assert( pOld->hdrOffset==0 || CORRUPT_DB );
76547 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
76554 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
76566 ** size of all cells on the i-th page and cntNew[] which is the index
76573 ** szNew[i]: Spaced used on the i-th sibling page.
76575 ** the right of the i-th sibling page.
76579 usableSpace = pBt->usableSize - 12 + leafCorrection;
76582 b.apEnd[k] = p->aDataEnd;
76584 if( k && b.ixNx[k]==b.ixNx[k-1] ){
76585 k--; /* Omit b.ixNx[] entry for child pages with no cells */
76589 b.apEnd[k] = pParent->aDataEnd;
76592 assert( p->nFree>=0 );
76593 szNew[i] = usableSpace - p->nFree;
76594 for(j=0; j<p->nOverflow; j++){
76595 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
76606 szNew[k-1] = 0;
76607 cntNew[k-1] = b.nCell;
76609 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
76610 szNew[i] -= sz;
76619 cntNew[i]--;
76633 szNew[i+1] -= sz;
76637 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
76646 ** always nearly full, while the right-most sibling might be nearly empty.
76651 ** be so out of balance as to be illegal. For example, the right-most
76654 for(i=k-1; i>0; i--){
76656 int szLeft = szNew[i-1]; /* Size of sibling on the left */
76657 int r; /* Index of right-most cell in left sibling */
76660 r = cntNew[i-1] - 1;
76661 d = r + 1 - leafData;
76668 && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+(i==k-1?0:2)))){
76672 szLeft -= b.szCell[r] + 2;
76673 cntNew[i-1] = r;
76674 r--;
76675 d--;
76678 szNew[i-1] = szLeft;
76679 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
76685 /* Sanity check: For a non-corrupt database file one of the follwing
76692 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
76694 apOld[0]->pgno, apOld[0]->nCell,
76695 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
76696 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
76702 pageFlags = apOld[0]->aData[0];
76708 rc = sqlite3PagerWrite(pNew->pDbPage);
76710 if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
76725 /* Set the pointer-map entry for the new sibling page. */
76727 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
76748 aPgno[i] = apNew[i]->pgno;
76749 assert( apNew[i]->pDbPage->flags & PGHDR_WRITEABLE );
76750 assert( apNew[i]->pDbPage->flags & PGHDR_DIRTY );
76752 for(i=0; i<nNew-1; i++){
76755 if( apNew[j]->pgno < apNew[iB]->pgno ) iB = j;
76764 Pgno pgnoA = apNew[i]->pgno;
76765 Pgno pgnoB = apNew[iB]->pgno;
76766 Pgno pgnoTemp = (PENDING_BYTE/pBt->pageSize)+1;
76767 u16 fgA = apNew[i]->pDbPage->flags;
76768 u16 fgB = apNew[iB]->pDbPage->flags;
76769 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoTemp, fgB);
76770 sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
76771 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
76772 apNew[i]->pgno = pgnoB;
76773 apNew[iB]->pgno = pgnoA;
76779 apNew[0]->pgno, szNew[0], cntNew[0],
76780 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
76781 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
76782 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
76783 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
76784 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
76785 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
76786 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
76787 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
76790 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
76792 assert( apNew[nNew-1]!=0 );
76793 put4byte(pRight, apNew[nNew-1]->pgno);
76795 /* If the sibling pages are not leaves, ensure that the right-child pointer
76796 ** of the right-most new sibling page is set to the value that was
76797 ** originally in the same field of the right-most old sibling page. */
76799 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
76800 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
76815 ** associated with the right-child of each sibling may also need to be
76822 int cntOldNext = pNew->nCell + pNew->nOverflow;
76833 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
76847 || pNew->pgno!=aPgno[iOld]
76848 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
76851 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
76853 if( cachedCellSize(&b,i)>pNew->minLocal ){
76862 for(i=0; i<nNew-1; i++){
76875 if( !pNew->leaf ){
76876 memcpy(&pNew->aData[8], pCell, 4);
76878 /* If the tree is a leaf-data tree, and the siblings are leaves,
76880 ** cell consists of the integer key for the right-most cell of
76881 ** the sibling-page assembled above only.
76884 j--;
76885 pNew->xParseCell(pNew, b.apCell[j], &info);
76890 pCell -= 4;
76891 /* Obscure case for non-leaf-data trees: If the cell at pCell was
76898 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
76904 sz = pParent->xCellSize(pParent, pCell);
76908 assert( sz<=pBt->maxLocal+23 );
76909 assert( iOvflSpace <= (int)pBt->pageSize );
76916 insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
76918 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
76925 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
76927 ** the left-hand sibling apNew[iPg-1] has been updated.
76931 ** the right-hand sibling apNew[iPg+1] has been updated.
76935 ** The iPg value in the following loop starts at nNew-1 goes down
76936 ** to 0, then back up to nNew-1 again, thus making two passes over
76943 for(i=1-nNew; i<nNew; i++){
76944 int iPg = i<0 ? -i : i;
76948 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
76955 ** only after iPg-1 has already been updated. */
76956 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
76966 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
76967 iNew = cntNew[iPg-1] + !leafData;
76968 nNewCell = cntNew[iPg] - iNew;
76974 apNew[iPg]->nFree = usableSpace-szNew[iPg];
76975 assert( apNew[iPg]->nOverflow==0 );
76976 assert( apNew[iPg]->nCell==nNewCell );
76986 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
76987 /* The root page of the b-tree now contains no cells. The only sibling
76988 ** page is the right-child of the parent. Copy the contents of the
76990 ** b-tree structure by one. This is described as the "balance-shallower"
76991 ** sub-algorithm in some documentation.
76993 ** If this is an auto-vacuum database, the call to copyNodeContent()
76994 ** sets all pointer-map entries corresponding to database image pages
77003 rc = defragmentPage(apNew[0], -1);
77005 assert( apNew[0]->nFree ==
77006 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
77007 - apNew[0]->nCell*2)
77013 /* Fix the pointer map entries associated with the right-child of each
77017 u32 key = get4byte(&apNew[i]->aData[8]);
77018 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
77022 assert( pParent->isInit );
77033 if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
77060 ** This function is called when the root page of a b-tree structure is
77065 ** page is then overwritten to make it an empty page with the right-child
77068 ** Before returning, all pointer-map entries corresponding to pages
77069 ** that the new child-page now contains pointers to are updated. The
77070 ** entry corresponding to the new right-child pointer of the root
77082 BtShared *pBt = pRoot->pBt; /* The BTree */
77084 assert( pRoot->nOverflow>0 );
77085 assert( sqlite3_mutex_held(pBt->mutex) );
77087 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
77088 ** page that will become the new right-child of pPage. Copy the contents
77091 rc = sqlite3PagerWrite(pRoot->pDbPage);
77093 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
77096 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
77104 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
77105 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
77106 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
77108 TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
77111 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
77112 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
77113 memcpy(pChild->apOvfl, pRoot->apOvfl,
77114 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
77115 pChild->nOverflow = pRoot->nOverflow;
77117 /* Zero the contents of pRoot. Then install pChild as the right-child. */
77118 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
77119 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
77127 ** on the same B-tree as pCur.
77130 ** pointing to the same b-tree. If an insert occurs on one SQL table
77132 ** table linked to the same b-tree. If the secondary insert causes a
77138 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
77140 && pOther->eState==CURSOR_VALID
77141 && pOther->pPage==pCur->pPage
77169 MemPage *pPage = pCur->pPage;
77171 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
77172 if( pPage->nOverflow==0 && pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
77178 }else if( (iPage = pCur->iPage)==0 ){
77179 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
77180 /* The root page of the b-tree is overfull. In this case call the
77181 ** balance_deeper() function to create a new child for the root-page
77182 ** and copy the current contents of the root-page to it. The
77183 ** next iteration of the do-loop will balance the child page.
77187 rc = balance_deeper(pPage, &pCur->apPage[1]);
77189 pCur->iPage = 1;
77190 pCur->ix = 0;
77191 pCur->aiIdx[0] = 0;
77192 pCur->apPage[0] = pPage;
77193 pCur->pPage = pCur->apPage[1];
77194 assert( pCur->pPage->nOverflow );
77199 }else if( sqlite3PagerPageRefcount(pPage->pDbPage)>1 ){
77205 MemPage * const pParent = pCur->apPage[iPage-1];
77206 int const iIdx = pCur->aiIdx[iPage-1];
77208 rc = sqlite3PagerWrite(pParent->pDbPage);
77209 if( rc==SQLITE_OK && pParent->nFree<0 ){
77214 if( pPage->intKeyLeaf
77215 && pPage->nOverflow==1
77216 && pPage->aiOvfl[0]==pPage->nCell
77217 && pParent->pgno!=1
77218 && pParent->nCell==iIdx
77223 ** happens, the next iteration of the do-loop will balance pParent
77242 ** become overfull or underfull. The next iteration of the do-loop
77247 ** A subsequent iteration of the do-loop will deal with this by
77249 ** but it doesn't deal with overflow cells - just moves them to a
77256 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
77258 pCur->hints&BTREE_BULKLOAD);
77274 pPage->nOverflow = 0;
77276 /* The next iteration of the do-loop balances the parent page. */
77278 pCur->iPage--;
77279 assert( pCur->iPage>=0 );
77280 pCur->pPage = pCur->apPage[pCur->iPage];
77296 const BtreePayload *pX, /* Source of data to write */
77300 int nData = pX->nData - iOffset;
77306 int rc = sqlite3PagerWrite(pPage->pDbPage);
77308 memset(pDest + i, 0, iAmt - i);
77315 iAmt-nData);
77319 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
77320 int rc = sqlite3PagerWrite(pPage->pDbPage);
77322 /* In a corrupt database, it is possible for the source and destination
77326 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
77337 int iOffset; /* Next byte of pX->pData to write */
77338 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
77340 MemPage *pPage = pCur->pPage; /* Page being written */
77345 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
77346 || pCur->info.pPayload < pPage->aData + pPage->cellOffset
77351 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
77352 0, pCur->info.nLocal);
77354 if( pCur->info.nLocal==nTotal ) return SQLITE_OK;
77357 iOffset = pCur->info.nLocal;
77360 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
77361 pBt = pPage->pBt;
77362 ovflPageSize = pBt->usableSize - 4;
77366 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
77370 ovflPgno = get4byte(pPage->aData);
77372 ovflPageSize = nTotal - iOffset;
77374 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
77377 sqlite3PagerUnref(pPage->pDbPage);
77400 ** If the seekResult parameter is non-zero, then a successful call to
77411 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
77412 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
77422 int loc = seekResult; /* -1: before desired location +1: after */
77426 Btree *p = pCur->pBtree;
77427 BtShared *pBt = p->pBt;
77432 assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
77436 ** In some cases, the call to btreeMoveto() below is a no-op. For
77437 ** example, when inserting data into a table with auto-generated integer
77440 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
77445 if( pCur->curFlags & BTCF_Multiple ){
77446 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
77448 if( loc && pCur->iPage<0 ){
77461 if( pCur->eState>=CURSOR_REQUIRESEEK ){
77462 testcase( pCur->eState==CURSOR_REQUIRESEEK );
77463 testcase( pCur->eState==CURSOR_FAULT );
77469 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
77470 && pBt->inTransaction==TRANS_WRITE
77471 && (pBt->btsFlags & BTS_READ_ONLY)==0 );
77472 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
77475 ** expecting an index b-tree, then the caller should be inserting blob
77479 assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
77481 if( pCur->pKeyInfo==0 ){
77482 assert( pX->pKey==0 );
77483 /* If this is an insert into a table b-tree, invalidate any incrblob
77485 if( p->hasIncrblobCur ){
77486 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
77494 assert( pCur->curFlags & BTCF_ValidNKey );
77495 assert( pX->nKey==pCur->info.nKey );
77504 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
77507 assert( pX->nData>=0 && pX->nZero>=0 );
77508 if( pCur->info.nSize!=0
77509 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
77520 rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
77538 if( pX->nMem ){
77540 r.pKeyInfo = pCur->pKeyInfo;
77541 r.aMem = pX->aMem;
77542 r.nField = pX->nMem;
77547 rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
77559 if( pCur->info.nKey==pX->nKey ){
77561 x2.pData = pX->pKey;
77562 x2.nData = pX->nKey;
77568 assert( pCur->eState==CURSOR_VALID
77569 || (pCur->eState==CURSOR_INVALID && loc) );
77571 pPage = pCur->pPage;
77572 assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
77573 assert( pPage->leaf || !pPage->intKey );
77574 if( pPage->nFree<0 ){
77575 if( NEVER(pCur->eState>CURSOR_INVALID) ){
77576 /* ^^^^^--- due to the moveToRoot() call above */
77585 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
77587 assert( pPage->isInit || CORRUPT_DB );
77588 newCell = pBt->pTmpSpace;
77592 szNew = pBt->nPreformatSize;
77594 if( ISAUTOVACUUM && szNew>pPage->maxLocal ){
77596 pPage->xParseCell(pPage, newCell, &info);
77598 Pgno ovfl = get4byte(&newCell[szNew-4]);
77599 ptrmapPut(pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
77606 assert( szNew==pPage->xCellSize(pPage, newCell) );
77608 idx = pCur->ix;
77612 if( idx>=pPage->nCell ){
77615 rc = sqlite3PagerWrite(pPage->pDbPage);
77620 if( !pPage->leaf ){
77624 testcase( pCur->curFlags & BTCF_ValidOvfl );
77627 && (!ISAUTOVACUUM || szNew<pPage->minLocal)
77637 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
77639 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
77642 if( oldCell+szNew > pPage->aDataEnd ){
77650 }else if( loc<0 && pPage->nCell>0 ){
77651 assert( pPage->leaf );
77652 idx = ++pCur->ix;
77653 pCur->curFlags &= ~BTCF_ValidNKey;
77655 assert( pPage->leaf );
77658 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
77659 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
77673 ** multiple records into an intkey b-tree using a single cursor (as can
77676 ** the b-tree if possible. If the cursor is left pointing to the last
77681 pCur->info.nSize = 0;
77682 if( pPage->nOverflow ){
77684 pCur->curFlags &= ~(BTCF_ValidNKey);
77691 pCur->pPage->nOverflow = 0;
77692 pCur->eState = CURSOR_INVALID;
77695 if( pCur->pKeyInfo ){
77696 assert( pCur->pKey==0 );
77697 pCur->pKey = sqlite3Malloc( pX->nKey );
77698 if( pCur->pKey==0 ){
77701 memcpy(pCur->pKey, pX->pKey, pX->nKey);
77704 pCur->eState = CURSOR_REQUIRESEEK;
77705 pCur->nKey = pX->nKey;
77708 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
77731 BtShared *pBt = pDest->pBt;
77732 u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */
77738 if( pSrc->info.nPayload<0x80 ){
77739 *(aOut++) = pSrc->info.nPayload;
77741 aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload);
77743 if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
77744 nIn = pSrc->info.nLocal;
77745 aIn = pSrc->info.pPayload;
77746 if( aIn+nIn>pSrc->pPage->aDataEnd ){
77749 nRem = pSrc->info.nPayload;
77750 if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
77752 pBt->nPreformatSize = nIn + (aOut - pBt->pTmpSpace);
77754 Pager *pSrcPager = pSrc->pBt->pPager;
77761 nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
77762 pBt->nPreformatSize = nOut + (aOut - pBt->pTmpSpace);
77763 if( nOut<pSrc->info.nPayload ){
77765 pBt->nPreformatSize += 4;
77769 if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
77772 ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
77776 nRem -= nOut;
77782 nOut -= nCopy;
77783 nIn -= nCopy;
77795 nIn = pSrc->pBt->usableSize - 4;
77806 ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
77811 pPgnoOut = pPageOut->aData;
77814 nOut = MIN(pBt->usableSize - 4, nRem);
77839 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
77844 Btree *p = pCur->pBtree;
77845 BtShared *pBt = p->pBt;
77855 assert( pBt->inTransaction==TRANS_WRITE );
77856 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
77857 assert( pCur->curFlags & BTCF_WriteFlag );
77858 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
77859 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
77861 if( pCur->eState!=CURSOR_VALID ){
77862 if( pCur->eState>=CURSOR_REQUIRESEEK ){
77864 assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
77865 if( rc || pCur->eState!=CURSOR_VALID ) return rc;
77870 assert( pCur->eState==CURSOR_VALID );
77872 iCellDepth = pCur->iPage;
77873 iCellIdx = pCur->ix;
77874 pPage = pCur->pPage;
77875 if( pPage->nCell<=iCellIdx ){
77879 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
77885 ** will cause a b-tree rebalance, then this is done by saving the cursor
77901 if( !pPage->leaf
77902 || (pPage->nFree+pPage->xCellSize(pPage,pCell)+2) >
77903 (int)(pBt->usableSize*2/3)
77904 || pPage->nCell==1 /* See dbfuzz001.test for a test case */
77906 /* A b-tree rebalance will be required after deleting this entry.
77920 ** sub-tree headed by the child page of the cell being deleted. This makes
77922 if( !pPage->leaf ){
77930 if( pCur->curFlags & BTCF_Multiple ){
77931 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
77935 /* If this is a delete operation to remove a row from a table b-tree,
77937 if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
77938 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
77944 rc = sqlite3PagerWrite(pPage->pDbPage);
77951 ** is currently pointing to the largest entry in the sub-tree headed
77952 ** by the child-page of the cell that was just deleted from an internal
77955 if( !pPage->leaf ){
77956 MemPage *pLeaf = pCur->pPage;
77961 if( pLeaf->nFree<0 ){
77965 if( iCellDepth<pCur->iPage-1 ){
77966 n = pCur->apPage[iCellDepth+1]->pgno;
77968 n = pCur->pPage->pgno;
77970 pCell = findCell(pLeaf, pLeaf->nCell-1);
77971 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
77972 nCell = pLeaf->xCellSize(pLeaf, pCell);
77974 pTmp = pBt->pTmpSpace;
77976 rc = sqlite3PagerWrite(pLeaf->pDbPage);
77978 insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
77980 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
77999 assert( pCur->pPage->nOverflow==0 );
78000 assert( pCur->pPage->nFree>=0 );
78001 if( pCur->pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
78003 ** then balance() will always be a no-op. No need to invoke it. */
78008 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
78009 releasePageNotNull(pCur->pPage);
78010 pCur->iPage--;
78011 while( pCur->iPage>iCellDepth ){
78012 releasePage(pCur->apPage[pCur->iPage--]);
78014 pCur->pPage = pCur->apPage[pCur->iPage];
78020 assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
78021 assert( pPage==pCur->pPage || CORRUPT_DB );
78022 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
78023 pCur->eState = CURSOR_SKIPNEXT;
78024 if( iCellIdx>=pPage->nCell ){
78025 pCur->skipNext = -1;
78026 pCur->ix = pPage->nCell-1;
78028 pCur->skipNext = 1;
78034 pCur->eState = CURSOR_REQUIRESEEK;
78054 BtShared *pBt = p->pBt;
78058 int ptfFlags; /* Page-type flage for the root page of new table */
78061 assert( pBt->inTransaction==TRANS_WRITE );
78062 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
78070 if( pBt->autoVacuum ){
78071 Pgno pgnoMove; /* Move a page here to make room for the root-page */
78076 ** out to be an overflow page, delete all overflow page-map caches
78082 ** root page of the new table should go. meta[3] is the largest root-page
78083 ** created so far, so the new root-page is (meta[3]+1).
78091 /* The new root-page may not be allocated on a pointer-map page, or the
78110 /* pgnoRoot is the page that will be used for the root-page of
78154 rc = sqlite3PagerWrite(pRoot->pDbPage);
78163 /* Update the pointer-map and meta-data with the new root-page number. */
78174 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
78186 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
78193 sqlite3PagerUnref(pRoot->pDbPage);
78194 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
78223 assert( sqlite3_mutex_held(pBt->mutex) );
78229 if( (pBt->openFlags & BTREE_SINGLE)==0
78230 && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
78235 hdr = pPage->hdrOffset;
78236 for(i=0; i<pPage->nCell; i++){
78238 if( !pPage->leaf ){
78245 if( !pPage->leaf ){
78246 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
78248 if( pPage->intKey ) pnChange = 0;
78251 testcase( !pPage->intKey );
78252 *pnChange += pPage->nCell;
78256 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
78257 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
78279 BtShared *pBt = p->pBt;
78281 assert( p->inTrans==TRANS_WRITE );
78287 ** is the root of a table b-tree - if it is not, the following call is
78288 ** a no-op). */
78289 if( p->hasIncrblobCur ){
78304 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
78330 BtShared *pBt = p->pBt;
78333 assert( p->inTrans==TRANS_WRITE );
78353 if( pBt->autoVacuum ){
78358 /* If the table being dropped is the table with the largest root-page
78367 /* The table being dropped does not have the largest root-page
78369 ** gap left by the deleted root-page.
78392 /* Set the new 'max-root-page' value in the database header. This
78394 ** be a root-page number, less one again if that is the
78397 maxRootPgno--;
78400 maxRootPgno--;
78422 ** This function may only be called if the b-tree connection already
78425 ** Read the meta-information out of a database file. Meta[0]
78428 ** is read-only, the others are read/write.
78442 BtShared *pBt = p->pBt;
78445 assert( p->inTrans>TRANS_NONE );
78447 assert( pBt->pPage1 );
78451 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
78453 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
78456 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
78457 ** database, mark the database as read-only. */
78460 pBt->btsFlags |= BTS_READ_ONLY;
78468 ** Write meta-information back into the database. Meta[0] is
78469 ** read-only and may not be written.
78472 BtShared *pBt = p->pBt;
78477 assert( p->inTrans==TRANS_WRITE );
78478 assert( pBt->pPage1!=0 );
78479 pP1 = pBt->pPage1->aData;
78480 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
78485 assert( pBt->autoVacuum || iMeta==0 );
78487 pBt->incrVacuum = (u8)iMeta;
78496 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
78497 ** number of entries in the b-tree and write the result to *pnEntry.
78514 ** page in the B-Tree structure (not including overflow pages).
78516 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
78518 MemPage *pPage; /* Current page of the b-tree */
78520 /* If this is a leaf page or the tree is not an int-key tree, then
78524 pPage = pCur->pPage;
78525 if( pPage->leaf || !pPage->intKey ){
78526 nEntry += pPage->nCell;
78532 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
78534 ** to visit is the right-child of its parent.
78539 if( pPage->leaf ){
78541 if( pCur->iPage==0 ){
78542 /* All pages of the b-tree have been visited. Return successfully. */
78547 }while ( pCur->ix>=pCur->pPage->nCell );
78549 pCur->ix++;
78550 pPage = pCur->pPage;
78554 ** points at. This is the right-child if (iIdx==pPage->nCell).
78556 iIdx = pCur->ix;
78557 if( iIdx==pPage->nCell ){
78558 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
78573 return p->pBt->pPager;
78586 if( !pCheck->mxErr ) return;
78587 pCheck->mxErr--;
78588 pCheck->nErr++;
78590 if( pCheck->errMsg.nChar ){
78591 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
78593 if( pCheck->zPfx ){
78594 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
78596 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
78598 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
78599 pCheck->bOomFault = 1;
78607 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
78611 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
78612 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
78619 assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
78620 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
78626 ** reference to the page, add an error message to pCheck->zErrMsg.
78633 if( iPage>pCheck->nPage || iPage==0 ){
78641 if( AtomicLoad(&pCheck->db->u1.isInterrupted) ) return 1;
78648 ** Check that the entry in the pointer-map for page iChild maps to
78662 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
78664 if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->bOomFault = 1;
78689 int nErrAtStart = pCheck->nErr;
78690 while( iPage!=0 && pCheck->mxErr ){
78694 N--;
78695 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
78703 if( pCheck->pBt->autoVacuum ){
78707 if( n>pCheck->pBt->usableSize/4-2 ){
78710 N--;
78715 if( pCheck->pBt->autoVacuum ){
78721 N -= n;
78726 /* If this database supports auto-vacuum and iPage is not the last
78727 ** page in this overflow list, check that the pointer-map entry for
78730 if( pCheck->pBt->autoVacuum && N>0 ){
78739 if( N && nErrAtStart==pCheck->nErr ){
78743 expected-N, expected);
78749 ** An implementation of a min-heap.
78759 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
78786 aHeap[0]--;
78823 int depth = -1, d2; /* Depth of a subtree */
78839 u32 *heap = 0; /* Min-heap used for checking cell coverage */
78840 u32 x, prev = 0; /* Next and previous entry on the min-heap */
78841 const char *saved_zPfx = pCheck->zPfx;
78842 int saved_v1 = pCheck->v1;
78843 int saved_v2 = pCheck->v2;
78848 pBt = pCheck->pBt;
78849 usableSize = pBt->usableSize;
78852 pCheck->zPfx = "Page %u: ";
78853 pCheck->v1 = iPage;
78862 savedIsInit = pPage->isInit;
78863 pPage->isInit = 0;
78875 data = pPage->aData;
78876 hdr = pPage->hdrOffset;
78879 pCheck->zPfx = "On tree page %u cell %d: ";
78883 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
78886 assert( pPage->nCell==nCell );
78888 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
78889 ** immediately follows the b-tree page header. */
78890 cellStart = hdr + 12 - 4*pPage->leaf;
78891 assert( pPage->aCellIdx==&data[cellStart] );
78892 pCellIdx = &data[cellStart + 2*(nCell-1)];
78894 if( !pPage->leaf ){
78895 /* Analyze the right-child page of internal pages */
78898 if( pBt->autoVacuum ){
78899 pCheck->zPfx = "On page %u at right child: ";
78908 heap = pCheck->heap;
78912 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
78914 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
78918 pCheck->v2 = i;
78921 pCellIdx -= 2;
78922 if( pc<contentOffset || pc>usableSize-4 ){
78924 pc, contentOffset, usableSize-4);
78929 pPage->xParseCell(pPage, pCell, &info);
78937 if( pPage->intKey ){
78949 assert( pc + info.nSize - 4 <= usableSize );
78950 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
78951 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
78953 if( pBt->autoVacuum ){
78960 if( !pPage->leaf ){
78964 if( pBt->autoVacuum ){
78975 /* Populate the coverage-checking heap for leaf pages */
78976 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
78983 pCheck->zPfx = 0;
78984 if( doCoverageCheck && pCheck->mxErr>0 ){
78985 /* For leaf pages, the min-heap has already been initialized and the
78988 if( !pPage->leaf ){
78989 heap = pCheck->heap;
78991 for(i=nCell-1; i>=0; i--){
78994 size = pPage->xCellSize(pPage, &data[pc]);
78995 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
78998 /* Add the freeblocks to the min-heap
79000 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
79007 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
79010 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
79011 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
79012 ** big-endian integer which is the offset in the b-tree page of the next
79016 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
79019 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
79022 /* Analyze the min-heap looking for overlap between cells and/or
79025 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
79030 ** The loop below pulls entries from the min-heap in order and compares
79036 prev = contentOffset - 1; /* Implied first min-heap entry */
79043 nFrag += (x>>16) - (prev&0xffff) - 1;
79047 nFrag += usableSize - (prev&0xffff) - 1;
79048 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
79049 ** is stored in the fifth field of the b-tree page header.
79050 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
79061 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
79063 pCheck->zPfx = saved_zPfx;
79064 pCheck->v1 = saved_v1;
79065 pCheck->v2 = saved_v2;
79076 ** A read-only or read-write transaction must be opened before calling
79081 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
79085 ** root pages is incomplete. This is a "partial integrity-check". This
79103 BtShared *pBt = p->pBt;
79104 u64 savedDbFlags = pBt->db->flags;
79119 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
79120 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
79124 sCheck.pPager = pBt->pPager;
79145 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
79158 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
79159 get4byte(&pBt->pPage1->aData[36]));
79167 if( pBt->autoVacuum ){
79171 mxInHdr = get4byte(&pBt->pPage1->aData[52]);
79178 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
79185 testcase( pBt->db->flags & SQLITE_CellSizeCk );
79186 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
79191 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
79197 pBt->db->flags = savedDbFlags;
79208 /* If the database supports auto-vacuum, make sure no tables contain
79209 ** references to pointer-map pages.
79212 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
79216 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
79235 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
79243 ** an empty string if the database is in-memory or a TEMP database.
79249 assert( p->pBt->pPager!=0 );
79250 return sqlite3PagerFilename(p->pBt->pPager, 1);
79262 assert( p->pBt->pPager!=0 );
79263 return sqlite3PagerJournalname(p->pBt->pPager);
79271 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
79272 return p ? p->inTrans : 0;
79280 ** transaction on the shared-cache the argument Btree is connected to.
79287 BtShared *pBt = p->pBt;
79289 if( pBt->inTransaction!=TRANS_NONE ){
79292 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
79305 assert( sqlite3_mutex_held(p->db->mutex) );
79306 return p->nBackup!=0;
79311 ** a single shared-btree. The memory is used by client code for its own
79312 ** purposes (for example, to store a high-level schema associated with
79313 ** the shared-btree). The btree layer manages reference counting issues.
79315 ** The first time this is called on a shared-btree, nBytes bytes of memory
79324 ** Just before the shared-btree is closed, the function passed as the
79330 BtShared *pBt = p->pBt;
79332 if( !pBt->pSchema && nBytes ){
79333 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
79334 pBt->xFreeSchema = xFree;
79337 return pBt->pSchema;
79347 assert( sqlite3_mutex_held(p->db->mutex) );
79364 assert( p->inTrans!=TRANS_NONE );
79365 if( p->sharable ){
79395 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
79396 assert( pCsr->curFlags & BTCF_Incrblob );
79402 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
79403 if( pCsr->eState!=CURSOR_VALID ){
79409 ** version of the b-tree page modified by the accessPayload call below.
79415 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
79421 ** (c) the connection holds a write-lock on the table (if required),
79422 ** (d) there are no conflicting read-locks, and
79425 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
79428 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
79429 && pCsr->pBt->inTransaction==TRANS_WRITE );
79430 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
79431 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
79432 assert( pCsr->pPage->intKey );
79441 pCur->curFlags |= BTCF_Incrblob;
79442 pCur->pBtree->hasIncrblobCur = 1;
79452 BtShared *pBt = pBtree->pBt;
79460 pBt->btsFlags &= ~BTS_NO_WAL;
79461 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
79465 u8 *aData = pBt->pPage1->aData;
79469 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
79478 pBt->btsFlags &= ~BTS_NO_WAL;
79487 return (pCsr->hints & mask)!=0;
79491 ** Return true if the given Btree is read-only.
79494 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
79503 ** If no transaction is active and the database is not a temp-db, clear
79504 ** the in-memory pager cache.
79507 BtShared *pBt = p->pBt;
79508 if( pBt->inTransaction==TRANS_NONE ){
79509 sqlite3PagerClearCache(pBt->pPager);
79518 return p->sharable;
79527 testcase( p->sharable );
79528 return p->pBt->nRef;
79537 ** The author disclaims copyright to this source code. In place of
79556 Btree *pDest; /* Destination b-tree file */
79558 int bDestLocked; /* True once a write-transaction is open on pDest */
79560 Pgno iNext; /* Page number of the next source page to copy */
79561 sqlite3* pSrcDb; /* Source database handle */
79562 Btree *pSrc; /* Source b-tree file */
79573 sqlite3_backup *pNext; /* Next backup associated with source pager */
79580 ** structure may be accessed via two groups of thread-safe entry points:
79583 ** backup_finish(). Both these functions obtain the source database
79584 ** handle mutex and the mutex associated with the source BtShared
79589 ** the page cache associated with the source database. The mutex
79590 ** associated with the source database BtShared structure will always
79594 ** backup_pagecount() are not thread-safe functions. If they are called
79602 ** Non-sharable Btrees (in-memory databases for example), do not have
79638 return pDb->aDb[i].pBt;
79643 ** of the source.
79647 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0);
79652 ** Check that there is no open read-transaction on the b-tree passed as the
79654 ** is an open read-transaction, return SQLITE_ERROR and leave an error
79688 /* Lock the source database handle. The destination database
79696 sqlite3_mutex_enter(pSrcDb->mutex);
79697 sqlite3_mutex_enter(pDestDb->mutex);
79701 pDestDb, SQLITE_ERROR, "source and destination must be distinct"
79706 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
79717 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
79718 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
79719 p->pDestDb = pDestDb;
79720 p->pSrcDb = pSrcDb;
79721 p->iNext = 1;
79722 p->isAttached = 0;
79724 if( 0==p->pSrc || 0==p->pDest
79725 || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
79737 p->pSrc->nBackup++;
79740 sqlite3_mutex_leave(pDestDb->mutex);
79741 sqlite3_mutex_leave(pSrcDb->mutex);
79756 ** page iSrcPg from the source database. Copy this data into the
79761 Pgno iSrcPg, /* Source database page to backup */
79762 const u8 *zSrcData, /* Source database page data */
79765 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
79766 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
79767 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
79771 /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
79772 ** guaranteed that the shared-mutex is held by this thread, handle
79773 ** p->pSrc may not actually be the owner. */
79774 int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
79775 int nDestReserve = sqlite3BtreeGetRequestedReserve(p->pDest);
79780 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
79781 assert( p->bDestLocked );
79782 assert( !isFatalError(p->rc) );
79783 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
79786 /* Catch the case where the destination is an in-memory database and the
79787 ** page sizes of the source and destination differ.
79801 ** between source and destination. If there is a difference, try to
79802 ** fix the destination to agree with the source. If that is not possible,
79811 /* This loop runs once for each destination page spanned by the source
79815 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
79818 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
79826 /* Copy the data from the source page into the destination page.
79836 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
79848 ** this function is a no-op.
79863 ** Register this backup object with the associated source pager for
79868 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
79869 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
79870 p->pNext = *pp;
79872 p->isAttached = 1;
79876 ** Copy nPage pages from the source b-tree to the destination.
79881 int pgszSrc = 0; /* Source page size */
79887 sqlite3_mutex_enter(p->pSrcDb->mutex);
79888 sqlite3BtreeEnter(p->pSrc);
79889 if( p->pDestDb ){
79890 sqlite3_mutex_enter(p->pDestDb->mutex);
79893 rc = p->rc;
79895 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
79896 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
79898 int nSrcPage = -1; /* Size of source db in pages */
79901 /* If the source pager is currently in a write-transaction, return
79904 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
79910 /* If there is no open read-transaction on the source database, open
79914 if( rc==SQLITE_OK && SQLITE_TXN_NONE==sqlite3BtreeTxnState(p->pSrc) ){
79915 rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
79921 ** try to set its page size to the same as the source database. This
79925 if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
79930 if( SQLITE_OK==rc && p->bDestLocked==0
79931 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
79932 (int*)&p->iDestSchema))
79934 p->bDestLocked = 1;
79938 ** and the page sizes are different between source and destination */
79939 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
79940 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
79941 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
79946 /* Now that there is a read-lock on the source database, query the
79947 ** source pager for the number of pages in the database.
79949 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
79951 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
79952 const Pgno iSrcPg = p->iNext; /* Source page number */
79953 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
79954 DbPage *pSrcPg; /* Source page object */
79961 p->iNext++;
79964 p->nPagecount = nSrcPage;
79965 p->nRemaining = nSrcPage+1-p->iNext;
79966 if( p->iNext>(Pgno)nSrcPage ){
79968 }else if( !p->isAttached ){
79974 ** is to make sure that the schema-version really does change in
79975 ** the case where the source and destination databases have the
79980 rc = sqlite3BtreeNewDb(p->pDest);
79984 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
79987 if( p->pDestDb ){
79988 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
79991 rc = sqlite3BtreeSetVersion(p->pDest, 2);
79998 ** size may be different to the source page size.
80000 ** If the source page size is smaller than the destination page size,
80008 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
80009 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
80012 nDestTruncate = (nSrcPage+ratio-1)/ratio;
80013 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
80014 nDestTruncate--;
80022 /* If the source page-size is smaller than the destination page-size,
80028 ** pending-byte page in the source database may need to be
80041 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
80053 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
80097 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
80105 ** on the source database. Close the read transaction here. There is
80107 ** "committing" a read-only transaction cannot fail.
80111 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
80112 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
80119 p->rc = rc;
80121 if( p->pDestDb ){
80122 sqlite3_mutex_leave(p->pDestDb->mutex);
80124 sqlite3BtreeLeave(p->pSrc);
80125 sqlite3_mutex_leave(p->pSrcDb->mutex);
80134 sqlite3 *pSrcDb; /* Source database connection */
80139 pSrcDb = p->pSrcDb;
80140 sqlite3_mutex_enter(pSrcDb->mutex);
80141 sqlite3BtreeEnter(p->pSrc);
80142 if( p->pDestDb ){
80143 sqlite3_mutex_enter(p->pDestDb->mutex);
80146 /* Detach this backup from the source pager. */
80147 if( p->pDestDb ){
80148 p->pSrc->nBackup--;
80150 if( p->isAttached ){
80151 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
80154 pp = &(*pp)->pNext;
80157 *pp = p->pNext;
80161 sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
80164 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
80165 if( p->pDestDb ){
80166 sqlite3Error(p->pDestDb, rc);
80169 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
80171 sqlite3BtreeLeave(p->pSrc);
80172 if( p->pDestDb ){
80173 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
80193 return p->nRemaining;
80197 ** Return the total number of pages in the source database as of the most
80207 return p->nPagecount;
80212 ** source database have been modified. If page iPage has already been
80219 ** corresponding to the source database is held when this function is
80229 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
80230 if( !isFatalError(p->rc) && iPage<p->iNext ){
80232 ** has been modified by a transaction on the source pager. Copy
80236 assert( p->pDestDb );
80237 sqlite3_mutex_enter(p->pDestDb->mutex);
80239 sqlite3_mutex_leave(p->pDestDb->mutex);
80242 p->rc = rc;
80245 }while( (p = p->pNext)!=0 );
80259 ** corresponding to the source database is held when this function is
80264 for(p=pBackup; p; p=p->pNext){
80265 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
80266 p->iNext = 1;
80288 if( pFd->pMethods ){
80301 b.pSrcDb = pFrom->db;
80314 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
80321 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
80339 ** The author disclaims copyright to this source code. In place of
80359 #define ISPOWEROF2(X) (((X)&((X)-1))==0)
80372 assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
80378 assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
80381 assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );
80383 if( p->flags & MEM_Null ){
80385 assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
80392 if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
80395 assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
80396 ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
80397 ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
80400 assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
80408 assert( (p->flags & MEM_Cleared)==0 );
80412 assert( p->szMalloc==0
80413 || (p->flags==MEM_Undefined
80414 && p->szMalloc<=sqlite3DbMallocSize(p->db,p->zMalloc))
80415 || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc));
80425 if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
80427 ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
80428 ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
80429 ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
80430 ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
80443 assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
80445 if( p->flags & MEM_Int ){
80447 /* Work-around for GCC bug
80450 assert( (p->flags&MEM_Int)*2==sizeof(x) );
80451 memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2);
80454 sqlite3Int64ToText(p->u.i, zBuf);
80459 (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r);
80478 ** https://www.sqlite.org/src/info/343634942dd54ab (2018-01-31) for
80492 if( (p->flags & MEM_Str)==0 ) return 1;
80493 if( p->flags & MEM_Term ){
80494 /* Insure that the string is properly zero-terminated. Pay particular
80495 ** attention to the case where p->n is odd */
80496 if( p->szMalloc>0 && p->z==p->zMalloc ){
80497 assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
80498 assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
80500 assert( p->z[p->n]==0 );
80501 assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );
80502 assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );
80504 if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;
80506 z = p->z;
80509 if( p->enc!=SQLITE_UTF8 ){
80511 if( p->enc==SQLITE_UTF16BE ) z++;
80528 ** routine is a no-op.
80542 if( !(pMem->flags&MEM_Str) ){
80543 pMem->enc = desiredEnc;
80546 if( pMem->enc==desiredEnc ){
80549 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
80559 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
80560 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
80566 ** Make sure pMem->z points to a writable allocation of at least n bytes.
80569 ** pMem->z into the new allocation. pMem must be either a string or
80571 ** in pMem->z is discarded.
80576 testcase( pMem->db==0 );
80580 assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
80581 testcase( bPreserve && pMem->z==0 );
80583 assert( pMem->szMalloc==0
80584 || (pMem->flags==MEM_Undefined
80585 && pMem->szMalloc<=sqlite3DbMallocSize(pMem->db,pMem->zMalloc))
80586 || pMem->szMalloc==sqlite3DbMallocSize(pMem->db,pMem->zMalloc));
80587 if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
80588 if( pMem->db ){
80589 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
80591 pMem->zMalloc = sqlite3Realloc(pMem->z, n);
80592 if( pMem->zMalloc==0 ) sqlite3_free(pMem->z);
80593 pMem->z = pMem->zMalloc;
80597 if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
80598 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
80600 if( pMem->zMalloc==0 ){
80602 pMem->z = 0;
80603 pMem->szMalloc = 0;
80606 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
80609 if( bPreserve && pMem->z ){
80610 assert( pMem->z!=pMem->zMalloc );
80611 memcpy(pMem->zMalloc, pMem->z, pMem->n);
80613 if( (pMem->flags&MEM_Dyn)!=0 ){
80614 assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
80615 pMem->xDel((void *)(pMem->z));
80618 pMem->z = pMem->zMalloc;
80619 pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
80624 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
80625 ** If pMem->zMalloc already meets or exceeds the requested size, this
80626 ** routine is a no-op.
80629 ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
80638 assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
80639 if( pMem->szMalloc<szNew ){
80642 assert( (pMem->flags & MEM_Dyn)==0 );
80643 pMem->z = pMem->zMalloc;
80644 pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);
80653 ** to be a double-zero byte at an even byte boundary in order to
80658 if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){
80661 pMem->z[pMem->n] = 0;
80662 pMem->z[pMem->n+1] = 0;
80663 pMem->z[pMem->n+2] = 0;
80664 pMem->flags |= MEM_Term;
80676 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
80678 if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
80680 if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
80685 pMem->flags &= ~MEM_Ephem;
80687 pMem->pScopyFrom = 0;
80694 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
80701 assert( pMem->flags & MEM_Zero );
80702 assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
80705 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
80708 nByte = pMem->n + pMem->u.nZero;
80710 if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
80716 assert( pMem->z!=0 );
80717 assert( sqlite3DbMallocSize(pMem->db,pMem->z) >= nByte );
80719 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
80720 pMem->n += pMem->u.nZero;
80721 pMem->flags &= ~(MEM_Zero|MEM_Term);
80731 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
80732 testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
80733 testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
80734 if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
80759 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
80760 assert( !(pMem->flags&MEM_Zero) );
80761 assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
80762 assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );
80768 pMem->enc = 0;
80772 vdbeMemRenderNum(nByte, pMem->z, pMem);
80773 assert( pMem->z!=0 );
80774 pMem->n = sqlite3Strlen30NN(pMem->z);
80775 pMem->enc = SQLITE_UTF8;
80776 pMem->flags |= MEM_Str|MEM_Term;
80777 if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
80795 assert( pMem->db!=0 );
80796 assert( pFunc->xFinalize!=0 );
80797 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
80798 assert( sqlite3_mutex_held(pMem->db->mutex) );
80802 t.db = pMem->db;
80807 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
80808 assert( (pMem->flags & MEM_Dyn)==0 );
80809 if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
80826 assert( pFunc->xValue!=0 );
80827 assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
80828 assert( pAccum->db!=0 );
80829 assert( sqlite3_mutex_held(pAccum->db->mutex) );
80835 ctx.enc = ENC(pAccum->db);
80836 pFunc->xValue(&ctx);
80851 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
80853 if( p->flags&MEM_Agg ){
80854 sqlite3VdbeMemFinalize(p, p->u.pDef);
80855 assert( (p->flags & MEM_Agg)==0 );
80856 testcase( p->flags & MEM_Dyn );
80858 if( p->flags&MEM_Dyn ){
80859 assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
80860 p->xDel((void *)p->z);
80862 p->flags = MEM_Null;
80867 ** by p->xDel and memory in p->zMalloc.
80877 if( p->szMalloc ){
80878 sqlite3DbFreeNN(p->db, p->zMalloc);
80879 p->szMalloc = 0;
80881 p->z = 0;
80896 if( VdbeMemDynamic(p) || p->szMalloc ){
80906 if( p->szMalloc ) vdbeMemClear(p);
80910 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
80911 ** If the double is out of range of a 64-bit signed integer then
80912 ** return the closest available 64-bit signed integer.
80916 /* When floating-point is omitted, double and int64 are the same thing */
80921 ** minimum and maximum 64-bit integers, or they define them
80924 ** larger than a 32-bit integer constant.
80943 ** a floating-point then the value returned is the integer part.
80946 ** an SQL-NULL value, return 0.
80952 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
80958 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
80960 flags = pMem->flags;
80963 return pMem->u.i;
80965 return doubleToInt64(pMem->u.r);
80966 }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){
80982 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
80987 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
80989 if( pMem->flags & MEM_Real ){
80990 return pMem->u.r;
80991 }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
80992 testcase( pMem->flags & MEM_IntReal );
80993 return (double)pMem->u.i;
80994 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
81007 testcase( pMem->flags & MEM_IntReal );
81008 if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;
81009 if( pMem->flags & MEM_Null ) return ifNull;
81020 assert( pMem->flags & MEM_Real );
81022 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
81025 ix = doubleToInt64(pMem->u.r);
81029 ** (1) the round-trip conversion real->int->real is a no-op, and
81037 if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
81038 pMem->u.i = ix;
81048 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
81052 pMem->u.i = sqlite3VdbeIntValue(pMem);
81063 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
81066 pMem->u.r = sqlite3VdbeRealValue(pMem);
81076 ** For some versions of GCC on 32-bit machines, if you do the more obvious
81078 ** though the r1 and (double)i values are bit-for-bit the same.
81084 && i >= -2251799813685248LL && i < 2251799813685248LL);
81107 testcase( pMem->flags & MEM_Int );
81108 testcase( pMem->flags & MEM_Real );
81109 testcase( pMem->flags & MEM_IntReal );
81110 testcase( pMem->flags & MEM_Null );
81111 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){
81114 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
81115 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
81116 rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
81117 if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)
81118 || sqlite3RealSameAsInt(pMem->u.r, (ix = sqlite3RealToI64(pMem->u.r)))
81120 pMem->u.i = ix;
81126 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );
81127 pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
81139 if( pMem->flags & MEM_Null ) return SQLITE_OK;
81142 if( (pMem->flags & MEM_Blob)==0 ){
81144 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
81145 if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
81147 pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
81166 pMem->flags |= (pMem->flags&MEM_Blob)>>3;
81168 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
81169 pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
81170 if( encoding!=SQLITE_UTF8 ) pMem->n &= ~1;
81184 pMem->flags = flags;
81185 pMem->db = db;
81186 pMem->szMalloc = 0;
81206 pMem->flags = MEM_Null;
81220 pMem->flags = MEM_Blob|MEM_Zero;
81221 pMem->n = 0;
81223 pMem->u.nZero = n;
81224 pMem->enc = SQLITE_UTF8;
81225 pMem->z = 0;
81233 assert( pMem->z!=0 );
81234 assert( sqlite3DbMallocSize(pMem->db, pMem->z)>=nByte );
81235 memset(pMem->z, 0, nByte);
81236 pMem->n = n>0?n:0;
81237 pMem->flags = MEM_Blob;
81238 pMem->enc = SQLITE_UTF8;
81246 ** a 64-bit integer.
81250 pMem->u.i = val;
81251 pMem->flags = MEM_Int;
81262 pMem->u.i = val;
81263 pMem->flags = MEM_Int;
81267 /* A no-op destructor */
81280 assert( pMem->flags==MEM_Null );
81282 pMem->u.zPType = zPType ? zPType : "";
81283 pMem->z = pPtr;
81284 pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
81285 pMem->eSubtype = 'p';
81286 pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
81297 pMem->u.r = val;
81298 pMem->flags = MEM_Real;
81309 return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
81310 && pMem->xDel==sqlite3RowSetDelete;
81322 sqlite3 *db = pMem->db;
81329 pMem->z = (char*)p;
81330 pMem->flags = MEM_Blob|MEM_Dyn;
81331 pMem->xDel = sqlite3RowSetDelete;
81337 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
81340 assert( p->db!=0 );
81341 if( p->flags & (MEM_Str|MEM_Blob) ){
81342 int n = p->n;
81343 if( p->flags & MEM_Zero ){
81344 n += p->u.nZero;
81346 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
81357 ** This is used for testing and debugging only - to help ensure that shallow
81363 for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){
81364 if( pX->pScopyFrom==pMem ){
81366 if( pVdbe->db->flags & SQLITE_VdbeTrace ){
81368 (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));
81376 mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
81377 assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
81380 ** undefined so that we can quickly detect the shallow-copy error */
81381 pX->flags = MEM_Undefined;
81382 pX->pScopyFrom = 0;
81385 pMem->pScopyFrom = 0;
81391 ** pTo are freed. The pFrom->z field is not duplicated. If
81392 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
81402 assert( pTo->db==pFrom->db );
81405 if( (pFrom->flags&MEM_Static)==0 ){
81406 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
81408 pTo->flags |= srcType;
81422 pTo->flags &= ~MEM_Dyn;
81423 if( pTo->flags&(MEM_Str|MEM_Blob) ){
81424 if( 0==(pFrom->flags&MEM_Static) ){
81425 pTo->flags |= MEM_Ephem;
81440 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
81441 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
81442 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
81446 pFrom->flags = MEM_Null;
81447 pFrom->szMalloc = 0;
81470 ** non-negative for blobs.
81479 i64 nByte = n; /* New value for pMem->n */
81481 u16 flags; /* New value for pMem->flags */
81484 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
81494 if( pMem->db ){
81495 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
81516 sqlite3DbFree(pMem->db, (void*)z);
81522 return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
81540 memcpy(pMem->z, z, nAlloc);
81543 pMem->z = (char *)z;
81545 pMem->zMalloc = pMem->z;
81546 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
81548 pMem->xDel = xDel;
81553 pMem->n = (int)(nByte & 0x7fffffff);
81554 pMem->flags = flags;
81555 pMem->enc = enc;
81574 ** pMem->zMalloc to hold the content from the btree, if possible. New
81575 ** pMem->zMalloc space will be allocated if necessary. The calling routine
81589 pMem->flags = MEM_Null;
81594 rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
81596 pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
81597 pMem->flags = MEM_Blob;
81598 pMem->n = (int)amt;
81619 pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);
81620 assert( pMem->z!=0 );
81623 pMem->flags = MEM_Blob|MEM_Ephem;
81624 pMem->n = (int)amt;
81635 ** to a zero-terminated version of that string.
81639 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
81642 assert( (pVal->flags & (MEM_Null))==0 );
81643 if( pVal->flags & (MEM_Blob|MEM_Str) ){
81645 pVal->flags |= MEM_Str;
81646 if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
81649 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
81650 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
81655 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
81658 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
81660 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
81661 || pVal->db->mallocFailed );
81662 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
81664 return pVal->z;
81676 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
81682 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
81685 if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
81687 return pVal->z;
81689 if( pVal->flags&MEM_Null ){
81701 p->flags = MEM_Null;
81702 p->db = db;
81723 ** Otherwise, if the second argument is non-zero, then this function is
81732 UnpackedRecord *pRec = p->ppRec[0];
81735 Index *pIdx = p->pIdx; /* Index being probed */
81738 int nCol = pIdx->nColumn; /* Number of index columns including rowid */
81743 pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
81744 if( pRec->pKeyInfo ){
81745 assert( pRec->pKeyInfo->nAllField==nCol );
81746 assert( pRec->pKeyInfo->enc==ENC(db) );
81747 pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
81749 pRec->aMem[i].flags = MEM_Null;
81750 pRec->aMem[i].db = db;
81758 p->ppRec[0] = pRec;
81761 pRec->nField = p->iVal+1;
81762 return &pRec->aMem[p->iVal];
81809 assert( (p->flags & EP_TokenOnly)==0 );
81811 pList = p->x.pList;
81812 if( pList ) nVal = pList->nExpr;
81814 pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
81816 if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
81817 || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
81829 rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
81840 testcase( pCtx->pParse->rc==SQLITE_ERROR );
81841 testcase( pCtx->pParse->rc==SQLITE_OK );
81846 pFunc->xSFunc(&ctx, nVal, apVal);
81849 sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
81856 pCtx->pParse->nErr++;
81859 pCtx->pParse->rc = rc;
81905 while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
81906 if( op==TK_REGISTER ) op = pExpr->op2;
81912 assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
81917 aff = sqlite3AffinityType(pExpr->u.zToken,0);
81918 rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
81928 ** case when the value is -9223372036854775808.
81931 && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
81932 pExpr = pExpr->pLeft;
81933 op = pExpr->op;
81934 negInt = -1;
81935 zNeg = "-";
81942 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
81944 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
81946 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
81953 assert( (pVal->flags & MEM_IntReal)==0 );
81954 if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
81955 testcase( pVal->flags & MEM_Int );
81956 testcase( pVal->flags & MEM_Real );
81957 pVal->flags &= ~MEM_Str;
81963 /* This branch happens for multiple negative signs. Ex: -(-5) */
81964 if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
81968 if( pVal->flags & MEM_Real ){
81969 pVal->u.r = -pVal->u.r;
81970 }else if( pVal->u.i==SMALLEST_INT64 ){
81972 pVal->u.r = -(double)SMALLEST_INT64;
81974 pVal->u.r = LARGEST_INT64;
81978 pVal->u.i = -pVal->u.i;
81991 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
81992 assert( pExpr->u.zToken[1]=='\'' );
81995 zVal = &pExpr->u.zToken[2];
81996 nVal = sqlite3Strlen30(zVal)-1;
82011 pVal->flags = MEM_Int;
82012 pVal->u.i = pExpr->u.zToken[4]==0;
82021 if( pCtx==0 || NEVER(pCtx->pParse->nErr==0) )
82082 sqlite3 *db = pParse->db;
82087 assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
82093 }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
82095 int iBindVar = pExpr->iColumn;
82096 sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
82097 if( (v = pParse->pReprepare)!=0 ){
82100 rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
82102 pVal->db = pParse->db;
82109 assert( pVal==0 || pVal->db==db );
82160 if( pExpr==0 || pExpr->op!=TK_SELECT ){
82171 u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
82203 ** Extract the iCol-th column from the nRec-byte record in pRec. Write
82245 sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
82246 pMem->enc = ENC(db);
82258 int nCol = pRec->pKeyInfo->nAllField;
82259 Mem *aMem = pRec->aMem;
82264 sqlite3KeyInfoUnref(pRec->pKeyInfo);
82289 sqlite3DbFreeNN(((Mem*)v)->db, v);
82298 return valueToText(pVal, enc)!=0 ? pVal->n : 0;
82302 assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
82303 if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
82304 return p->n;
82306 if( (p->flags & MEM_Str)!=0 && enc!=SQLITE_UTF8 && pVal->enc!=SQLITE_UTF8 ){
82307 return p->n;
82309 if( (p->flags & MEM_Blob)!=0 ){
82310 if( p->flags & MEM_Zero ){
82311 return p->n + p->u.nZero;
82313 return p->n;
82316 if( p->flags & MEM_Null ) return 0;
82325 ** The author disclaims copyright to this source code. In place of
82347 sqlite3 *db = pParse->db;
82351 memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
82352 p->db = db;
82353 if( db->pVdbe ){
82354 db->pVdbe->ppVPrev = &p->pVNext;
82356 p->pVNext = db->pVdbe;
82357 p->ppVPrev = &db->pVdbe;
82358 db->pVdbe = p;
82359 assert( p->eVdbeState==VDBE_INIT_STATE );
82360 p->pParse = pParse;
82361 pParse->pVdbe = p;
82362 assert( pParse->aLabel==0 );
82363 assert( pParse->nLabel==0 );
82364 assert( p->nOpAlloc==0 );
82365 assert( pParse->szOpAlloc==0 );
82374 return p->pParse;
82382 sqlite3DbFree(p->db, p->zErrMsg);
82384 p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
82393 p->prepFlags = prepFlags;
82395 p->expmask = 0;
82397 assert( p->zSql==0 );
82398 p->zSql = sqlite3DbStrNDup(p->db, z, n);
82403 ** Add a new element to the Vdbe->pDblStr list.
82409 sizeof(*pStr)+n+1-sizeof(pStr->z));
82411 pStr->pNextStr = p->pDblStr;
82412 p->pDblStr = pStr;
82413 memcpy(pStr->z, z, n+1);
82421 ** zId of length nId is a double-quoted identifier. Check to see if
82426 const char *zId /* The double-quoted identifier, already dequoted */
82430 if( pVdbe->pDblStr==0 ) return 0;
82431 for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
82432 if( strcmp(zId, pStr->z)==0 ) return 1;
82439 ** Swap byte-code between two VDBE structures.
82451 assert( pA->db==pB->db );
82455 pTmp = pA->pVNext;
82456 pA->pVNext = pB->pVNext;
82457 pB->pVNext = pTmp;
82458 ppTmp = pA->ppVPrev;
82459 pA->ppVPrev = pB->ppVPrev;
82460 pB->ppVPrev = ppTmp;
82461 zTmp = pA->zSql;
82462 pA->zSql = pB->zSql;
82463 pB->zSql = zTmp;
82465 zTmp = pA->zNormSql;
82466 pA->zNormSql = pB->zNormSql;
82467 pB->zNormSql = zTmp;
82469 pB->expmask = pA->expmask;
82470 pB->prepFlags = pA->prepFlags;
82471 memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
82472 pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
82480 ** If an out-of-memory error occurs while resizing the array, return
82487 Parse *p = v->pParse;
82489 /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
82497 sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
82498 : (sqlite3_int64)v->nOpAlloc+nOp);
82500 sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
82506 if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
82507 sqlite3OomFault(p->db);
82512 assert( nNew>=(v->nOpAlloc+nOp) );
82513 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
82515 p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
82516 v->nOpAlloc = p->szOpAlloc/sizeof(Op);
82517 v->aOp = pNew;
82557 assert( p->nOpAlloc<=p->nOp );
82559 assert( p->nOpAlloc>p->nOp );
82566 i = p->nOp;
82567 assert( p->eVdbeState==VDBE_INIT_STATE );
82569 if( p->nOpAlloc<=i ){
82572 assert( p->aOp!=0 );
82573 p->nOp++;
82574 pOp = &p->aOp[i];
82576 pOp->opcode = (u8)op;
82577 pOp->p5 = 0;
82578 pOp->p1 = p1;
82579 pOp->p2 = p2;
82580 pOp->p3 = p3;
82581 pOp->p4.p = 0;
82582 pOp->p4type = P4_NOTUSED;
82584 pOp->zComment = 0;
82587 if( p->db->flags & SQLITE_VdbeAddopTrace ){
82588 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
82589 test_addop_breakpoint(i, &p->aOp[i]);
82593 pOp->cycles = 0;
82594 pOp->cnt = 0;
82597 pOp->iSrcLine = 0;
82691 Vdbe *v = pParse->pVdbe;
82696 nByte = sizeof(*pCtx) + (nArg-1)*sizeof(sqlite3_value*);
82697 pCtx = sqlite3DbMallocRawNN(pParse->db, nByte);
82699 assert( pParse->db->mallocFailed );
82700 freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
82703 pCtx->pOut = 0;
82704 pCtx->pFunc = (FuncDef*)pFunc;
82705 pCtx->pVdbe = 0;
82706 pCtx->isError = 0;
82707 pCtx->argc = nArg;
82708 pCtx->iOp = sqlite3VdbeCurrentAddr(v);
82741 if( pParse->addrExplain==0 ) return 0;
82742 pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
82743 return pOp->p2;
82767 if( pParse->explain==2 )
82775 zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
82777 v = pParse->pVdbe;
82778 iThis = v->nOp;
82779 sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
82781 sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetLastOp(v)->p4.z);
82783 pParse->addrExplain = iThis;
82793 pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
82809 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
82810 sqlite3MayAbort(p->pParse);
82825 if( p->db->mallocFailed==0 ){
82826 VdbeOp *pOp = &p->aOp[addr];
82827 pOp->p4type = P4_INT32;
82828 pOp->p4.i = p4;
82833 /* Insert the end of a co-routine
82839 ** co-routine has its own independent set of registers, because co-routines
82841 ** that could cause problems if two or more co-routines are using the same
82844 v->pParse->nTempReg = 0;
82845 v->pParse->nRangeReg = 0;
82857 ** always negative and P2 values are suppose to be non-negative.
82864 ** Parse.aLabel[x] Stores the address that the x-th label resolves
82866 ** labels stores -1, but that is not required.
82874 return --pParse->nLabel;
82883 int nNewSize = 10 - p->nLabel;
82884 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
82885 nNewSize*sizeof(p->aLabel[0]));
82886 if( p->aLabel==0 ){
82887 p->nLabelAlloc = 0;
82891 for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
82893 p->nLabelAlloc = nNewSize;
82894 p->aLabel[j] = v->nOp;
82898 Parse *p = v->pParse;
82900 assert( v->eVdbeState==VDBE_INIT_STATE );
82901 assert( j<-p->nLabel );
82904 if( p->db->flags & SQLITE_VdbeAddopTrace ){
82905 printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
82908 if( p->nLabelAlloc + p->nLabel < 0 ){
82911 assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
82912 p->aLabel[j] = v->nOp;
82928 for(i=1; ALWAYS(i<p->nOp); i++){
82929 if( ALWAYS(p->aOp[i].opcode==OP_Expire) ){
82930 p->aOp[1].opcode = OP_Noop;
82940 ** in a Vdbe main program and each of the sub-programs (triggers) it may
82951 ** sqlite3DbFree(v->db, sIter.apSub);
82960 int iSub; /* 0 = main program, 1 = first sub-program etc. */
82963 Vdbe *v = p->v;
82968 if( p->iSub<=p->nSub ){
82970 if( p->iSub==0 ){
82971 aOp = v->aOp;
82972 nOp = v->nOp;
82974 aOp = p->apSub[p->iSub-1]->aOp;
82975 nOp = p->apSub[p->iSub-1]->nOp;
82977 assert( p->iAddr<nOp );
82979 pRet = &aOp[p->iAddr];
82980 p->iAddr++;
82981 if( p->iAddr==nOp ){
82982 p->iSub++;
82983 p->iAddr = 0;
82986 if( pRet->p4type==P4_SUBPROGRAM ){
82987 int nByte = (p->nSub+1)*sizeof(SubProgram*);
82989 for(j=0; j<p->nSub; j++){
82990 if( p->apSub[j]==pRet->p4.pProgram ) break;
82992 if( j==p->nSub ){
82993 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
82994 if( !p->apSub ){
82997 p->apSub[p->nSub++] = pRet->p4.pProgram;
83010 ** sub-programs contains any of the following:
83027 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
83043 int opcode = pOp->opcode;
83050 && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
83055 if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
83059 ** where a "DELETE FROM tbl" has a statement-journal but does not
83060 ** require one. This is not so bad - it is an inefficiency, not a bug. */
83061 if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
83066 if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
83071 sqlite3DbFree(v->db, sIter.apSub);
83078 return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
83082 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
83091 || (pC->eCurType!=CURTYPE_SORTER
83092 && pC->eCurType!=CURTYPE_PSEUDO
83093 && !pC->isEphemeral)
83095 p->nWrite++;
83106 assert( p->nWrite==0 || p->usesStmtJournal );
83134 Parse *pParse = p->pParse;
83135 int *aLabel = pParse->aLabel;
83136 p->readOnly = 1;
83137 p->bIsReader = 0;
83138 pOp = &p->aOp[p->nOp-1];
83139 assert( p->aOp[0].opcode==OP_Init );
83147 if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
83150 switch( pOp->opcode ){
83152 if( pOp->p2!=0 ) p->readOnly = 0;
83157 p->bIsReader = 1;
83165 p->readOnly = 0;
83166 p->bIsReader = 1;
83170 assert( pOp->p2>=0 );
83175 if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
83180 assert( (pOp - p->aOp) >= 3 );
83181 assert( pOp[-1].opcode==OP_Integer );
83182 n = pOp[-1].p1;
83189 if( pOp->p2<0 ){
83191 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
83192 ** have non-negative values for P2. */
83193 assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
83194 assert( ADDR(pOp->p2)<-pParse->nLabel );
83195 pOp->p2 = aLabel[ADDR(pOp->p2)];
83201 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
83202 ** have non-negative values for P2. */
83203 assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
83205 assert( pOp>p->aOp );
83206 pOp--;
83210 sqlite3DbNNFreeNN(p->db, pParse->aLabel);
83211 pParse->aLabel = 0;
83213 pParse->nLabel = 0;
83215 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
83240 Vdbe *v, /* The byte-code program under construction */
83250 pParse = v->pParse;
83252 if( pParse->nErr ) return;
83254 assert( iLast<v->nOp );
83255 pOp = &v->aOp[iFirst];
83257 if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 ){
83258 int iDest = pOp->p2; /* Jump destination */
83260 if( pOp->opcode==OP_Gosub ) continue;
83264 if( j>=-pParse->nLabel || pParse->aLabel[j]<0 ){
83267 iDest = pParse->aLabel[j];
83271 for(; j<v->nOp; j++){
83272 VdbeOp *pX = &v->aOp[j];
83273 if( pX->opcode==OP_Return ){
83274 if( pX->p1==iRetReg ) break;
83277 if( pX->opcode==OP_Noop ) continue;
83278 if( pX->opcode==OP_Explain ) continue;
83306 assert( p->eVdbeState==VDBE_INIT_STATE );
83307 return p->nOp;
83316 ** sqlite3VdbeAddOpList() will always be non-NULL.
83320 assert( p->nOp + N <= p->nOpAlloc );
83334 for(i=0; i<p->nOp; i++){
83335 assert( p->aOp[i].opcode!=OP_ResultRow );
83363 VdbeOp *aOp = p->aOp;
83364 assert( aOp && !p->db->mallocFailed );
83367 assert( DbMaskAllZero(p->btreeMask) );
83370 *pnOp = p->nOp;
83371 p->aOp = 0;
83379 ** Non-zero P2 arguments to jump instructions are automatically adjusted
83386 int iLineno /* Source-file line number of first opcode */
83391 assert( p->eVdbeState==VDBE_INIT_STATE );
83392 if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
83395 pFirst = pOut = &p->aOp[p->nOp];
83397 pOut->opcode = aOp->opcode;
83398 pOut->p1 = aOp->p1;
83399 pOut->p2 = aOp->p2;
83400 assert( aOp->p2>=0 );
83401 if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
83402 pOut->p2 += p->nOp;
83404 pOut->p3 = aOp->p3;
83405 pOut->p4type = P4_NOTUSED;
83406 pOut->p4.p = 0;
83407 pOut->p5 = 0;
83409 pOut->zComment = 0;
83412 pOut->iSrcLine = iLineno+i;
83417 if( p->db->flags & SQLITE_VdbeAddopTrace ){
83418 sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
83422 p->nOp += nOp;
83438 sqlite3_int64 nByte = (p->nScan+1) * sizeof(ScanStatus);
83440 aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
83442 ScanStatus *pNew = &aNew[p->nScan++];
83443 pNew->addrExplain = addrExplain;
83444 pNew->addrLoop = addrLoop;
83445 pNew->addrVisit = addrVisit;
83446 pNew->nEst = nEst;
83447 pNew->zName = sqlite3DbStrDup(p->db, zName);
83448 p->aScan = aNew;
83460 sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
83464 sqlite3VdbeGetOp(p,addr)->p1 = val;
83467 assert( addr>=0 || p->db->mallocFailed );
83468 sqlite3VdbeGetOp(p,addr)->p2 = val;
83472 sqlite3VdbeGetOp(p,addr)->p3 = val;
83475 assert( p->nOp>0 || p->db->mallocFailed );
83476 if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
83486 if( pOp->p3==iDest && pOp->opcode==OP_Column ){
83487 pOp->p5 |= OPFLAG_TYPEOFARG;
83496 sqlite3VdbeChangeP2(p, addr, p->nOp);
83502 ** the previous opcode (and is thus a no-op) then simply back up
83507 ** strives to omit useless byte-code like this:
83513 if( addr==p->nOp-1 ){
83514 assert( p->aOp[addr].opcode==OP_Once
83515 || p->aOp[addr].opcode==OP_If
83516 || p->aOp[addr].opcode==OP_FkIfZero );
83517 assert( p->aOp[addr].p4type==0 );
83519 sqlite3VdbeGetLastOp(p)->iSrcLine = 0; /* Erase VdbeCoverage() macros */
83521 p->nOp--;
83523 sqlite3VdbeChangeP2(p, addr, p->nOp);
83534 if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
83543 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
83548 freeEphemeralFunction(db, p->pFunc);
83566 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
83580 if( db->pnBytesFreed==0 ){
83588 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
83603 Op *pOp = &aOp[nOp-1];
83605 if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
83607 sqlite3DbFree(db, pOp->zComment);
83610 pOp--;
83618 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
83622 p->pNext = pVdbe->pProgram;
83623 pVdbe->pProgram = p;
83630 return pVdbe->pProgram!=0;
83638 if( p->db->mallocFailed ) return 0;
83639 assert( addr>=0 && addr<p->nOp );
83640 pOp = &p->aOp[addr];
83641 freeP4(p->db, pOp->p4type, pOp->p4.p);
83642 pOp->p4type = P4_NOTUSED;
83643 pOp->p4.z = 0;
83644 pOp->opcode = OP_Noop;
83653 if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
83654 return sqlite3VdbeChangeToNoop(p, p->nOp-1);
83672 if( N==0 || OptimizationDisabled(pParse->db, SQLITE_ReleaseReg) ) return;
83673 assert( pParse->pVdbe );
83675 assert( iFirst+N-1<=pParse->nMem );
83680 N--;
83682 while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){
83683 mask &= ~MASKBIT32(N-1);
83684 N--;
83688 sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);
83689 if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);
83718 if( pOp->p4type ){
83719 freeP4(p->db, pOp->p4type, pOp->p4.p);
83720 pOp->p4type = 0;
83721 pOp->p4.p = 0;
83724 sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
83727 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
83728 pOp->p4type = P4_DYNAMIC;
83735 db = p->db;
83736 assert( p->eVdbeState==VDBE_INIT_STATE );
83737 assert( p->aOp!=0 || db->mallocFailed );
83738 if( db->mallocFailed ){
83742 assert( p->nOp>0 );
83743 assert( addr<p->nOp );
83745 addr = p->nOp - 1;
83747 pOp = &p->aOp[addr];
83748 if( n>=0 || pOp->p4type ){
83755 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
83756 pOp->p4type = P4_INT32;
83759 pOp->p4.p = (void*)zP4;
83760 pOp->p4type = (signed char)n;
83767 ** to the value defined by the arguments. This is a high-speed
83778 if( p->db->mallocFailed ){
83779 freeP4(p->db, n, pP4);
83782 assert( p->nOp>0 );
83783 pOp = &p->aOp[p->nOp-1];
83784 assert( pOp->p4type==P4_NOTUSED );
83785 pOp->p4type = n;
83786 pOp->p4.p = pP4;
83795 Vdbe *v = pParse->pVdbe;
83806 ** insert a No-op and add the comment to that new instruction. This
83811 assert( p->nOp>0 || p->aOp==0 );
83812 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->pParse->nErr>0 );
83813 if( p->nOp ){
83814 assert( p->aOp );
83815 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
83816 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
83843 sqlite3VdbeGetLastOp(v)->iSrcLine = iLine;
83848 ** Return the opcode for a given address. The address must be non-negative.
83864 assert( p->eVdbeState==VDBE_INIT_STATE );
83865 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
83866 if( p->db->mallocFailed ){
83869 return &p->aOp[addr];
83876 return sqlite3VdbeGetOp(p, p->nOp - 1);
83885 if( c=='1' ) return pOp->p1;
83886 if( c=='2' ) return pOp->p2;
83887 if( c=='3' ) return pOp->p3;
83888 if( c=='4' ) return pOp->p4.i;
83889 return pOp->p5;
83895 ** The Synopsis: field in comments in the vdbe.c source file gets converted
83900 ** "PX" -> "r[X]"
83901 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
83902 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
83903 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
83906 sqlite3 *db, /* Optional - Oom error reporting only */
83918 zOpName = sqlite3OpcodeName(pOp->opcode);
83934 if( pOp->zComment && pOp->zComment[0] ){
83935 sqlite3_str_appendall(&x, pOp->zComment);
83952 sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1);
83955 sqlite3_context *pCtx = pOp->p4.pCtx;
83956 if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){
83958 }else if( pCtx->argc>1 ){
83959 sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1);
83962 x.nChar -= 2;
83968 if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
83977 if( !seenCom && pOp->zComment ){
83978 sqlite3_str_appendf(&x, "; %s", pOp->zComment);
83980 }else if( pOp->zComment ){
83981 sqlite3_str_appendall(&x, pOp->zComment);
83997 switch( pExpr->op ){
84000 sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
84003 sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
84009 sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
84013 if( pExpr->iColumn<0 ){
84016 sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
84054 displayP4Expr(p, pExpr->pLeft);
84055 if( pExpr->pRight ){
84057 displayP4Expr(p, pExpr->pRight);
84075 switch( pOp->p4type ){
84078 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
84079 assert( pKeyInfo->aSortFlags!=0 );
84080 sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
84081 for(j=0; j<pKeyInfo->nKeyField; j++){
84082 CollSeq *pColl = pKeyInfo->aColl[j];
84083 const char *zColl = pColl ? pColl->zName : "";
84086 (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
84087 (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
84095 displayP4Expr(&x, pOp->p4.pExpr);
84101 CollSeq *pColl = pOp->p4.pColl;
84102 assert( pColl->enc<4 );
84103 sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
84104 encnames[pColl->enc]);
84108 FuncDef *pDef = pOp->p4.pFunc;
84109 sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
84113 FuncDef *pDef = pOp->p4.pCtx->pFunc;
84114 sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
84118 sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
84122 sqlite3_str_appendf(&x, "%d", pOp->p4.i);
84126 sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
84130 Mem *pMem = pOp->p4.pMem;
84131 if( pMem->flags & MEM_Str ){
84132 zP4 = pMem->z;
84133 }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
84134 sqlite3_str_appendf(&x, "%lld", pMem->u.i);
84135 }else if( pMem->flags & MEM_Real ){
84136 sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
84137 }else if( pMem->flags & MEM_Null ){
84140 assert( pMem->flags & MEM_Blob );
84147 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
84154 u32 *ai = pOp->p4.ai;
84168 zP4 = pOp->p4.pTab->zName;
84172 zP4 = pOp->p4.z;
84184 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
84188 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
84189 ** p->btreeMask of databases that will require a lock.
84192 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
84193 assert( i<(int)sizeof(p->btreeMask)*8 );
84194 DbMaskSet(p->btreeMask, i);
84195 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
84196 DbMaskSet(p->lockMask, i);
84202 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
84206 ** that the correct busy-handler callback is invoked if required.
84208 ** If SQLite is not threadsafe but does support shared-cache mode, then
84213 ** If SQLite is not threadsafe and does not support shared-cache mode, this
84214 ** function is a no-op.
84216 ** The p->btreeMask field is a bitmask of all btrees that the prepared
84217 ** statement p will ever use. Let N be the number of bits in p->btreeMask
84227 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
84228 db = p->db;
84229 aDb = db->aDb;
84230 nDb = db->nDb;
84232 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
84248 db = p->db;
84249 aDb = db->aDb;
84250 nDb = db->nDb;
84252 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
84258 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
84271 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
84283 ** information from the vdbe.c source text */
84285 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3,
84286 zP4 ? zP4 : "", pOp->p5,
84299 ** This is a high-runner, so only those fields that really do need to
84314 p->flags = flags;
84315 p->db = db;
84316 p->szMalloc = 0;
84318 p->pScopyFrom = 0;
84321 }while( (--N)>0 );
84336 sqlite3 *db = p->db;
84337 if( db->pnBytesFreed ){
84339 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
84353 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
84354 ** sqlite3MemRelease() were called from here. With -O2, this jumps
84359 testcase( p->flags & MEM_Agg );
84360 testcase( p->flags & MEM_Dyn );
84361 if( p->flags&(MEM_Agg|MEM_Dyn) ){
84362 testcase( (p->flags & MEM_Dyn)!=0 && p->xDel==sqlite3VdbeFrameMemDel );
84364 p->flags = MEM_Undefined;
84365 }else if( p->szMalloc ){
84366 sqlite3DbNNFreeNN(db, p->zMalloc);
84367 p->szMalloc = 0;
84368 p->flags = MEM_Undefined;
84372 p->flags = MEM_Undefined;
84387 if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
84403 pFrame->pParent = pFrame->v->pDelFrame;
84404 pFrame->v->pDelFrame = pFrame;
84424 int nSub = 0; /* Number of sub-vdbes seen so far */
84425 SubProgram **apSub = 0; /* Array of sub-vdbes */
84436 ** encountered, but p->pc will eventually catch up to nRow.
84438 nRow = p->nOp;
84440 if( pSub->flags&MEM_Blob ){
84443 nSub = pSub->n/sizeof(Vdbe*);
84444 apSub = (SubProgram **)pSub->z;
84447 nRow += apSub[i]->nOp;
84454 p->rc = SQLITE_OK;
84458 if( i<p->nOp ){
84461 aOp = p->aOp;
84466 i -= p->nOp;
84469 for(j=0; i>=apSub[j]->nOp; j++){
84470 i -= apSub[j]->nOp;
84471 assert( i<apSub[j]->nOp || j+1<nSub );
84473 aOp = apSub[j]->aOp;
84478 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
84488 p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
84489 if( p->rc!=SQLITE_OK ){
84493 apSub = (SubProgram **)pSub->z;
84496 pSub->n = nSub*sizeof(SubProgram*);
84497 nRow += aOp[i].p4.pProgram->nOp;
84504 if( pOp->opcode==OP_OpenRead ) break;
84505 if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
84506 if( pOp->opcode==OP_ReopenIdx ) break;
84530 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
84532 for(i=0; i<p->nChildCsr; i++){
84533 if( apCsr[i] ) sqlite3VdbeFreeCursorNN(p->v, apCsr[i]);
84535 releaseMemArray(aMem, p->nChildMem);
84536 sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
84537 sqlite3DbFree(p->v->db, p);
84548 ** When p->explain==1, each instruction is listed. When
84549 ** p->explain==2, only OP_Explain instructions are listed and these
84550 ** are shown in a different format. p->explain==2 is used to implement
84552 ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
84556 ** When p->explain==1, first the main program is listed, then each of
84563 sqlite3 *db = p->db; /* The database connection */
84566 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
84567 int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
84571 assert( p->explain );
84572 assert( p->eVdbeState==VDBE_RUN_STATE );
84573 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
84577 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
84580 p->pResultSet = 0;
84582 if( p->rc==SQLITE_NOMEM ){
84594 assert( p->nMem>9 );
84595 pSub = &p->aMem[9];
84601 rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);
84605 if( AtomicLoad(&db->u1.isInterrupted) ){
84606 p->rc = SQLITE_INTERRUPT;
84608 sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
84611 if( p->explain==2 ){
84612 sqlite3VdbeMemSetInt64(pMem, pOp->p1);
84613 sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);
84614 sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);
84615 sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);
84616 p->nResColumn = 4;
84619 sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),
84620 -1, SQLITE_UTF8, SQLITE_STATIC);
84621 sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);
84622 sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);
84623 sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);
84625 sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);
84629 sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);
84634 sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);
84635 p->nResColumn = 8;
84637 p->pResultSet = pMem;
84638 if( db->mallocFailed ){
84639 p->rc = SQLITE_NOMEM;
84642 p->rc = SQLITE_OK;
84657 if( p->zSql ){
84658 z = p->zSql;
84659 }else if( p->nOp>=1 ){
84660 const VdbeOp *pOp = &p->aOp[0];
84661 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
84662 z = pOp->p4.z;
84675 int nOp = p->nOp;
84679 pOp = &p->aOp[0];
84680 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
84683 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
84687 if( z[i-1]!=' ' ){
84710 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
84729 assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
84732 if( nByte <= p->nFree ){
84733 p->nFree -= nByte;
84734 pBuf = &p->pSpace[p->nFree];
84736 p->nNeeded += nByte;
84752 assert( p->eVdbeState==VDBE_INIT_STATE
84753 || p->eVdbeState==VDBE_READY_STATE
84754 || p->eVdbeState==VDBE_HALT_STATE );
84758 assert( p->nOp>0 );
84760 p->eVdbeState = VDBE_READY_STATE;
84763 for(i=0; i<p->nMem; i++){
84764 assert( p->aMem[i].db==p->db );
84767 p->pc = -1;
84768 p->rc = SQLITE_OK;
84769 p->errorAction = OE_Abort;
84770 p->nChange = 0;
84771 p->cacheCtr = 1;
84772 p->minWriteFileFormat = 255;
84773 p->iStatement = 0;
84774 p->nFkConstraint = 0;
84776 for(i=0; i<p->nOp; i++){
84777 p->aOp[i].cnt = 0;
84778 p->aOp[i].cycles = 0;
84814 assert( p->nOp>0 );
84816 assert( p->eVdbeState==VDBE_INIT_STATE );
84817 assert( pParse==p->pParse );
84818 p->pVList = pParse->pVList;
84819 pParse->pVList = 0;
84820 db = p->db;
84821 assert( db->mallocFailed==0 );
84822 nVar = pParse->nVar;
84823 nMem = pParse->nMem;
84824 nCursor = pParse->nTab;
84825 nArg = pParse->nMaxArg;
84839 n = ROUND8P(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
84840 x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
84842 x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
84847 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
84848 if( pParse->explain ){
84855 p->explain = pParse->explain;
84856 if( pParse->explain==2 ){
84866 sqlite3VdbeSetColName(p, i-iFirst, COLNAME_NAME,
84870 p->expired = 0;
84878 ** This two-pass approach that reuses as much memory as possible from
84883 p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
84884 p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
84885 p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
84886 p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
84888 p->anExec = allocSpace(&x, 0, p->nOp*sizeof(i64));
84891 x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
84893 if( !db->mallocFailed ){
84894 p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
84895 p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
84896 p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
84897 p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
84899 p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
84904 if( db->mallocFailed ){
84905 p->nVar = 0;
84906 p->nCursor = 0;
84907 p->nMem = 0;
84909 p->nCursor = nCursor;
84910 p->nVar = (ynVar)nVar;
84911 initMemArray(p->aVar, nVar, db, MEM_Null);
84912 p->nMem = nMem;
84913 initMemArray(p->aMem, nMem, db, MEM_Undefined);
84914 memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
84916 memset(p->anExec, 0, p->nOp*sizeof(i64));
84930 switch( pCx->eCurType ){
84932 sqlite3VdbeSorterClose(p->db, pCx);
84936 assert( pCx->uc.pCursor!=0 );
84937 sqlite3BtreeCloseCursor(pCx->uc.pCursor);
84942 sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
84943 const sqlite3_module *pModule = pVCur->pVtab->pModule;
84944 assert( pVCur->pVtab->nRef>0 );
84945 pVCur->pVtab->nRef--;
84946 pModule->xClose(pVCur);
84958 for(i=0; i<p->nCursor; i++){
84959 VdbeCursor *pC = p->apCsr[i];
84962 p->apCsr[i] = 0;
84969 ** is used, for example, when a trigger sub-program is halted to restore
84973 Vdbe *v = pFrame->v;
84976 v->anExec = pFrame->anExec;
84978 v->aOp = pFrame->aOp;
84979 v->nOp = pFrame->nOp;
84980 v->aMem = pFrame->aMem;
84981 v->nMem = pFrame->nMem;
84982 v->apCsr = pFrame->apCsr;
84983 v->nCursor = pFrame->nCursor;
84984 v->db->lastRowid = pFrame->lastRowid;
84985 v->nChange = pFrame->nChange;
84986 v->db->nChange = pFrame->nDbChange;
84987 sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
84988 v->pAuxData = pFrame->pAuxData;
84989 pFrame->pAuxData = 0;
84990 return pFrame->pc;
85002 if( p->pFrame ){
85004 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
85006 p->pFrame = 0;
85007 p->nFrame = 0;
85009 assert( p->nFrame==0 );
85011 releaseMemArray(p->aMem, p->nMem);
85012 while( p->pDelFrame ){
85013 VdbeFrame *pDel = p->pDelFrame;
85014 p->pDelFrame = pDel->pParent;
85019 if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
85020 assert( p->pAuxData==0 );
85031 sqlite3 *db = p->db;
85033 if( p->nResColumn ){
85034 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
85035 sqlite3DbFree(db, p->aColName);
85038 p->nResColumn = (u16)nResColumn;
85039 p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
85040 if( p->aColName==0 ) return;
85041 initMemArray(p->aColName, n, db, MEM_Null);
85063 assert( idx<p->nResColumn );
85065 if( p->db->mallocFailed ){
85069 assert( p->aColName!=0 );
85070 pColName = &(p->aColName[idx+var*p->nResColumn]);
85071 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
85072 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
85079 ** write-transaction spanning more than one database file, this routine
85080 ** takes care of the super-journal trickery.
85084 int nTrans = 0; /* Number of databases with an active write-transaction
85085 ** that are candidates for a two-phase commit using a
85086 ** super-journal */
85099 ** be done before determining whether a super-journal file is
85108 ** one database file has an open write transaction, a super-journal
85111 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
85112 Btree *pBt = db->aDb[i].pBt;
85114 /* Whether or not a database might need a super-journal depends upon
85116 ** journal modes use a super-journal and which do not */
85129 if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
85144 /* If there are any write-transactions at all, invoke the commit hook */
85145 if( needXcommit && db->xCommitCallback ){
85146 rc = db->xCommitCallback(db->pCommitArg);
85152 /* The simple case - no more than one database file (not counting the
85154 ** super-journal.
85158 ** that case we do not support atomic multi-file commits, so use the
85161 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
85164 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
85165 Btree *pBt = db->aDb[i].pBt;
85176 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
85177 Btree *pBt = db->aDb[i].pBt;
85187 /* The complex case - There is a multi-file write-transaction active.
85188 ** This requires a super-journal file to ensure the transaction is
85193 sqlite3_vfs *pVfs = db->pVfs;
85194 char *zSuper = 0; /* File-name for the super-journal */
85195 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
85202 /* Select a super-journal file name */
85220 sqlite3_snprintf(13, &zSuper[nMainFile], "-mj%06X9%02X",
85222 /* The antipenultimate character of the super-journal name must
85224 assert( zSuper[sqlite3Strlen30(zSuper)-3]=='9' );
85229 /* Open the super-journal. */
85236 sqlite3DbFree(db, zSuper-4);
85241 ** super-journal file. If an error occurs at this point close
85242 ** and delete the super-journal file. All the individual journal files
85243 ** still have 'null' as the super-journal pointer, so they will roll
85246 for(i=0; i<db->nDb; i++){
85247 Btree *pBt = db->aDb[i].pBt;
85259 sqlite3DbFree(db, zSuper-4);
85265 /* Sync the super-journal file. If the IOCAP_SEQUENTIAL device
85273 sqlite3DbFree(db, zSuper-4);
85278 ** sets the super-journal pointer in each individual journal. If
85279 ** an error occurs here, do not delete the super-journal file.
85283 ** super-journal file will be orphaned. But we cannot delete it,
85284 ** in case the super-journal file name was written into the journal
85287 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
85288 Btree *pBt = db->aDb[i].pBt;
85296 sqlite3DbFree(db, zSuper-4);
85300 /* Delete the super-journal file. This commits the transaction. After
85305 sqlite3DbFree(db, zSuper-4);
85320 for(i=0; i<db->nDb; i++){
85321 Btree *pBt = db->aDb[i].pBt;
85340 ** This is an internal self-check only - it is not an essential processing
85343 ** This is a no-op if NDEBUG is defined.
85351 p = db->pVdbe;
85355 if( p->readOnly==0 ) nWrite++;
85356 if( p->bIsReader ) nRead++;
85358 p = p->pVNext;
85360 assert( cnt==db->nVdbeActive );
85361 assert( nWrite==db->nVdbeWrite );
85362 assert( nRead==db->nVdbeRead );
85369 ** If the Vdbe passed as the first argument opened a statement-transaction,
85379 sqlite3 *const db = p->db;
85382 const int iSavepoint = p->iStatement-1;
85385 assert( db->nStatement>0 );
85386 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
85388 for(i=0; i<db->nDb; i++){
85390 Btree *pBt = db->aDb[i].pBt;
85403 db->nStatement--;
85404 p->iStatement = 0;
85419 db->nDeferredCons = p->nStmtDefCons;
85420 db->nDeferredImmCons = p->nStmtDefImmCons;
85425 if( p->db->nStatement && p->iStatement ){
85444 sqlite3 *db = p->db;
85445 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
85446 || (!deferred && p->nFkConstraint>0)
85448 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
85449 p->errorAction = OE_Abort;
85451 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR;
85473 sqlite3 *db = p->db;
85491 assert( p->eVdbeState==VDBE_RUN_STATE );
85492 if( db->mallocFailed ){
85493 p->rc = SQLITE_NOMEM_BKPT;
85500 if( p->bIsReader ){
85501 int mrc; /* Primary error code from p->rc */
85509 if( p->rc ){
85510 mrc = p->rc & 0xff;
85519 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
85524 ** Even if the statement is read-only, it is important to perform
85526 ** occurred while writing to the journal, sub-journal or database
85531 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
85532 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
85540 db->autoCommit = 1;
85541 p->nChange = 0;
85547 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
85551 /* If the auto-commit flag is set and this is the only active writer
85558 && db->autoCommit
85559 && db->nVdbeWrite==(p->readOnly==0)
85561 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
85564 if( NEVER(p->readOnly) ){
85569 }else if( db->flags & SQLITE_CorruptRdOnly ){
85571 db->flags &= ~SQLITE_CorruptRdOnly;
85573 /* The auto-commit flag is true, the vdbe program was successful
85579 if( rc==SQLITE_BUSY && p->readOnly ){
85583 p->rc = rc;
85585 p->nChange = 0;
85587 db->nDeferredCons = 0;
85588 db->nDeferredImmCons = 0;
85589 db->flags &= ~(u64)SQLITE_DeferFKs;
85594 p->nChange = 0;
85596 db->nStatement = 0;
85598 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
85600 }else if( p->errorAction==OE_Abort ){
85605 db->autoCommit = 1;
85606 p->nChange = 0;
85610 /* If eStatementOp is non-zero, then a statement transaction needs to
85619 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
85620 p->rc = rc;
85621 sqlite3DbFree(db, p->zErrMsg);
85622 p->zErrMsg = 0;
85626 db->autoCommit = 1;
85627 p->nChange = 0;
85632 ** has been rolled back, update the database connection change-counter.
85634 if( p->changeCntOn ){
85636 sqlite3VdbeSetChanges(db, p->nChange);
85640 p->nChange = 0;
85648 db->nVdbeActive--;
85649 if( !p->readOnly ) db->nVdbeWrite--;
85650 if( p->bIsReader ) db->nVdbeRead--;
85651 assert( db->nVdbeActive>=db->nVdbeRead );
85652 assert( db->nVdbeRead>=db->nVdbeWrite );
85653 assert( db->nVdbeWrite>=0 );
85654 p->eVdbeState = VDBE_HALT_STATE;
85656 if( db->mallocFailed ){
85657 p->rc = SQLITE_NOMEM_BKPT;
85660 /* If the auto-commit flag is set to true, then any locks that were held
85662 ** to invoke any required unlock-notify callbacks.
85664 if( db->autoCommit ){
85668 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
85669 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
85675 ** in p->rc. This routine sets that result back to SQLITE_OK.
85678 p->rc = SQLITE_OK;
85690 sqlite3 *db = p->db;
85691 int rc = p->rc;
85692 if( p->zErrMsg ){
85693 db->bBenignMalloc++;
85695 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
85696 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
85698 db->bBenignMalloc--;
85699 }else if( db->pErr ){
85700 sqlite3ValueSetNull(db->pErr);
85702 db->errCode = rc;
85703 db->errByteOffset = -1;
85713 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
85714 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
85715 assert( v->db->init.busy==0 );
85718 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
85720 sqlite3DbFree(v->db, zExpanded);
85745 db = p->db;
85751 if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
85758 if( p->pc>=0 ){
85760 if( db->pErr || p->zErrMsg ){
85763 db->errCode = p->rc;
85772 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
85773 if( p->aMem ){
85774 for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
85777 if( p->zErrMsg ){
85778 sqlite3DbFree(db, p->zErrMsg);
85779 p->zErrMsg = 0;
85781 p->pResultSet = 0;
85783 p->nWrite = 0;
85792 fprintf(out, "---- ");
85793 for(i=0; i<p->nOp; i++){
85794 fprintf(out, "%02x", p->aOp[i].opcode);
85797 if( p->zSql ){
85799 fprintf(out, "-- ");
85800 for(i=0; (c = p->zSql[i])!=0; i++){
85801 if( pc=='\n' ) fprintf(out, "-- ");
85807 for(i=0; i<p->nOp; i++){
85810 p->aOp[i].cnt,
85811 p->aOp[i].cycles,
85812 p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
85815 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
85821 return p->rc & db->errMask;
85833 if( p->eVdbeState>=VDBE_READY_STATE ){
85835 assert( (rc & p->db->errMask)==rc );
85861 || (pAux->iAuxOp==iOp
85862 && pAux->iAuxArg>=0
85863 && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
85865 testcase( pAux->iAuxArg==31 );
85866 if( pAux->xDeleteAux ){
85867 pAux->xDeleteAux(pAux->pAux);
85869 *pp = pAux->pNextAux;
85872 pp= &pAux->pNextAux;
85888 assert( p->db==0 || p->db==db );
85889 if( p->aColName ){
85890 releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
85891 sqlite3DbNNFreeNN(db, p->aColName);
85893 for(pSub=p->pProgram; pSub; pSub=pNext){
85894 pNext = pSub->pNext;
85895 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
85898 if( p->eVdbeState!=VDBE_INIT_STATE ){
85899 releaseMemArray(p->aVar, p->nVar);
85900 if( p->pVList ) sqlite3DbNNFreeNN(db, p->pVList);
85901 if( p->pFree ) sqlite3DbNNFreeNN(db, p->pFree);
85903 vdbeFreeOpArray(db, p->aOp, p->nOp);
85904 if( p->zSql ) sqlite3DbNNFreeNN(db, p->zSql);
85906 sqlite3DbFree(db, p->zNormSql);
85909 for(pThis=p->pDblStr; pThis; pThis=pNext){
85910 pNext = pThis->pNextStr;
85918 for(i=0; i<p->nScan; i++){
85919 sqlite3DbFree(db, p->aScan[i].zName);
85921 sqlite3DbFree(db, p->aScan);
85933 db = p->db;
85935 assert( sqlite3_mutex_held(db->mutex) );
85937 if( db->pnBytesFreed==0 ){
85938 assert( p->ppVPrev!=0 );
85939 *p->ppVPrev = p->pVNext;
85940 if( p->pVNext ){
85941 p->pVNext->ppVPrev = p->ppVPrev;
85957 assert( p->deferredMoveto );
85958 assert( p->isTable );
85959 assert( p->eCurType==CURTYPE_BTREE );
85960 rc = sqlite3BtreeTableMoveto(p->uc.pCursor, p->movetoTarget, 0, &res);
85966 p->deferredMoveto = 0;
85967 p->cacheStatus = CACHE_STALE;
85980 assert( p->eCurType==CURTYPE_BTREE );
85981 assert( p->uc.pCursor!=0 );
85982 assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
85983 rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
85984 p->cacheStatus = CACHE_STALE;
85985 if( isDifferentRow ) p->nullRow = 1;
85994 assert( p->eCurType==CURTYPE_BTREE || IsNullCursor(p) );
85995 if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
86007 ** sqlite3VdbeSerialPut() <--- in-lined into OP_MakeRecord as of 2022-04-02
86012 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
86019 ** serial-type and data blob separately.
86024 ** -------------- --------------- ---------------
86036 ** N>=12 and even (N-12)/2 BLOB
86037 ** N>=13 and odd (N-13)/2 text
86045 ** Return the serial-type for the value stored in pMem.
86049 ** 2019-07-11: The primary user of this subroutine was the OP_MakeRecord
86050 ** opcode in the byte-code engine. But by moving this routine in-line, we
86056 int flags = pMem->flags;
86066 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
86067 i64 i = pMem->u.i;
86092 ** as an integer, then we might as well make it an 8-byte floating
86094 pMem->u.r = (double)pMem->u.i;
86095 pMem->flags &= ~MEM_IntReal;
86096 pMem->flags |= MEM_Real;
86105 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
86106 assert( pMem->n>=0 );
86107 n = (u32)pMem->n;
86109 n += pMem->u.nZero;
86137 ** Return the length of the data corresponding to the supplied serial-type.
86141 return (serial_type-12)/2;
86144 || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
86154 ** If we are on an architecture with mixed-endian floating
86158 ** For most architectures, this is a no-op.
86160 ** (later): It is reported to me that the mixed-endian problem
86162 ** that early versions of GCC stored the two words of a 64-bit
86170 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
86174 ** (2007-08-30) Frank van Vugt has studied this problem closely
86177 ** emulation that uses only 32-bit mantissas instead of a full
86178 ** 48-bits as required by the IEEE standard. (This is the
86181 ** the necessary byte swapping is carried out using a 64-bit integer
86182 ** rather than a 64-bit float. Frank assures us that the code here
86205 ** big-endian integer. Return the equivalent native integer
86231 /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
86232 ** twos-complement integer. */
86233 pMem->u.i = *(i64*)&x;
86234 pMem->flags = MEM_Int;
86235 testcase( pMem->u.i<0 );
86237 /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
86242 ** defined that 64-bit floating point values really are mixed
86251 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
86253 memcpy(&pMem->u.r, &x, sizeof(x));
86254 pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
86264 ** UPDATE no-change flag set */
86265 pMem->flags = MEM_Null|MEM_Zero;
86266 pMem->n = 0;
86267 pMem->u.nZero = 0;
86272 /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
86273 pMem->flags = MEM_Null;
86277 /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
86279 pMem->u.i = ONE_BYTE_INT(buf);
86280 pMem->flags = MEM_Int;
86281 testcase( pMem->u.i<0 );
86284 case 2: { /* 2-byte signed integer */
86285 /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
86286 ** twos-complement integer. */
86287 pMem->u.i = TWO_BYTE_INT(buf);
86288 pMem->flags = MEM_Int;
86289 testcase( pMem->u.i<0 );
86292 case 3: { /* 3-byte signed integer */
86293 /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
86294 ** twos-complement integer. */
86295 pMem->u.i = THREE_BYTE_INT(buf);
86296 pMem->flags = MEM_Int;
86297 testcase( pMem->u.i<0 );
86300 case 4: { /* 4-byte signed integer */
86301 /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
86302 ** twos-complement integer. */
86303 pMem->u.i = FOUR_BYTE_INT(buf);
86305 /* Work around a sign-extension bug in the HP compiler for HP/UX */
86306 if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
86308 pMem->flags = MEM_Int;
86309 testcase( pMem->u.i<0 );
86312 case 5: { /* 6-byte signed integer */
86313 /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
86314 ** twos-complement integer. */
86315 pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
86316 pMem->flags = MEM_Int;
86317 testcase( pMem->u.i<0 );
86320 case 6: /* 8-byte signed integer */
86329 /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
86330 /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
86331 pMem->u.i = serial_type-8;
86332 pMem->flags = MEM_Int;
86336 /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
86338 ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
86339 ** (N-13)/2 bytes in length. */
86341 pMem->z = (char *)buf;
86342 pMem->n = (serial_type-12)/2;
86343 pMem->flags = aFlag[serial_type&1];
86368 nByte = ROUND8P(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
86369 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
86371 p->aMem = (Mem*)&((char*)p)[ROUND8P(sizeof(UnpackedRecord))];
86372 assert( pKeyInfo->aSortFlags!=0 );
86373 p->pKeyInfo = pKeyInfo;
86374 p->nField = pKeyInfo->nKeyField + 1;
86379 ** Given the nKey-byte encoding of a record in pKey[], populate the
86394 Mem *pMem = p->aMem;
86396 p->default_rc = 0;
86405 pMem->enc = pKeyInfo->enc;
86406 pMem->db = pKeyInfo->db;
86407 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
86408 pMem->szMalloc = 0;
86409 pMem->z = 0;
86413 if( (++u)>=p->nField ) break;
86420 sqlite3VdbeMemSetNull(pMem-1);
86422 assert( u<=pKeyInfo->nKeyField + 1 );
86423 p->nField = u;
86452 pKeyInfo = pPKey2->pKeyInfo;
86453 if( pKeyInfo->db==0 ) return 1;
86454 mem1.enc = pKeyInfo->enc;
86455 mem1.db = pKeyInfo->db;
86471 assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
86472 assert( pKeyInfo->aSortFlags!=0 );
86473 assert( pKeyInfo->nKeyField>0 );
86500 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
86501 pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
86504 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
86505 && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
86507 rc = -rc;
86509 if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
86510 rc = -rc; /* Invert the result for DESC sort order. */
86515 }while( idx1<szHdr1 && i<pPKey2->nField );
86526 rc = pPKey2->default_rc;
86533 if( pKeyInfo->db->mallocFailed ) return 1;
86542 ** limit given by pKeyInfo->nAllField.
86544 ** If this constraint is not satisfied, it means that the high-speed
86568 assert( nField <= pKeyInfo->nAllField );
86578 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
86586 if( pMem1->enc==pColl->enc ){
86589 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
86595 sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
86596 sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
86599 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
86600 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
86605 rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
86615 ** with MEM_Zero. Return true if it could be a zero-blob.
86632 int n1 = pB1->n;
86633 int n2 = pB2->n;
86635 /* It is possible to have a Blob value that has some non-zero content
86639 assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
86640 assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
86642 if( (pB1->flags|pB2->flags) & MEM_Zero ){
86643 if( pB1->flags & pB2->flags & MEM_Zero ){
86644 return pB1->u.nZero - pB2->u.nZero;
86645 }else if( pB1->flags & MEM_Zero ){
86646 if( !isAllZero(pB2->z, pB2->n) ) return -1;
86647 return pB1->u.nZero - n2;
86649 if( !isAllZero(pB1->z, pB1->n) ) return +1;
86650 return n1 - pB2->u.nZero;
86653 c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
86655 return n1 - n2;
86659 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
86669 if( x<r ) return -1;
86675 if( r<-9223372036854775808.0 ) return +1;
86676 if( r>=9223372036854775808.0 ) return -1;
86678 if( i<y ) return -1;
86681 if( s<r ) return -1;
86700 f1 = pMem1->flags;
86701 f2 = pMem2->flags;
86709 return (f2&MEM_Null) - (f1&MEM_Null);
86721 if( pMem1->u.i < pMem2->u.i ) return -1;
86722 if( pMem1->u.i > pMem2->u.i ) return +1;
86726 if( pMem1->u.r < pMem2->u.r ) return -1;
86727 if( pMem1->u.r > pMem2->u.r ) return +1;
86734 return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
86736 if( pMem1->u.i < pMem2->u.i ) return -1;
86737 if( pMem1->u.i > pMem2->u.i ) return +1;
86740 return -1;
86747 return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
86749 return -1;
86763 return -1;
86766 assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
86767 assert( pMem1->enc==SQLITE_UTF8 ||
86768 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
86774 assert( !pColl || pColl->xCmp );
86789 ** The first argument passed to this function is a serial-type that
86790 ** corresponds to an integer - all values between 1 and 9 inclusive
86826 return (serial_type - 8);
86838 ** If argument bSkip is non-zero, it is assumed that the caller has already
86842 ** fields that appear in both keys are equal, then pPKey2->default_rc is
86845 ** If database corruption is discovered, set pPKey2->errCode to
86847 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
86848 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
86860 Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
86889 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
86894 assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
86896 assert( pPKey2->pKeyInfo->aSortFlags!=0 );
86897 assert( pPKey2->pKeyInfo->nKeyField>0 );
86899 while( 1 /*exit-by-break*/ ){
86903 if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
86904 testcase( pRhs->flags & MEM_Int );
86905 testcase( pRhs->flags & MEM_IntReal );
86909 rc = serial_type==10 ? -1 : +1;
86911 rc = -1;
86914 rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
86917 i64 rhs = pRhs->u.i;
86919 rc = -1;
86927 else if( pRhs->flags & MEM_Real ){
86934 rc = serial_type==10 ? -1 : +1;
86936 rc = -1;
86940 if( mem1.u.r<pRhs->u.r ){
86941 rc = -1;
86942 }else if( mem1.u.r>pRhs->u.r ){
86946 rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
86952 else if( pRhs->flags & MEM_Str ){
86956 rc = -1;
86960 mem1.n = (serial_type - 12) / 2;
86964 || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
86966 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
86968 }else if( pKeyInfo->aColl[i] ){
86969 mem1.enc = pKeyInfo->enc;
86970 mem1.db = pKeyInfo->db;
86974 &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
86977 int nCmp = MIN(mem1.n, pRhs->n);
86978 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
86979 if( rc==0 ) rc = mem1.n - pRhs->n;
86985 else if( pRhs->flags & MEM_Blob ){
86986 assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
86990 rc = -1;
86992 int nStr = (serial_type - 12) / 2;
86996 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
86998 }else if( pRhs->flags & MEM_Zero ){
87002 rc = nStr - pRhs->u.nZero;
87005 int nCmp = MIN(nStr, pRhs->n);
87006 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
87007 if( rc==0 ) rc = nStr - pRhs->n;
87019 int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
87023 !=(serial_type==0 || (pRhs->flags&MEM_Null)))
87025 rc = -rc;
87034 if( i==pPKey2->nField ) break;
87040 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
87054 || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
87055 || pPKey2->pKeyInfo->db->mallocFailed
87057 pPKey2->eqSeen = 1;
87058 return pPKey2->default_rc;
87071 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
87089 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
87092 case 1: { /* 1-byte signed integer */
87097 case 2: { /* 2-byte signed integer */
87102 case 3: { /* 3-byte signed integer */
87107 case 4: { /* 4-byte signed integer */
87113 case 5: { /* 6-byte signed integer */
87118 case 6: { /* 8-byte signed integer */
87145 assert( pPKey2->u.i == pPKey2->aMem[0].u.i );
87146 v = pPKey2->u.i;
87148 res = pPKey2->r1;
87150 res = pPKey2->r2;
87151 }else if( pPKey2->nField>1 ){
87157 ** fields. Return pPKey2->default_rc in this case. */
87158 res = pPKey2->default_rc;
87159 pPKey2->eqSeen = 1;
87169 ** uses the collation sequence BINARY and (c) that the size-of-header varint
87180 assert( pPKey2->aMem[0].flags & MEM_Str );
87181 assert( pPKey2->aMem[0].n == pPKey2->n );
87182 assert( pPKey2->aMem[0].z == pPKey2->u.z );
87183 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
87193 res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
87195 res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
87201 nStr = (serial_type-12) / 2;
87203 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
87206 nCmp = MIN( pPKey2->n, nStr );
87207 res = memcmp(&aKey1[szHdr], pPKey2->u.z, nCmp);
87210 res = pPKey2->r2;
87212 res = pPKey2->r1;
87214 res = nStr - pPKey2->n;
87216 if( pPKey2->nField>1 ){
87219 res = pPKey2->default_rc;
87220 pPKey2->eqSeen = 1;
87223 res = pPKey2->r2;
87225 res = pPKey2->r1;
87232 || pPKey2->pKeyInfo->db->mallocFailed
87244 ** that the size-of-header varint that occurs at the start of each record
87256 if( p->pKeyInfo->nAllField<=13 ){
87257 int flags = p->aMem[0].flags;
87258 if( p->pKeyInfo->aSortFlags[0] ){
87259 if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
87262 p->r1 = 1;
87263 p->r2 = -1;
87265 p->r1 = -1;
87266 p->r2 = 1;
87269 p->u.i = p->aMem[0].u.i;
87276 && p->pKeyInfo->aColl[0]==0
87279 p->u.z = p->aMem[0].z;
87280 p->n = p->aMem[0].n;
87305 ** than 2GiB are support - anything large must be database corruption.
87307 ** this code can safely assume that nCellKey is 32-bits
87330 /* The last field of the index should be an integer - the ROWID.
87332 getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);
87351 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
87386 assert( pC->eCurType==CURTYPE_BTREE );
87387 pCur = pC->uc.pCursor;
87411 assert( sqlite3_mutex_held(db->mutex) );
87412 db->nChange = nChange;
87413 db->nTotalChange += nChange;
87421 v->changeCntOn = 1;
87430 ** programs obsolete. Removing user-defined functions or collating
87444 for(p = db->pVdbe; p; p=p->pVNext){
87445 p->expired = iCode+1;
87453 return v->db;
87460 return v->prepFlags;
87474 Mem *pMem = &v->aVar[iVar-1];
87475 assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
87476 if( 0==(pMem->flags & MEM_Null) ){
87477 sqlite3_value *pRet = sqlite3ValueNew(v->db);
87490 ** to sqlite3_reoptimize() that re-preparing the statement may result
87495 assert( (v->db->flags & SQLITE_EnableQPSG)==0 );
87497 v->expmask |= 0x80000000;
87499 v->expmask |= ((u32)1 << (iVar-1));
87508 ** throw an error if it is given inputs that would make it non-deterministic.
87509 ** This routine is invoked by date/time functions that use non-deterministic
87515 if( pCtx->pVdbe==0 ) return 1;
87517 pOp = pCtx->pVdbe->aOp + pCtx->iOp;
87518 if( pOp->opcode==OP_PureFunc ){
87521 if( pOp->p5 & NC_IsCheck ){
87523 }else if( pOp->p5 & NC_GenCol ){
87528 zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
87529 pCtx->pFunc->zName, zContext);
87530 sqlite3_result_error(pCtx, zMsg, -1);
87544 if( pVtab->zErrMsg ){
87545 sqlite3 *db = p->db;
87546 sqlite3DbFree(db, p->zErrMsg);
87547 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
87548 sqlite3_free(pVtab->zErrMsg);
87549 pVtab->zErrMsg = 0;
87558 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
87569 Mem *pMem = &p->aMem[i];
87570 if( pMem->zMalloc ) sqlite3VdbeMemReleaseMalloc(pMem);
87579 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
87585 Vdbe *v, /* Vdbe pre-update hook is invoked by */
87594 sqlite3 *db = v->db;
87597 const char *zTbl = pTab->zName;
87600 assert( db->pPreUpdate==0 );
87607 iKey2 = v->aMem[iReg].u.i;
87614 assert( pCsr->eCurType==CURTYPE_BTREE );
87615 assert( pCsr->nField==pTab->nCol
87616 || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
87625 preupdate.keyinfo.nKeyField = pTab->nCol;
87632 db->pPreUpdate = &preupdate;
87633 db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
87634 db->pPreUpdate = 0;
87640 for(i=0; i<pCsr->nField; i++){
87653 ** The author disclaims copyright to this source code. In place of
87670 ** Return TRUE (non-zero) of the statement supplied as an argument needs
87679 return p==0 || p->expired;
87689 if( p->db==0 ){
87713 assert( p->startTime>0 );
87714 assert( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0 );
87715 assert( db->init.busy==0 );
87716 assert( p->zSql!=0 );
87717 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
87718 iElapse = (iNow - p->startTime)*1000000;
87720 if( db->xProfile ){
87721 db->xProfile(db->pProfileArg, p->zSql, iElapse);
87724 if( db->mTrace & SQLITE_TRACE_PROFILE ){
87725 db->trace.xV2(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
87727 p->startTime = 0;
87734 if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
87736 # define checkProfileCallback(DB,P) /*no-op*/
87751 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
87752 ** pointer is a harmless no-op. */
87756 sqlite3 *db = v->db;
87758 sqlite3_mutex_enter(db->mutex);
87760 assert( v->eVdbeState>=VDBE_READY_STATE );
87783 sqlite3 *db = v->db;
87784 sqlite3_mutex_enter(db->mutex);
87788 assert( (rc & (db->errMask))==rc );
87790 sqlite3_mutex_leave(db->mutex);
87803 sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
87806 for(i=0; i<p->nVar; i++){
87807 sqlite3VdbeMemRelease(&p->aVar[i]);
87808 p->aVar[i].flags = MEM_Null;
87810 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
87811 if( p->expmask ){
87812 p->expired = 1;
87825 if( p->flags & (MEM_Blob|MEM_Str) ){
87827 assert( p->flags==MEM_Null && p->z==0 );
87830 p->flags |= MEM_Blob;
87831 return p->n ? p->z : 0;
87853 return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
87857 if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
87860 && p->eSubtype=='p'
87861 && strcmp(p->u.zPType, zPType)==0
87863 return (void*)p->z;
87882 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
87883 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
87956 if( pVal->flags & MEM_Null ){
87958 }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){
87960 }else if( pVal->flags & MEM_Int ){
87962 }else if( pVal->flags & MEM_Str ){
87965 assert( eType == aType[pVal->flags&MEM_AffMask] );
87968 return aType[pVal->flags&MEM_AffMask];
87971 return pVal->enc;
87976 return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
87981 return (pVal->flags&MEM_FromBind)!=0;
87993 pNew->flags &= ~MEM_Dyn;
87994 pNew->db = 0;
87995 if( pNew->flags&(MEM_Str|MEM_Blob) ){
87996 pNew->flags &= ~(MEM_Static|MEM_Dyn);
87997 pNew->flags |= MEM_Ephem;
88002 }else if( pNew->flags & MEM_Null ){
88004 pNew->flags &= ~(MEM_Term|MEM_Subtype);
88018 ** The following routines are used by user-defined functions to specify
88035 Mem *pOut = pCtx->pOut;
88048 sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
88076 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88085 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88094 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88095 sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
88098 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88099 pCtx->isError = SQLITE_ERROR;
88100 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
88104 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88105 pCtx->isError = SQLITE_ERROR;
88106 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
88110 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88111 sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
88114 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88115 sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
88118 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88119 sqlite3VdbeMemSetNull(pCtx->pOut);
88127 Mem *pOut = pCtx->pOut;
88128 assert( sqlite3_mutex_held(pOut->db->mutex) );
88130 pOut->flags = MEM_Null;
88134 Mem *pOut = pCtx->pOut;
88135 assert( sqlite3_mutex_held(pOut->db->mutex) );
88136 pOut->eSubtype = eSubtype & 0xff;
88137 pOut->flags |= MEM_Subtype;
88145 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88155 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88171 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88180 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88189 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88194 Mem *pOut = pCtx->pOut;
88195 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88197 sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
88206 Mem *pOut = pCtx->pOut;
88207 assert( sqlite3_mutex_held(pOut->db->mutex) );
88208 if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
88213 sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
88216 return sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
88220 pCtx->isError = errCode ? errCode : -1;
88222 if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
88224 if( pCtx->pOut->flags & MEM_Null ){
88225 setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
88232 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88233 pCtx->isError = SQLITE_TOOBIG;
88234 sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
88240 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88241 sqlite3VdbeMemSetNull(pCtx->pOut);
88242 pCtx->isError = SQLITE_NOMEM_BKPT;
88243 sqlite3OomFault(pCtx->pOut->db);
88249 ** test-control.
88252 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88253 if( pCtx->pOut->flags & MEM_Int ){
88254 pCtx->pOut->flags &= ~MEM_Int;
88255 pCtx->pOut->flags |= MEM_IntReal;
88269 for(i=0; i<db->nDb; i++){
88270 Btree *pBt = db->aDb[i].pBt;
88276 if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
88277 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
88300 db = p->db;
88301 if( p->eVdbeState!=VDBE_RUN_STATE ){
88303 if( p->eVdbeState==VDBE_READY_STATE ){
88304 if( p->expired ){
88305 p->rc = SQLITE_SCHEMA;
88307 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
88309 ** error has occurred, then return the error code in p->rc to the
88322 if( db->nVdbeActive==0 ){
88323 AtomicStore(&db->u1.isInterrupted, 0);
88326 assert( db->nVdbeWrite>0 || db->autoCommit==0
88327 || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
88331 if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
88332 && !db->init.busy && p->zSql ){
88333 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
88335 assert( p->startTime==0 );
88339 db->nVdbeActive++;
88340 if( p->readOnly==0 ) db->nVdbeWrite++;
88341 if( p->bIsReader ) db->nVdbeRead++;
88342 p->pc = 0;
88343 p->eVdbeState = VDBE_RUN_STATE;
88346 if( ALWAYS(p->eVdbeState==VDBE_HALT_STATE) ){
88351 ** This "automatic-reset" change is not technically an incompatibility,
88357 ** returns, and those were broken by the automatic-reset change. As a
88358 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
88364 if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
88372 assert( p->eVdbeState==VDBE_READY_STATE );
88378 p->rcApp = SQLITE_OK;
88381 if( p->explain ){
88386 db->nVdbeExec++;
88388 db->nVdbeExec--;
88392 assert( p->rc==SQLITE_OK );
88393 assert( db->mallocFailed==0 );
88394 db->errCode = SQLITE_ROW;
88402 if( rc==SQLITE_DONE && db->autoCommit ){
88403 assert( p->rc==SQLITE_OK );
88404 p->rc = doWalCallbacks(db);
88405 if( p->rc!=SQLITE_OK ){
88408 }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
88410 ** error has occurred, then return the error code in p->rc to the
88417 db->errCode = rc;
88418 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
88419 p->rc = SQLITE_NOMEM_BKPT;
88420 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc;
88425 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
88429 return (rc&db->errMask);
88434 sqlite3_mutex_enter(db->mutex);
88435 db->xDropTableHandle = xFunc;
88436 sqlite3_mutex_leave(db->mutex);
88442 ** This is the top-level implementation of sqlite3_step(). Call
88455 db = v->db;
88456 sqlite3_mutex_enter(db->mutex);
88459 int savedPc = v->pc;
88461 Sqlite3SharedBlockMethods *pSharedBlock = v->pSharedBlock;
88462 int totalRows = v->totalRows;
88463 int blockFull = v->blockFull;
88464 int startPos = v->startPos;
88465 int addedRows = v->addedRows;
88477 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
88478 sqlite3DbFree(db, v->zErrMsg);
88479 if( !db->mallocFailed ){
88480 v->zErrMsg = sqlite3DbStrDup(db, zErr);
88481 v->rc = rc = sqlite3ApiExit(db, rc);
88483 v->zErrMsg = 0;
88484 v->rc = rc = SQLITE_NOMEM_BKPT;
88490 v->pSharedBlock = pSharedBlock;
88491 v->totalRows = totalRows;
88492 v->blockFull = blockFull;
88493 v->startPos = startPos;
88494 v->addedRows = addedRows;
88502 ** SQLITE_SCHEMA. tag-20220401a */
88503 v->minWriteFileFormat = 254;
88505 assert( v->expired==0 );
88508 if( rc==SQLITE_DONE && db->xDropTableHandle!=NULL && db->isDropTable==1 ){
88509 db->isDropTable = 0;
88510 db->xDropTableHandle(db, db->mDropTableName, db->mDropSchemaName);
88512 if( db->mDropTableName!=NULL ){
88513 sqlite3_free(db->mDropTableName);
88514 db->mDropTableName = NULL;
88516 if( db->mDropSchemaName!=NULL ){
88517 sqlite3_free(db->mDropSchemaName);
88518 db->mDropSchemaName = NULL;
88521 sqlite3_mutex_leave(db->mutex);
88531 assert( p && p->pFunc );
88532 return p->pFunc->pUserData;
88539 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
88546 assert( p && p->pOut );
88547 return p->pOut->db;
88561 ** performance by substituting a NULL result, or some other light-weight
88566 return sqlite3_value_nochange(p->pOut);
88586 rc = sqlite3BtreeNext(pRhs->pCsr, 0);
88589 rc = sqlite3BtreeFirst(pRhs->pCsr, &dummy);
88590 assert( rc==SQLITE_OK || sqlite3BtreeEof(pRhs->pCsr) );
88591 if( sqlite3BtreeEof(pRhs->pCsr) ) rc = SQLITE_DONE;
88597 sz = sqlite3BtreePayloadSize(pRhs->pCsr);
88598 rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);
88602 sqlite3_value *pOut = pRhs->pOut;
88605 pOut->enc = ENC(pOut->db);
88606 if( (pOut->flags & MEM_Ephem)!=0 && sqlite3VdbeMemMakeWriteable(pOut) ){
88643 sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
88644 assert( p->pVdbe!=0 );
88647 sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
88650 rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
88658 ** its pMem->z element.
88661 Mem *pMem = p->pMem;
88662 assert( (pMem->flags & MEM_Agg)==0 );
88665 pMem->z = 0;
88668 pMem->flags = MEM_Agg;
88669 pMem->u.pDef = p->pFunc;
88670 if( pMem->z ){
88671 memset(pMem->z, 0, nByte);
88674 return (void*)pMem->z;
88683 assert( p && p->pFunc && p->pFunc->xFinalize );
88684 assert( sqlite3_mutex_held(p->pOut->db->mutex) );
88686 if( (p->pMem->flags & MEM_Agg)==0 ){
88689 return (void*)p->pMem->z;
88695 ** the user-function defined by pCtx.
88697 ** The left-most argument is 0.
88706 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88708 if( pCtx->pVdbe==0 ) return 0;
88710 assert( pCtx->pVdbe!=0 );
88712 for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
88713 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
88714 return pAuxData->pAux;
88722 ** argument to the user-function defined by pCtx. Any previous value is
88725 ** The left-most argument is 0.
88738 Vdbe *pVdbe = pCtx->pVdbe;
88740 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
88747 for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
88748 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
88753 pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
88755 pAuxData->iAuxOp = pCtx->iOp;
88756 pAuxData->iAuxArg = iArg;
88757 pAuxData->pNextAux = pVdbe->pAuxData;
88758 pVdbe->pAuxData = pAuxData;
88759 if( pCtx->isError==0 ) pCtx->isError = -1;
88760 }else if( pAuxData->xDeleteAux ){
88761 pAuxData->xDeleteAux(pAuxData->pAux);
88764 pAuxData->pAux = pAux;
88765 pAuxData->xDeleteAux = xDelete;
88785 assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
88786 return p->pMem->n;
88795 return pVm ? pVm->nResColumn : 0;
88804 if( pVm==0 || pVm->pResultSet==0 ) return 0;
88805 return pVm->nResColumn;
88814 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
88815 ** instead of an 8-byte one. This all works fine, except that when
88817 ** that a Mem structure is located on an 8-byte boundary. To prevent
88819 ** using gcc, we force nullMem to be 8-byte aligned using the magical
88857 assert( pVm->db );
88858 sqlite3_mutex_enter(pVm->db->mutex);
88859 if( pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
88860 pOut = &pVm->pResultSet[i];
88862 sqlite3Error(pVm->db, SQLITE_RANGE);
88895 assert( p->db!=0 );
88896 assert( sqlite3_mutex_held(p->db->mutex) );
88897 p->rc = sqlite3ApiExit(p->db, p->rc);
88898 sqlite3_mutex_leave(p->db->mutex);
88948 if( pOut->flags&MEM_Static ){
88949 pOut->flags &= ~MEM_Static;
88950 pOut->flags |= MEM_Ephem;
88969 ** Convert the N-th element of pStmt->pColName[] into a string using
89002 db = p->db;
89007 sqlite3_mutex_enter(db->mutex);
89008 assert( db->mallocFailed==0 );
89011 ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
89015 ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
89020 if( db->mallocFailed ){
89024 sqlite3_mutex_leave(db->mutex);
89123 ** The error code stored in database p->db is overwritten with the return
89131 sqlite3_mutex_enter(p->db->mutex);
89132 if( p->eVdbeState!=VDBE_READY_STATE ){
89133 sqlite3Error(p->db, SQLITE_MISUSE);
89134 sqlite3_mutex_leave(p->db->mutex);
89136 "bind on a busy prepared statement: [%s]", p->zSql);
89139 if( i>=(unsigned int)p->nVar ){
89140 sqlite3Error(p->db, SQLITE_RANGE);
89141 sqlite3_mutex_leave(p->db->mutex);
89144 pVar = &p->aVar[i];
89146 pVar->flags = MEM_Null;
89147 p->db->errCode = SQLITE_OK;
89152 ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
89158 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
89159 if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
89160 p->expired = 1;
89180 rc = vdbeUnbind(p, (u32)(i-1));
89183 pVar = &p->aVar[i-1];
89186 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
89189 sqlite3Error(p->db, rc);
89190 rc = sqlite3ApiExit(p->db, rc);
89193 sqlite3_mutex_leave(p->db->mutex);
89229 rc = vdbeUnbind(p, (u32)(i-1));
89231 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
89232 sqlite3_mutex_leave(p->db->mutex);
89242 rc = vdbeUnbind(p, (u32)(i-1));
89244 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
89245 sqlite3_mutex_leave(p->db->mutex);
89252 rc = vdbeUnbind(p, (u32)(i-1));
89254 sqlite3_mutex_leave(p->db->mutex);
89267 rc = vdbeUnbind(p, (u32)(i-1));
89269 sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
89270 sqlite3_mutex_leave(p->db->mutex);
89312 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
89316 assert( pValue->flags & (MEM_Real|MEM_IntReal) );
89318 (pValue->flags & MEM_Real) ? pValue->u.r : (double)pValue->u.i
89323 if( pValue->flags & MEM_Zero ){
89324 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
89326 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
89331 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
89332 pValue->enc);
89345 rc = vdbeUnbind(p, (u32)(i-1));
89348 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
89350 rc = sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
89352 sqlite3_mutex_leave(p->db->mutex);
89359 sqlite3_mutex_enter(p->db->mutex);
89360 if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
89366 rc = sqlite3ApiExit(p->db, rc);
89367 sqlite3_mutex_leave(p->db->mutex);
89377 return p ? p->nVar : 0;
89384 ** The result is always UTF-8.
89389 return sqlite3VListNumToName(p->pVList, i);
89399 return sqlite3VListNameToNum(p->pVList, zName, nName);
89412 assert( pTo->db==pFrom->db );
89413 assert( pTo->nVar==pFrom->nVar );
89414 sqlite3_mutex_enter(pTo->db->mutex);
89415 for(i=0; i<pFrom->nVar; i++){
89416 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
89418 sqlite3_mutex_leave(pTo->db->mutex);
89438 if( pFrom->nVar!=pTo->nVar ){
89441 assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
89442 if( pTo->expmask ){
89443 pTo->expired = 1;
89445 assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
89446 if( pFrom->expmask ){
89447 pFrom->expired = 1;
89460 return pStmt ? ((Vdbe*)pStmt)->db : 0;
89468 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
89476 return pStmt ? ((Vdbe*)pStmt)->explain : 0;
89484 return v!=0 && v->eVdbeState==VDBE_RUN_STATE;
89501 sqlite3_mutex_enter(pDb->mutex);
89503 pNext = (sqlite3_stmt*)pDb->pVdbe;
89505 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pVNext;
89507 sqlite3_mutex_leave(pDb->mutex);
89519 || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
89526 sqlite3 *db = pVdbe->db;
89527 sqlite3_mutex_enter(db->mutex);
89529 db->pnBytesFreed = (int*)&v;
89530 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
89531 db->lookaside.pEnd = db->lookaside.pStart;
89533 db->pnBytesFreed = 0;
89534 db->lookaside.pEnd = db->lookaside.pTrueEnd;
89535 sqlite3_mutex_leave(db->mutex);
89537 v = pVdbe->aCounter[op];
89538 if( resetFlag ) pVdbe->aCounter[op] = 0;
89548 return p ? p->zSql : 0;
89568 sqlite3_mutex_enter(p->db->mutex);
89570 sqlite3_mutex_leave(p->db->mutex);
89583 if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
89584 sqlite3_mutex_enter(p->db->mutex);
89585 p->zNormSql = sqlite3Normalize(p, p->zSql);
89586 sqlite3_mutex_leave(p->db->mutex);
89588 return p->zNormSql;
89607 memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
89614 ** This function is called from within a pre-update callback to retrieve
89618 PreUpdate *p = db->pPreUpdate;
89623 ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
89624 if( !p || p->op==SQLITE_INSERT ){
89628 if( p->pPk ){
89629 iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
89631 if( iIdx>=p->pCsr->nField || iIdx<0 ){
89637 if( p->pUnpacked==0 ){
89641 assert( p->pCsr->eCurType==CURTYPE_BTREE );
89642 nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
89645 rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
89647 p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
89648 if( !p->pUnpacked ) rc = SQLITE_NOMEM;
89654 p->aRecord = aRec;
89657 pMem = *ppValue = &p->pUnpacked->aMem[iIdx];
89658 if( iIdx==p->pTab->iPKey ){
89659 sqlite3VdbeMemSetInt64(pMem, p->iKey1);
89660 }else if( iIdx>=p->pUnpacked->nField ){
89662 }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
89663 if( pMem->flags & (MEM_Int|MEM_IntReal) ){
89664 testcase( pMem->flags & MEM_Int );
89665 testcase( pMem->flags & MEM_IntReal );
89678 ** This function is called from within a pre-update callback to retrieve
89682 PreUpdate *p = db->pPreUpdate;
89683 return (p ? p->keyinfo.nKeyField : 0);
89689 ** This function is designed to be called from within a pre-update callback
89693 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
89694 ** top-level trigger etc.).
89700 PreUpdate *p = db->pPreUpdate;
89701 return (p ? p->v->nFrame : 0);
89707 ** This function is designed to be called from within a pre-update callback
89711 PreUpdate *p = db->pPreUpdate;
89712 return (p ? p->iBlobWrite : -1);
89718 ** This function is called from within a pre-update callback to retrieve
89722 PreUpdate *p = db->pPreUpdate;
89726 if( !p || p->op==SQLITE_DELETE ){
89730 if( p->pPk && p->op!=SQLITE_UPDATE ){
89731 iIdx = sqlite3TableColumnToIndex(p->pPk, iIdx);
89733 if( iIdx>=p->pCsr->nField || iIdx<0 ){
89738 if( p->op==SQLITE_INSERT ){
89739 /* For an INSERT, memory cell p->iNewReg contains the serialized record
89741 UnpackedRecord *pUnpack = p->pNewUnpacked;
89743 Mem *pData = &p->v->aMem[p->iNewReg];
89746 pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
89751 p->pNewUnpacked = pUnpack;
89753 pMem = &pUnpack->aMem[iIdx];
89754 if( iIdx==p->pTab->iPKey ){
89755 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
89756 }else if( iIdx>=pUnpack->nField ){
89760 /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
89765 assert( p->op==SQLITE_UPDATE );
89766 if( !p->aNew ){
89767 p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
89768 if( !p->aNew ){
89773 assert( iIdx>=0 && iIdx<p->pCsr->nField );
89774 pMem = &p->aNew[iIdx];
89775 if( pMem->flags==0 ){
89776 if( iIdx==p->pTab->iPKey ){
89777 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
89779 rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
89804 if( idx<0 || idx>=p->nScan ) return 1;
89805 pScan = &p->aScan[idx];
89808 *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
89812 *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
89817 LogEst x = pScan->nEst;
89826 *(const char**)pOut = pScan->zName;
89830 if( pScan->addrExplain ){
89831 *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
89838 if( pScan->addrExplain ){
89839 *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
89841 *(int*)pOut = -1;
89857 memset(p->anExec, 0, p->nOp * sizeof(i64));
89866 ** The author disclaims copyright to this source code. In place of
89878 ** The Vdbe parse-tree explainer is also found here.
89886 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
89911 ** This function returns a pointer to a nul-terminated string in memory
89915 ** then the returned string holds a copy of zRawSql with "-- " prepended
89921 ** with large (multi-megabyte) strings and blobs.
89931 ** parameter index is known, locate the value in p->aVar[]. Then render
89950 db = p->db;
89951 sqlite3StrAccumInit(&out, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
89952 if( db->nVdbeExec>1 ){
89956 sqlite3_str_append(&out, "-- ", 3);
89957 assert( (zRawSql - zStart) > 0 );
89958 sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
89960 }else if( p->nVar==0 ){
89989 assert( idx>0 && idx<=p->nVar );
89990 pVar = &p->aVar[idx-1];
89991 if( pVar->flags & MEM_Null ){
89993 }else if( pVar->flags & (MEM_Int|MEM_IntReal) ){
89994 sqlite3_str_appendf(&out, "%lld", pVar->u.i);
89995 }else if( pVar->flags & MEM_Real ){
89996 sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
89997 }else if( pVar->flags & MEM_Str ){
90004 sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
90012 nOut = pVar->n;
90016 while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
90019 sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
90021 if( nOut<pVar->n ){
90022 sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
90028 }else if( pVar->flags & MEM_Zero ){
90029 sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
90032 assert( pVar->flags & MEM_Blob );
90034 nOut = pVar->n;
90039 sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
90043 if( nOut<pVar->n ){
90044 sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
90061 ** The author disclaims copyright to this source code. In place of
90072 ** Various scripts scan this source file in order to generate HTML
90133 ** use this information to make sure that the zero-blob functionality
90140 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
90141 sqlite3_max_blobsize = p->n;
90151 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
90153 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
90205 ** M: 2 - two-way branch (I=0: fall-thru 1: jump )
90206 ** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL )
90207 ** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3)
90209 ** In other words, if M is 2, then I is either 0 (for fall-through) or
90211 ** ordinary fall-through, I is 1 if the branch was taken, and I is 2
90217 ** iSrcLine is the source code line (from the __LINE__ macro) that
90218 ** generated the VDBE instruction combined with flag bits. The source
90222 ** always taken, the flags should be 0x05 since the fall-through and
90224 ** flags should be 0x06 since only the fall-through approach is allowed.
90227 ** interested in equal or not-equal. In other words, I==0 and I==2
90232 ** should be no-ops except for special builds used to measure test coverage.
90237 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
90241 assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
90253 ** iSrcLine - the line number of the VdbeCoverage() macro, with
90255 ** I - Mask of bits 0x07 indicating which cases are are
90257 ** fall-thru, 0x02 means taken, 0x04 means NULL. Any
90262 ** M - Type of jump. Same as M argument above
90287 if( ((P)->flags&MEM_Ephem)!=0 \
90291 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
90318 ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
90319 ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
90321 Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
90329 assert( iCur>=0 && iCur<p->nCursor );
90330 if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
90331 sqlite3VdbeFreeCursorNN(p, p->apCsr[iCur]);
90332 p->apCsr[iCur] = 0;
90337 ** in pMem->zMalloc. But for the special case of the aMem[] entries used
90338 ** to hold cursors, it is faster to in-line the logic. */
90339 assert( pMem->flags==MEM_Undefined );
90340 assert( (pMem->flags & MEM_Dyn)==0 );
90341 assert( pMem->szMalloc==0 || pMem->z==pMem->zMalloc );
90342 if( pMem->szMalloc<nByte ){
90343 if( pMem->szMalloc>0 ){
90344 sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
90346 pMem->z = pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, nByte);
90347 if( pMem->zMalloc==0 ){
90348 pMem->szMalloc = 0;
90351 pMem->szMalloc = nByte;
90354 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->zMalloc;
90356 pCx->eCurType = eCurType;
90357 pCx->nField = nField;
90358 pCx->aOffset = &pCx->aType[nField];
90360 pCx->uc.pCursor = (BtCursor*)
90361 &pMem->z[ROUND8P(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
90362 sqlite3BtreeCursorZero(pCx->uc.pCursor);
90380 return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc);
90400 u8 enc = pRec->enc;
90402 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str );
90403 rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc);
90405 if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){
90406 pRec->flags |= MEM_Int;
90408 pRec->u.r = rValue;
90409 pRec->flags |= MEM_Real;
90412 /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
90415 ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
90416 pRec->flags &= ~MEM_Str;
90426 ** floating-point representation if an integer representation
90436 ** No-op. pRec is unchanged.
90446 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
90447 if( (pRec->flags & MEM_Real)==0 ){
90448 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
90459 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
90460 if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){
90461 testcase( pRec->flags & MEM_Int );
90462 testcase( pRec->flags & MEM_Real );
90463 testcase( pRec->flags & MEM_IntReal );
90467 pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal);
90502 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
90508 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );
90509 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
90511 pMem->u.i = 0;
90514 rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
90516 if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){
90517 pMem->u.i = ix;
90522 }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){
90523 pMem->u.i = ix;
90533 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
90534 ** But it does set pMem->u.r and pMem->u.i appropriately.
90537 assert( (pMem->flags & MEM_Null)==0
90538 || pMem->db==0 || pMem->db->mallocFailed );
90539 if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null) ){
90540 testcase( pMem->flags & MEM_Int );
90541 testcase( pMem->flags & MEM_Real );
90542 testcase( pMem->flags & MEM_IntReal );
90543 return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null);
90545 assert( pMem->flags & (MEM_Str|MEM_Blob) );
90546 testcase( pMem->flags & MEM_Str );
90547 testcase( pMem->flags & MEM_Blob );
90557 int f = pMem->flags;
90575 for(i=0; i<25 && i<pMem->n; i++){
90576 sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF));
90579 for(i=0; i<25 && i<pMem->n; i++){
90580 char z = pMem->z[i];
90585 sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero);
90602 sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n);
90603 for(j=0; j<25 && j<pMem->n; j++){
90604 c = pMem->z[j];
90607 sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]);
90617 if( p->flags & MEM_Undefined ){
90619 }else if( p->flags & MEM_Null ){
90620 printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
90621 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
90622 printf(" si:%lld", p->u.i);
90623 }else if( (p->flags & (MEM_IntReal))!=0 ){
90624 printf(" ir:%lld", p->u.i);
90625 }else if( p->flags & MEM_Int ){
90626 printf(" i:%lld", p->u.i);
90628 }else if( p->flags & MEM_Real ){
90629 printf(" r:%.17g", p->u.r);
90640 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
90645 if( p->pScopyFrom ){
90646 printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg]));
90665 for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);
90671 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
90681 ** high-performance timing routines.
90691 ** the number of non-transaction savepoints currently in the
90701 for(p=db->pSavepoint; p; p=p->pNext) n++;
90702 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
90716 int rc = p->pSharedBlock->xAddRow(pCtx, p->addedRows);
90721 for(i=0; i<pOp->p2; i++){
90724 rc = p->pSharedBlock->xPutLong(pCtx, p->addedRows, i, (sqlite3_int64)pMem[i].u.i);
90728 rc = p->pSharedBlock->xPutDouble(pCtx, p->addedRows, i, pMem[i].u.r);
90735 rc = p->pSharedBlock->xPutString(pCtx, p->addedRows, i, pMem[i].z, pMem[i].n+1);
90739 rc = p->pSharedBlock->xPutBlob(pCtx, p->addedRows, i, pMem[i].z, pMem[i].n);
90743 rc = p->pSharedBlock->xPutNull(pCtx, p->addedRows, i);
90747 rc = p->pSharedBlock->xPutOther(pCtx, p->addedRows, i);
90763 ** Return the register of pOp->p2 after first preparing it to be
90768 pOut->flags = MEM_Int;
90773 assert( pOp->p2>0 );
90774 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
90775 pOut = &p->aMem[pOp->p2];
90777 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
90780 pOut->flags = MEM_Int;
90786 ** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
90787 ** with pOp->p3. Return the hash.
90793 assert( pOp->p4type==P4_INT32 );
90794 for(i=pOp->p3, mx=i+pOp->p4.i; i<mx; i++){
90796 if( p->flags & (MEM_Int|MEM_IntReal) ){
90797 h += p->u.i;
90798 }else if( p->flags & MEM_Real ){
90800 }else if( p->flags & (MEM_Str|MEM_Blob) ){
90801 h += p->n;
90802 if( p->flags & MEM_Zero ) h += p->u.nZero;
90819 return azTypes[sqlite3_value_type(pMem)-1];
90829 Op *aOp = p->aOp; /* Copy of p->aOp */
90838 sqlite3 *db = p->db; /* The database */
90846 Mem *aMem = p->aMem; /* Copy of p->aMem */
90856 assert( p->eVdbeState==VDBE_RUN_STATE ); /* sqlite3_step() verifies this */
90859 if( db->xProgress ){
90860 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
90861 assert( 0 < db->nProgressOps );
90862 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
90867 if( p->rc==SQLITE_NOMEM ){
90872 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
90873 testcase( p->rc!=SQLITE_OK );
90874 p->rc = SQLITE_OK;
90875 assert( p->bIsReader || p->readOnly!=0 );
90876 p->iCurrentTime = 0;
90877 assert( p->explain==0 );
90878 p->pResultSet = 0;
90879 db->busyHandler.nBusy = 0;
90880 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
90884 if( p->pc==0
90885 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
90890 if( p->db->flags & SQLITE_VdbeListing ){
90892 for(i=0; i<p->nOp; i++){
90896 if( p->db->flags & SQLITE_VdbeEQP ){
90897 for(i=0; i<p->nOp; i++){
90905 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
90909 for(pOp=&aOp[p->pc]; 1; pOp++){
90914 assert( pOp>=aOp && pOp<&aOp[p->nOp]);
90920 if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
90926 if( db->flags & SQLITE_VdbeTrace ){
90927 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
90928 test_trace_breakpoint((int)(pOp - aOp),pOp,p);
90938 sqlite3_interrupt_count--;
90948 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
90950 assert( pOp->p1>0 );
90951 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
90952 assert( memIsValid(&aMem[pOp->p1]) );
90953 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
90954 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
90957 assert( pOp->p2>0 );
90958 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
90959 assert( memIsValid(&aMem[pOp->p2]) );
90960 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
90961 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
90964 assert( pOp->p3>0 );
90965 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
90966 assert( memIsValid(&aMem[pOp->p3]) );
90967 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
90968 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
90971 assert( pOp->p2>0 );
90972 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
90973 memAboutToChange(p, &aMem[pOp->p2]);
90976 assert( pOp->p3>0 );
90977 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
90978 memAboutToChange(p, &aMem[pOp->p3]);
90986 switch( pOp->opcode ){
90993 ** the switch statement will break with convention and be flush-left. Another
91031 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
91041 if( pOp->p5 ){
91042 assert( pOp->p2 < (int)(pOp - aOp) );
91043 assert( pOp->p2 > 1 );
91044 pOp = &aOp[pOp->p2 - 2];
91051 pOp = &aOp[pOp->p2 - 1];
91062 ** faster according to "valgrind --tool=cachegrind" */
91064 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
91069 ** If the progress callback returns non-zero, exit the virtual machine with
91072 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
91073 assert( db->nProgressOps!=0 );
91074 nProgressLimit += db->nProgressOps;
91075 if( db->xProgress(db->pProgressArg) ){
91092 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
91093 pIn1 = &aMem[pOp->p1];
91096 pIn1->flags = MEM_Int;
91097 pIn1->u.i = (int)(pOp-aOp);
91098 REGISTER_TRACE(pOp->p1, pIn1);
91109 ** OP_Return becomes a no-op. If P3 is 0, then register P1 must hold an
91116 ** P2 is not used by the byte-code engine. However, if P2 is positive
91121 ** value is a byte-code indentation hint. See tag-20220407a in
91125 pIn1 = &aMem[pOp->p1];
91126 if( pIn1->flags & MEM_Int ){
91127 if( pOp->p3 ){ VdbeBranchTaken(1, 2); }
91128 pOp = &aOp[pIn1->u.i];
91129 }else if( ALWAYS(pOp->p3) ){
91147 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
91148 assert( pOp->p2>=0 && pOp->p2<p->nOp );
91149 assert( pOp->p3>=0 && pOp->p3<p->nOp );
91150 pOut = &aMem[pOp->p1];
91152 pOut->u.i = pOp->p3 - 1;
91153 pOut->flags = MEM_Int;
91154 if( pOp->p2==0 ) break;
91159 assert( pOp->p2>0 ); /* There are never any jumps to instruction 0 */
91160 assert( pOp->p2<p->nOp ); /* Jumps must be in range */
91161 pOp = &aOp[pOp->p2 - 1];
91175 pIn1 = &aMem[pOp->p1];
91176 assert( pIn1->flags==MEM_Int );
91177 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
91178 pCaller = &aOp[pIn1->u.i];
91179 assert( pCaller->opcode==OP_Yield );
91180 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
91181 pOp = &aOp[pCaller->p2 - 1];
91182 pIn1->flags = MEM_Undefined;
91201 pIn1 = &aMem[pOp->p1];
91203 pIn1->flags = MEM_Int;
91204 pcDest = (int)pIn1->u.i;
91205 pIn1->u.i = (int)(pOp - aOp);
91206 REGISTER_TRACE(pOp->p1, pIn1);
91216 ** value in register P3 is not NULL, then this routine is a no-op.
91220 pIn3 = &aMem[pOp->p3];
91222 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
91224 if( (pIn3->flags & MEM_Null)==0 ) break;
91264 if( p->pSharedBlock!=NULL ){
91265 p->pSharedBlock->xFinish(p->pSharedBlock->pContext, p->addedRows, p->totalRows);
91270 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
91272 if( p->pFrame && pOp->p1==SQLITE_OK ){
91273 /* Halt the sub-program. Return control to the parent frame. */
91274 pFrame = p->pFrame;
91275 p->pFrame = pFrame->pParent;
91276 p->nFrame--;
91277 sqlite3VdbeSetChanges(db, p->nChange);
91279 if( pOp->p2==OE_Ignore ){
91280 /* Instruction pcx is the OP_Program that invoked the sub-program
91282 ** instruction is set to OE_Ignore, then the sub-program is throwing
91285 pcx = p->aOp[pcx].p2-1;
91287 aOp = p->aOp;
91288 aMem = p->aMem;
91292 p->rc = pOp->p1;
91293 p->errorAction = (u8)pOp->p2;
91294 assert( pOp->p5<=4 );
91295 if( p->rc ){
91296 if( pOp->p5 ){
91299 testcase( pOp->p5==1 );
91300 testcase( pOp->p5==2 );
91301 testcase( pOp->p5==3 );
91302 testcase( pOp->p5==4 );
91303 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
91304 if( pOp->p4.z ){
91305 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
91308 sqlite3VdbeError(p, "%s", pOp->p4.z);
91310 pcx = (int)(pOp - aOp);
91311 sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
91316 p->rc = SQLITE_BUSY;
91318 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
91319 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
91320 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
91328 ** The 32-bit integer value P1 is written into register P2.
91332 pOut->u.i = pOp->p1;
91339 ** P4 is a pointer to a 64-bit integer value.
91344 assert( pOp->p4.pI64!=0 );
91345 pOut->u.i = *pOp->p4.pI64;
91353 ** P4 is a pointer to a 64-bit floating point value.
91358 pOut->flags = MEM_Real;
91359 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
91360 pOut->u.r = *pOp->p4.pReal;
91368 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
91374 assert( pOp->p4.z!=0 );
91376 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
91380 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
91384 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
91386 pOut->szMalloc = 0;
91387 pOut->flags |= MEM_Static;
91388 if( pOp->p4type==P4_DYNAMIC ){
91389 sqlite3DbFree(db, pOp->p4.z);
91391 pOp->p4type = P4_DYNAMIC;
91392 pOp->p4.z = pOut->z;
91393 pOp->p1 = pOut->n;
91396 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
91399 pOp->opcode = OP_String;
91418 assert( pOp->p4.z!=0 );
91420 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
91421 pOut->z = pOp->p4.z;
91422 pOut->n = pOp->p1;
91423 pOut->enc = encoding;
91426 if( pOp->p3>0 ){
91427 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
91428 pIn3 = &aMem[pOp->p3];
91429 assert( pIn3->flags & MEM_Int );
91430 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
91439 ** Mark the beginning of a subroutine that can be entered in-line
91443 ** If the subroutine is entered in-line, then the OP_Return will simply
91449 ** a no-op that simply falls through to the next instruction (assuming that
91451 ** entered in-line, then the OP_Return will cause in-line execution to
91466 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
91475 cnt = pOp->p3-pOp->p2;
91476 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
91477 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
91478 pOut->n = 0;
91480 pOut->uTemp = 0;
91486 pOut->flags = nullFlag;
91487 pOut->n = 0;
91488 cnt--;
91502 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
91503 pOut = &aMem[pOp->p1];
91504 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
91513 ** a zero-filled blob that is P1 bytes long in P2.
91516 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
91518 if( pOp->p4.z==0 ){
91519 sqlite3VdbeMemSetZeroBlob(pOut, pOp->p1);
91522 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
91524 pOut->enc = encoding;
91540 assert( pOp->p1>0 && pOp->p1<=p->nVar );
91541 assert( pOp->p4.z==0 || pOp->p4.z==sqlite3VListNumToName(p->pVList,pOp->p1) );
91542 pVar = &p->aVar[pOp->p1 - 1];
91546 pOut = &aMem[pOp->p2];
91549 pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
91550 pOut->flags |= MEM_Static|MEM_FromBind;
91558 ** Move the P3 values in register P1..P1+P3-1 over into
91559 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
91561 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
91569 n = pOp->p3;
91570 p1 = pOp->p1;
91571 p2 = pOp->p2;
91578 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
91579 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
91584 pIn1->pScopyFrom = 0;
91586 for(i=1; i<p->nMem; i++){
91597 }while( --n );
91617 n = pOp->p3;
91618 pIn1 = &aMem[pOp->p1];
91619 pOut = &aMem[pOp->p2];
91625 if( (pOut->flags & MEM_Subtype)!=0 && (pOp->p5 & 0x0002)!=0 ){
91626 pOut->flags &= ~MEM_Subtype;
91629 pOut->pScopyFrom = 0;
91631 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
91632 if( (n--)==0 ) break;
91653 pIn1 = &aMem[pOp->p1];
91654 pOut = &aMem[pOp->p2];
91658 pOut->pScopyFrom = pIn1;
91659 pOut->mScopyFlags = pIn1->flags;
91673 pIn1 = &aMem[pOp->p1];
91674 assert( (pIn1->flags & MEM_Int)!=0 );
91675 pOut = &aMem[pOp->p2];
91676 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
91684 ** constraint violations, this is a no-op.
91701 ** The registers P1 through P1+P2-1 contain a single row of
91704 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
91708 assert( p->nResColumn==pOp->p2 );
91709 assert( pOp->p1>0 || CORRUPT_DB );
91710 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
91713 if( p->pSharedBlock!=NULL ){
91714 void *pCtx = p->pSharedBlock->pContext;
91715 p->totalRows++;
91716 if( p->totalRows<=p->startPos || p->blockFull ){
91719 Mem *pMem = &aMem[pOp->p1];
91721 …if( rc==SQLITE_FULL && p->addedRows && (p->startPos + p->addedRows) <= p->pSharedBlock->requiredPo…
91722 p->startPos += p->addedRows;
91723 p->addedRows = 0;
91724 p->pSharedBlock->xReset(pCtx,p->startPos);
91725 p->blockFull = 0;
91730 p->addedRows++;
91732 p->blockFull = 1;
91738 if( p->blockFull && p->pSharedBlock->countAllRows==0 ){
91739 p->pSharedBlock->xFinish(pCtx, p->addedRows, p->totalRows);
91742 }else if( p->blockFull && p->pSharedBlock->countAllRows==1 ){
91750 p->cacheCtr = (p->cacheCtr + 2)|1;
91751 p->pResultSet = &aMem[pOp->p1];
91754 Mem *pMem = p->pResultSet;
91756 for(i=0; i<pOp->p2; i++){
91758 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
91768 if( db->mallocFailed ) goto no_mem;
91769 if( db->mTrace & SQLITE_TRACE_ROW ){
91770 db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
91772 p->pc = (int)(pOp - aOp) + 1;
91795 pIn1 = &aMem[pOp->p1];
91796 pIn2 = &aMem[pOp->p2];
91797 pOut = &aMem[pOp->p3];
91800 flags1 = pIn1->flags;
91802 testcase( pIn2->flags & MEM_Null );
91803 if( (flags1 | pIn2->flags) & MEM_Null ){
91809 flags1 = pIn1->flags & ~MEM_Str;
91812 flags1 = pIn1->flags & ~MEM_Str;
91814 flags2 = pIn2->flags;
91817 flags2 = pIn2->flags & ~MEM_Str;
91820 flags2 = pIn2->flags & ~MEM_Str;
91822 nByte = pIn1->n + pIn2->n;
91823 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
91831 memcpy(pOut->z, pIn2->z, pIn2->n);
91832 assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
91833 pIn2->flags = flags2;
91835 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
91836 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
91837 pIn1->flags = flags1;
91839 pOut->z[nByte]=0;
91840 pOut->z[nByte+1] = 0;
91841 pOut->flags |= MEM_Term;
91842 pOut->n = (int)nByte;
91843 pOut->enc = encoding;
91864 ** Synopsis: r[P3]=r[P2]-r[P1]
91898 pIn1 = &aMem[pOp->p1];
91899 type1 = pIn1->flags;
91900 pIn2 = &aMem[pOp->p2];
91901 type2 = pIn2->flags;
91902 pOut = &aMem[pOp->p3];
91905 iA = pIn1->u.i;
91906 iB = pIn2->u.i;
91907 switch( pOp->opcode ){
91913 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
91919 if( iA==-1 ) iA = 1;
91924 pOut->u.i = iB;
91935 switch( pOp->opcode ){
91937 case OP_Subtract: rB -= rA; break;
91949 if( iA==-1 ) iA = 1;
91955 pOut->u.i = rB;
91961 pOut->u.r = rB;
91976 ** be returned. This is used by the built-in min(), max() and nullif()
91985 ** publicly. Only built-in functions have access to this feature.
91988 assert( pOp->p4type==P4_COLLSEQ );
91989 if( pOp->p1 ){
91990 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
91998 ** Take the bit-wise AND of the values in register P1 and P2 and
92005 ** Take the bit-wise OR of the values in register P1 and P2 and
92034 pIn1 = &aMem[pOp->p1];
92035 pIn2 = &aMem[pOp->p2];
92036 pOut = &aMem[pOp->p3];
92037 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
92043 op = pOp->opcode;
92054 op = 2*OP_ShiftLeft + 1 - op;
92055 iB = iB>(-64) ? -iB : 64;
92059 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
92066 /* Sign-extend on a right shift of a negative number */
92067 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
92072 pOut->u.i = iA;
92086 pIn1 = &aMem[pOp->p1];
92089 pIn1->u.i += pOp->p2;
92101 pIn1 = &aMem[pOp->p1];
92102 if( (pIn1->flags & MEM_Int)==0 ){
92104 if( (pIn1->flags & MEM_Int)==0 ){
92106 if( pOp->p2==0 ){
92130 pIn1 = &aMem[pOp->p1];
92131 if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
92132 testcase( pIn1->flags & MEM_Int );
92133 testcase( pIn1->flags & MEM_IntReal );
92135 REGISTER_TRACE(pOp->p1, pIn1);
92158 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
92159 testcase( pOp->p2==SQLITE_AFF_TEXT );
92160 testcase( pOp->p2==SQLITE_AFF_BLOB );
92161 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
92162 testcase( pOp->p2==SQLITE_AFF_INTEGER );
92163 testcase( pOp->p2==SQLITE_AFF_REAL );
92164 pIn1 = &aMem[pOp->p1];
92168 rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
92171 REGISTER_TRACE(pOp->p1, pIn1);
92182 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
92226 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
92276 u16 flags1; /* Copy of initial value of pIn1->flags */
92277 u16 flags3; /* Copy of initial value of pIn3->flags */
92279 pIn1 = &aMem[pOp->p1];
92280 pIn3 = &aMem[pOp->p3];
92281 flags1 = pIn1->flags;
92282 flags3 = pIn3->flags;
92284 assert( (pOp->p5 & SQLITE_AFF_MASK)!=SQLITE_AFF_TEXT || CORRUPT_DB );
92286 if( pIn3->u.i > pIn1->u.i ){
92287 if( sqlite3aGTb[pOp->opcode] ){
92288 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
92292 }else if( pIn3->u.i < pIn1->u.i ){
92293 if( sqlite3aLTb[pOp->opcode] ){
92294 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
92297 iCompare = -1;
92299 if( sqlite3aEQb[pOp->opcode] ){
92300 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
92305 VdbeBranchTaken(0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
92310 if( pOp->p5 & SQLITE_NULLEQ ){
92316 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
92317 testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
92323 res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
92331 if( pOp->p5 & SQLITE_JUMPIFNULL ){
92338 /* Neither operand is NULL and we couldn't do the special high-speed
92339 ** integer comparison case. So do a general-case comparison. */
92340 affinity = pOp->p5 & SQLITE_AFF_MASK;
92345 testcase( flags3==pIn3->flags );
92346 flags3 = pIn3->flags;
92354 testcase( pIn1->flags & MEM_Int );
92355 testcase( pIn1->flags & MEM_Real );
92356 testcase( pIn1->flags & MEM_IntReal );
92358 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
92359 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
92363 testcase( pIn3->flags & MEM_Int );
92364 testcase( pIn3->flags & MEM_Real );
92365 testcase( pIn3->flags & MEM_IntReal );
92367 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
92368 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
92371 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
92372 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
92384 res2 = sqlite3aLTb[pOp->opcode];
92386 res2 = sqlite3aEQb[pOp->opcode];
92388 res2 = sqlite3aGTb[pOp->opcode];
92393 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
92394 pIn3->flags = flags3;
92395 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
92396 pIn1->flags = flags1;
92398 VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
92420 /* Verify the preconditions of this opcode - that it follows an OP_Lt or
92423 for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
92447 assert( pOp->p4type==P4_INTARRAY );
92448 assert( pOp->p4.ai );
92455 ** Synopsis: r[P1@P3] <-> r[P2@P3]
92457 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
92458 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
92487 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
92491 assert( pOp[-1].opcode==OP_Permutation );
92492 assert( pOp[-1].p4type==P4_INTARRAY );
92493 aPermute = pOp[-1].p4.ai + 1;
92496 n = pOp->p3;
92497 pKeyInfo = pOp->p4.pKeyInfo;
92500 p1 = pOp->p1;
92501 p2 = pOp->p2;
92506 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
92507 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
92509 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
92510 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
92519 assert( i<pKeyInfo->nKeyField );
92520 pColl = pKeyInfo->aColl[i];
92521 bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
92524 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
92527 iCompare = -iCompare;
92529 if( bRev ) iCompare = -iCompare;
92547 if( pOp->p5&0x80 ){
92548 if( p->pSharedBlock!=NULL ){
92549 if( p->totalRows < p->startPos || p->blockFull ){
92550 p->totalRows++;
92551 pOp = &aOp[pOp->p2 - 1];
92557 assert( pOp>aOp && pOp[-1].opcode==OP_Compare );
92559 VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
92561 VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
92563 VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
92593 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
92594 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
92595 if( pOp->opcode==OP_And ){
92602 pOut = &aMem[pOp->p3];
92606 pOut->u.i = v1;
92633 assert( pOp->p4type==P4_INT32 );
92634 assert( pOp->p4.i==0 || pOp->p4.i==1 );
92635 assert( pOp->p3==0 || pOp->p3==1 );
92636 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
92637 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
92649 pIn1 = &aMem[pOp->p1];
92650 pOut = &aMem[pOp->p2];
92651 if( (pIn1->flags & MEM_Null)==0 ){
92663 ** ones-complement of the P1 value into register P2. If P1 holds
92667 pIn1 = &aMem[pOp->p1];
92668 pOut = &aMem[pOp->p2];
92670 if( (pIn1->flags & MEM_Null)==0 ){
92671 pOut->flags = MEM_Int;
92672 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
92680 ** encountered on each invocation of the byte-code program. Jump to P2
92683 ** Top-level programs determine first invocation by comparing the P1
92691 ** because the self-altering code trick does not work for recursive
92696 assert( p->aOp[0].opcode==OP_Init );
92697 if( p->pFrame ){
92698 iAddr = (int)(pOp - p->aOp);
92699 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
92703 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
92705 if( p->aOp[0].p1==pOp->p1 ){
92711 pOp->p1 = p->aOp[0].p1;
92718 ** is considered true if it is numeric and non-zero. If the value
92719 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
92723 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
92733 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
92737 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
92749 pIn1 = &aMem[pOp->p1];
92750 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
92751 if( (pIn1->flags & MEM_Null)!=0 ){
92770 ** If P1 is -1, then P3 is a register number and the datatype is taken
92787 assert( pOp->p1>=(-1) && pOp->p1<p->nCursor );
92788 assert( pOp->p1>=0 || (pOp->p3>=0 && pOp->p3<=(p->nMem+1 - p->nCursor)) );
92789 if( pOp->p1>=0 ){
92790 pC = p->apCsr[pOp->p1];
92792 assert( pOp->p3>=0 );
92793 if( pOp->p3<pC->nHdrParsed ){
92794 serialType = pC->aType[pOp->p3];
92821 typeMask = 1 << (pOp->p4.i - 1);
92829 assert( memIsValid(&aMem[pOp->p3]) );
92830 typeMask = 1 << (sqlite3_value_type((sqlite3_value*)&aMem[pOp->p3])-1);
92837 VdbeBranchTaken( (typeMask & pOp->p5)!=0, 2);
92838 if( typeMask & pOp->p5 ){
92852 if( (aMem[pOp->p1].flags & MEM_Null)!=0
92853 || (aMem[pOp->p3].flags & MEM_Null)!=0
92855 sqlite3VdbeMemSetNull(aMem + pOp->p2);
92857 sqlite3VdbeMemSetInt64(aMem + pOp->p2, 0);
92868 pIn1 = &aMem[pOp->p1];
92869 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
92870 if( (pIn1->flags & MEM_Null)==0 ){
92884 ** If P1 is not an open cursor, then this opcode is a no-op.
92888 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
92889 pC = p->apCsr[pOp->p1];
92890 if( ALWAYS(pC) && pC->nullRow ){
92891 sqlite3VdbeMemSetNull(aMem + pOp->p3);
92911 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
92915 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
92916 pC = p->apCsr[pOp->p1];
92917 pOut = &p->aMem[pOp->p3];
92918 if( pC==0 || pC->eCurType!=CURTYPE_BTREE ){
92921 if( pC->deferredMoveto ){
92925 if( sqlite3BtreeEof(pC->uc.pCursor) ){
92928 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
92940 ** information about the format of the data.) Extract the P2-th column
92960 BtCursor *pCrsr; /* The B-Tree cursor corresponding to pC */
92961 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
92969 u64 offset64; /* 64-bit offset */
92973 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
92974 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
92975 pC = p->apCsr[pOp->p1];
92976 p2 = (u32)pOp->p2;
92980 assert( p2<(u32)pC->nField
92981 || (pC->eCurType==CURTYPE_PSEUDO && pC->seekResult==0) );
92982 aOffset = pC->aOffset;
92983 assert( aOffset==pC->aType+pC->nField );
92984 assert( pC->eCurType!=CURTYPE_VTAB );
92985 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
92986 assert( pC->eCurType!=CURTYPE_SORTER );
92988 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
92989 if( pC->nullRow ){
92990 if( pC->eCurType==CURTYPE_PSEUDO && pC->seekResult>0 ){
92991 /* For the special case of as pseudo-cursor, the seekResult field
92993 pReg = &aMem[pC->seekResult];
92994 assert( pReg->flags & MEM_Blob );
92996 pC->payloadSize = pC->szRow = pReg->n;
92997 pC->aRow = (u8*)pReg->z;
92999 pDest = &aMem[pOp->p3];
93005 pCrsr = pC->uc.pCursor;
93006 if( pC->deferredMoveto ){
93008 assert( !pC->isEphemeral );
93009 if( pC->ub.aAltMap && (iMap = pC->ub.aAltMap[1+p2])>0 ){
93010 pC = pC->pAltCursor;
93011 p2 = iMap - 1;
93021 assert( pC->eCurType==CURTYPE_BTREE );
93024 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
93025 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
93026 assert( pC->szRow<=pC->payloadSize );
93027 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
93029 pC->cacheStatus = p->cacheCtr;
93030 if( (aOffset[0] = pC->aRow[0])<0x80 ){
93031 pC->iHdrOffset = 1;
93033 pC->iHdrOffset = sqlite3GetVarint32(pC->aRow, aOffset);
93035 pC->nHdrParsed = 0;
93037 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
93038 /* pC->aRow does not have to hold the entire row, but it does at least
93039 ** need to cover the header of the record. If pC->aRow does not contain
93042 pC->aRow = 0;
93043 pC->szRow = 0;
93051 ** 3-byte type for each of the maximum of 32768 columns plus three
93054 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
93059 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
93071 zData = pC->aRow;
93072 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
93076 }else if( sqlite3BtreeCursorHasMoved(pC->uc.pCursor) ){
93083 ** parsed and valid information is in aOffset[] and pC->aType[].
93085 if( pC->nHdrParsed<=p2 ){
93087 ** to extract additional fields up through the p2+1-th field
93089 if( pC->iHdrOffset<aOffset[0] ){
93091 if( pC->aRow==0 ){
93093 rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
93097 zData = pC->aRow;
93100 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
93102 i = pC->nHdrParsed;
93104 zHdr = zData + pC->iHdrOffset;
93108 if( (pC->aType[i] = t = zHdr[0])<0x80 ){
93113 pC->aType[i] = t;
93124 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
93125 || (offset64 > pC->payloadSize)
93131 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
93136 pC->nHdrParsed = i;
93137 pC->iHdrOffset = (u32)(zHdr - zData);
93138 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
93147 if( pC->nHdrParsed<=p2 ){
93148 pDest = &aMem[pOp->p3];
93150 if( pOp->p4type==P4_MEM ){
93151 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
93158 t = pC->aType[p2];
93161 /* Extract the content for the p2+1-th column. Control can only
93162 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
93165 assert( p2<pC->nHdrParsed );
93167 pDest = &aMem[pOp->p3];
93173 assert( t==pC->aType[p2] );
93174 if( pC->szRow>=aOffset[p2+1] ){
93176 ** page - where the content is not on an overflow page */
93177 zData = pC->aRow + aOffset[p2];
93182 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
93186 pDest->n = len = (t-12)/2;
93187 pDest->enc = encoding;
93188 if( pDest->szMalloc < len+2 ){
93189 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
93190 pDest->flags = MEM_Null;
93193 pDest->z = pDest->zMalloc;
93195 memcpy(pDest->z, zData, len);
93196 pDest->z[len] = 0;
93197 pDest->z[len+1] = 0;
93198 pDest->flags = aFlag[t&1];
93201 pDest->enc = encoding;
93203 if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
93204 && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
93222 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
93223 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, aOffset[p2], len, pDest);
93225 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
93226 pDest->flags &= ~MEM_Ephem;
93232 REGISTER_TRACE(pOp->p3, pDest);
93237 pOp = &aOp[aOp[0].p3-1];
93257 ** is zero. When P3 is non-zero, no type checking occurs for
93264 ** <li> P2 should be the number of non-virtual columns in the
93276 assert( pOp->p4type==P4_TABLE );
93277 pTab = pOp->p4.pTab;
93278 assert( pTab->tabFlags & TF_Strict );
93279 assert( pTab->nNVCol==pOp->p2 );
93280 aCol = pTab->aCol;
93281 pIn1 = &aMem[pOp->p1];
93282 for(i=0; i<pTab->nCol; i++){
93285 if( pOp->p3 ){ pIn1++; continue; }
93287 assert( pIn1 < &aMem[pOp->p1+pOp->p2] );
93289 if( (pIn1->flags & MEM_Null)==0 ){
93292 if( (pIn1->flags & MEM_Blob)==0 ) goto vdbe_type_error;
93297 if( (pIn1->flags & MEM_Int)==0 ) goto vdbe_type_error;
93301 if( (pIn1->flags & MEM_Str)==0 ) goto vdbe_type_error;
93305 testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_Real );
93306 testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_IntReal );
93307 if( pIn1->flags & MEM_Int ){
93310 ** so that we keep the high-resolution integer value but know that
93312 testcase( pIn1->u.i==140737488355328LL );
93313 testcase( pIn1->u.i==140737488355327LL );
93314 testcase( pIn1->u.i==-140737488355328LL );
93315 testcase( pIn1->u.i==-140737488355329LL );
93316 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
93317 pIn1->flags |= MEM_IntReal;
93318 pIn1->flags &= ~MEM_Int;
93320 pIn1->u.r = (double)pIn1->u.i;
93321 pIn1->flags |= MEM_Real;
93322 pIn1->flags &= ~MEM_Int;
93324 }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
93335 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
93338 assert( pIn1 == &aMem[pOp->p1+pOp->p2] );
93343 vdbeMemTypeName(pIn1), sqlite3StdType[aCol[i].eCType-1],
93344 pTab->zName, aCol[i].zCnName);
93354 ** P4 is a string that is P2 characters long. The N-th character of the
93355 ** string indicates the column affinity that should be used for the N-th
93361 zAffinity = pOp->p4.z;
93363 assert( pOp->p2>0 );
93364 assert( zAffinity[pOp->p2]==0 );
93365 pIn1 = &aMem[pOp->p1];
93366 while( 1 /*exit-by-break*/ ){
93367 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
93370 if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
93373 ** so that we keep the high-resolution integer value but know that
93375 testcase( pIn1->u.i==140737488355328LL );
93376 testcase( pIn1->u.i==140737488355327LL );
93377 testcase( pIn1->u.i==-140737488355328LL );
93378 testcase( pIn1->u.i==-140737488355329LL );
93379 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
93380 pIn1->flags |= MEM_IntReal;
93381 pIn1->flags &= ~MEM_Int;
93383 pIn1->u.r = (double)pIn1->u.i;
93384 pIn1->flags |= MEM_Real;
93385 pIn1->flags &= ~MEM_Int;
93388 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
93403 ** P4 may be a string that is P2 characters long. The N-th character of the
93404 ** string indicates the column affinity that should be used for the N-th
93413 ** compile-time option is enabled:
93416 ** of the right-most table that can be null-trimmed.
93420 ** accept no-change records with serial_type 10. This value is
93442 ** ------------------------------------------------------------------------
93443 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
93444 ** ------------------------------------------------------------------------
93451 ** hdr-size field is also a varint which is the offset from the beginning
93457 nField = pOp->p1;
93458 zAffinity = pOp->p4.z;
93459 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
93461 nField = pOp->p2;
93462 pLast = &pData0[nField-1];
93465 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
93466 pOut = &aMem[pOp->p3];
93476 if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
93477 pRec->flags |= MEM_IntReal;
93478 pRec->flags &= ~(MEM_Int);
93480 REGISTER_TRACE((int)(pRec-aMem), pRec);
93490 ** have a non-NULL default value. Also, the record must be left with
93492 ** index of the right-most column with a non-NULL default value */
93493 if( pOp->p5 ){
93494 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
93495 pLast--;
93496 nField--;
93503 ** the Mem.uTemp field of each term should hold the serial-type that will
93507 ** --------------- ---------------
93509 ** 1 1-byte signed integer
93510 ** 2 2-byte signed integer
93511 ** 3 3-byte signed integer
93512 ** 4 4-byte signed integer
93513 ** 5 6-byte signed integer
93514 ** 6 8-byte signed integer
93530 if( pRec->flags & MEM_Null ){
93531 if( pRec->flags & MEM_Zero ){
93535 ** Give such values a special internal-use-only serial-type of 10
93539 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
93541 pRec->uTemp = 10;
93543 pRec->uTemp = 0;
93546 }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
93548 i64 i = pRec->u.i;
93550 testcase( pRec->flags & MEM_Int );
93551 testcase( pRec->flags & MEM_IntReal );
93564 if( (i&1)==i && p->minWriteFileFormat>=4 ){
93565 pRec->uTemp = 8+(u32)uu;
93568 pRec->uTemp = 1;
93572 pRec->uTemp = 2;
93575 pRec->uTemp = 3;
93578 pRec->uTemp = 4;
93581 pRec->uTemp = 5;
93584 if( pRec->flags & MEM_IntReal ){
93586 ** as an integer, then we might as well make it an 8-byte floating
93588 pRec->u.r = (double)pRec->u.i;
93589 pRec->flags &= ~MEM_IntReal;
93590 pRec->flags |= MEM_Real;
93591 pRec->uTemp = 7;
93593 pRec->uTemp = 6;
93596 }else if( pRec->flags & MEM_Real ){
93599 pRec->uTemp = 7;
93601 assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
93602 assert( pRec->n>=0 );
93603 len = (u32)pRec->n;
93604 serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
93605 if( pRec->flags & MEM_Zero ){
93606 serial_type += pRec->u.nZero*2;
93609 len += pRec->u.nZero;
93611 nZero += pRec->u.nZero;
93616 pRec->uTemp = serial_type;
93619 pRec--;
93622 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
93640 ** the new record. The output register (pOp->p3) is not allowed to
93644 if( nByte+nZero<=pOut->szMalloc ){
93647 pOut->z = pOut->zMalloc;
93651 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
93658 pOut->n = (int)nByte;
93659 pOut->flags = MEM_Blob;
93661 pOut->u.nZero = nZero;
93662 pOut->flags |= MEM_Zero;
93665 zHdr = (u8 *)pOut->z;
93676 while( 1 /*exit-by-break*/ ){
93677 serial_type = pRec->uTemp;
93678 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
93680 ** EVIDENCE-OF: R-64536-51728 The values for each column in the record
93690 assert( sizeof(v)==sizeof(pRec->u.r) );
93691 memcpy(&v, &pRec->u.r, sizeof(v));
93694 v = pRec->u.i;
93698 while( 1 /*exit-by-break*/ ){
93699 zPayload[--i] = (u8)(v&0xFF);
93707 if( serial_type>=14 && pRec->n>0 ){
93708 assert( pRec->z!=0 );
93709 memcpy(zPayload, pRec->z, pRec->n);
93710 zPayload += pRec->n;
93714 if( pRec->n ){
93715 assert( pRec->z!=0 );
93716 memcpy(zPayload, pRec->z, pRec->n);
93717 zPayload += pRec->n;
93723 assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
93724 assert( nByte==(int)(zPayload - (u8*)pOut->z) );
93726 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
93727 REGISTER_TRACE(pOp->p3, pOut);
93738 ** every btree page of the table. But if P3 is non-zero, an estimate
93745 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
93746 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
93748 if( pOp->p3 ){
93756 pOut->u.i = nEntry;
93777 p1 = pOp->p1;
93778 zName = pOp->p4.z;
93783 assert( db->pSavepoint==0 || db->autoCommit==0 );
93785 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
93787 assert( p->bIsReader );
93790 if( db->nVdbeWrite>0 ){
93794 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
93803 ** that the db->aVTrans[] array is empty. */
93804 assert( db->autoCommit==0 || db->nVTrans==0 );
93806 db->nStatement+db->nSavepoint);
93813 pNew->zName = (char *)&pNew[1];
93814 memcpy(pNew->zName, zName, nName+1);
93818 if( db->autoCommit ){
93819 db->autoCommit = 0;
93820 db->isTransactionSavepoint = 1;
93822 db->nSavepoint++;
93826 pNew->pNext = db->pSavepoint;
93827 db->pSavepoint = pNew;
93828 pNew->nDeferredCons = db->nDeferredCons;
93829 pNew->nDeferredImmCons = db->nDeferredImmCons;
93839 pSavepoint = db->pSavepoint;
93840 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
93841 pSavepoint = pSavepoint->pNext
93848 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
93852 sqlite3VdbeError(p, "cannot release savepoint - "
93861 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
93866 db->autoCommit = 1;
93868 p->pc = (int)(pOp - aOp);
93869 db->autoCommit = 0;
93870 p->rc = rc = SQLITE_BUSY;
93873 rc = p->rc;
93875 db->autoCommit = 0;
93877 db->isTransactionSavepoint = 0;
93881 iSavepoint = db->nSavepoint - iSavepoint - 1;
93883 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
93884 for(ii=0; ii<db->nDb; ii++){
93885 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
93894 for(ii=0; ii<db->nDb; ii++){
93895 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
93903 db->mDbFlags |= DBFLAG_SchemaChange;
93910 while( db->pSavepoint!=pSavepoint ){
93911 pTmp = db->pSavepoint;
93912 db->pSavepoint = pTmp->pNext;
93914 db->nSavepoint--;
93922 assert( pSavepoint==db->pSavepoint );
93923 db->pSavepoint = pSavepoint->pNext;
93926 db->nSavepoint--;
93930 db->nDeferredCons = pSavepoint->nDeferredCons;
93931 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
93941 if( p->eVdbeState==VDBE_HALT_STATE ){
93950 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
93961 desiredAutoCommit = pOp->p1;
93962 iRollback = pOp->p2;
93965 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
93966 assert( p->bIsReader );
93968 if( desiredAutoCommit!=db->autoCommit ){
93972 db->autoCommit = 1;
93973 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
93977 sqlite3VdbeError(p, "cannot commit transaction - "
93984 db->autoCommit = (u8)desiredAutoCommit;
93987 p->pc = (int)(pOp - aOp);
93988 db->autoCommit = (u8)(1-desiredAutoCommit);
93989 p->rc = rc = SQLITE_BUSY;
93993 if( p->rc==SQLITE_OK ){
94002 (iRollback)?"cannot rollback - no transaction is active":
94003 "cannot commit - no transaction is active"));
94015 ** If P2 is non-zero, then a write-transaction is started, or if a
94016 ** read-transaction is already active, it is upgraded to a write-transaction.
94017 ** If P2 is zero, then a read-transaction is started. If P2 is 2 or more
94025 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
94051 assert( p->bIsReader );
94052 assert( p->readOnly==0 || pOp->p2==0 );
94053 assert( pOp->p2>=0 && pOp->p2<=2 );
94054 assert( pOp->p1>=0 && pOp->p1<db->nDb );
94055 assert( DbMaskTest(p->btreeMask, pOp->p1) );
94057 if( pOp->p2 && (db->flags & (SQLITE_QueryOnly|SQLITE_CorruptRdOnly))!=0 ){
94058 if( db->flags & SQLITE_QueryOnly ){
94068 pDb = &db->aDb[pOp->p1];
94069 pBt = pDb->pBt;
94072 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
94077 p->pc = (int)(pOp - aOp);
94078 p->rc = rc;
94084 if( p->usesStmtJournal
94085 && pOp->p2
94086 && (db->autoCommit==0 || db->nVdbeRead>1)
94089 if( p->iStatement==0 ){
94090 assert( db->nStatement>=0 && db->nSavepoint>=0 );
94091 db->nStatement++;
94092 p->iStatement = db->nSavepoint + db->nStatement;
94095 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
94097 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
94103 p->nStmtDefCons = db->nDeferredCons;
94104 p->nStmtDefImmCons = db->nDeferredImmCons;
94107 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
94109 && pOp->p5
94110 && (iMeta!=pOp->p3 || pDb->pSchema->iGeneration!=pOp->p4.i)
94113 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
94117 sqlite3DbFree(db, p->zErrMsg);
94118 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
94119 /* If the schema-cookie from the database file matches the cookie
94120 ** stored with the in-memory representation of the schema, do
94123 ** If virtual-tables are in use, this is not just an optimization.
94124 ** Often, v-tables store their data in other SQLite tables, which
94125 ** are queried from within xNext() and other v-table methods using
94126 ** prepared queries. If such a query is out-of-date, we do not want to
94128 ** v-table would have to be ready for the sqlite3_vtab structure itself
94130 ** a v-table method.
94132 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
94133 sqlite3ResetOneSchema(db, pOp->p1);
94135 p->expired = 1;
94141 p->changeCntOn = 0;
94155 ** There must be a read-lock on the database (either a transaction
94164 assert( p->bIsReader );
94165 iDb = pOp->p1;
94166 iCookie = pOp->p3;
94167 assert( pOp->p3<SQLITE_N_BTREE_META );
94168 assert( iDb>=0 && iDb<db->nDb );
94169 assert( db->aDb[iDb].pBt!=0 );
94170 assert( DbMaskTest(p->btreeMask, iDb) );
94172 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
94174 pOut->u.i = iMeta;
94189 ** schema version is set to P3-P5. The "PRAGMA schema_version=N" statement
94197 assert( pOp->p2<SQLITE_N_BTREE_META );
94198 assert( pOp->p1>=0 && pOp->p1<db->nDb );
94199 assert( DbMaskTest(p->btreeMask, pOp->p1) );
94200 assert( p->readOnly==0 );
94201 pDb = &db->aDb[pOp->p1];
94202 assert( pDb->pBt!=0 );
94203 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
94205 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
94206 if( pOp->p2==BTREE_SCHEMA_VERSION ){
94208 *(u32*)&pDb->pSchema->schema_cookie = *(u32*)&pOp->p3 - pOp->p5;
94209 db->mDbFlags |= DBFLAG_SchemaChange;
94210 sqlite3FkClearTriggerCache(db, pOp->p1);
94211 }else if( pOp->p2==BTREE_FILE_FORMAT ){
94213 pDb->pSchema->file_format = pOp->p3;
94215 if( pOp->p1==1 ){
94219 p->expired = 0;
94228 ** Open a read-only cursor for the database table whose root page is
94245 ** object, then table being opened must be an [index b-tree] where the
94247 ** sequence of that index b-tree. Otherwise, if P4 is an integer
94248 ** value, then the table being opened must be a [table b-tree] with a
94258 ** b-tree and if it is this opcode becomes a no-op. In other words,
94280 ** OPFLAG_P2ISREG bit is set in P5 - see below).
94284 ** object, then table being opened must be an [index b-tree] where the
94286 ** sequence of that index b-tree. Otherwise, if P4 is an integer
94287 ** value, then the table being opened must be a [table b-tree] with a
94319 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
94320 assert( pOp->p4type==P4_KEYINFO );
94321 pCur = p->apCsr[pOp->p1];
94322 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
94323 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
94324 assert( pCur->eCurType==CURTYPE_BTREE );
94325 sqlite3BtreeClearCursor(pCur->uc.pCursor);
94333 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
94334 assert( p->bIsReader );
94335 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
94336 || p->readOnly==0 );
94338 if( p->expired==1 ){
94345 p2 = (u32)pOp->p2;
94346 iDb = pOp->p3;
94347 assert( iDb>=0 && iDb<db->nDb );
94348 assert( DbMaskTest(p->btreeMask, iDb) );
94349 pDb = &db->aDb[iDb];
94350 pX = pDb->pBt;
94352 if( pOp->opcode==OP_OpenWrite ){
94354 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
94356 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
94357 p->minWriteFileFormat = pDb->pSchema->file_format;
94362 if( pOp->p5 & OPFLAG_P2ISREG ){
94364 assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
94365 assert( pOp->opcode==OP_OpenWrite );
94368 assert( (pIn2->flags & MEM_Int)!=0 );
94370 p2 = (int)pIn2->u.i;
94377 if( pOp->p4type==P4_KEYINFO ){
94378 pKeyInfo = pOp->p4.pKeyInfo;
94379 assert( pKeyInfo->enc==ENC(db) );
94380 assert( pKeyInfo->db==db );
94381 nField = pKeyInfo->nAllField;
94382 }else if( pOp->p4type==P4_INT32 ){
94383 nField = pOp->p4.i;
94385 assert( pOp->p1>=0 );
94388 pCur = allocateCursor(p, pOp->p1, nField, CURTYPE_BTREE);
94390 pCur->iDb = iDb;
94391 pCur->nullRow = 1;
94392 pCur->isOrdered = 1;
94393 pCur->pgnoRoot = p2;
94395 pCur->wrFlag = wrFlag;
94397 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
94398 pCur->pKeyInfo = pKeyInfo;
94400 ** SQLite used to check if the root-page flags were sane at this point
94403 pCur->isTable = pOp->p4type!=P4_KEYINFO;
94408 testcase( pOp->p5 & OPFLAG_BULKCSR );
94409 testcase( pOp->p2 & OPFLAG_SEEKEQ );
94410 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
94411 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
94422 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
94428 pOrig = p->apCsr[pOp->p2];
94430 assert( pOrig->isEphemeral ); /* Only ephemeral cursors can be duplicated */
94432 pCx = allocateCursor(p, pOp->p1, pOrig->nField, CURTYPE_BTREE);
94434 pCx->nullRow = 1;
94435 pCx->isEphemeral = 1;
94436 pCx->pKeyInfo = pOrig->pKeyInfo;
94437 pCx->isTable = pOrig->isTable;
94438 pCx->pgnoRoot = pOrig->pgnoRoot;
94439 pCx->isOrdered = pOrig->isOrdered;
94440 pCx->ub.pBtx = pOrig->ub.pBtx;
94441 pCx->noReuse = 1;
94442 pOrig->noReuse = 1;
94443 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
94444 pCx->pKeyInfo, pCx->uc.pCursor);
94458 ** the main database is read-only. The ephemeral
94475 ** can be used as zero-length data for OP_Insert. This is an optimization
94497 assert( pOp->p1>=0 );
94498 assert( pOp->p2>=0 );
94499 if( pOp->p3>0 ){
94502 assert( pOp->p2==0 ); /* Only used when number of columns is zero */
94503 assert( pOp->opcode==OP_OpenEphemeral );
94504 assert( aMem[pOp->p3].flags & MEM_Null );
94505 aMem[pOp->p3].n = 0;
94506 aMem[pOp->p3].z = "";
94508 pCx = p->apCsr[pOp->p1];
94509 if( pCx && !pCx->noReuse && ALWAYS(pOp->p2<=pCx->nField) ){
94513 assert( pCx->isEphemeral );
94514 pCx->seqCount = 0;
94515 pCx->cacheStatus = CACHE_STALE;
94516 rc = sqlite3BtreeClearTable(pCx->ub.pBtx, pCx->pgnoRoot, 0);
94518 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_BTREE);
94520 pCx->isEphemeral = 1;
94521 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->ub.pBtx,
94522 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
94525 rc = sqlite3BtreeBeginTrans(pCx->ub.pBtx, 1, 0);
94530 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
94532 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
94533 assert( pOp->p4type==P4_KEYINFO );
94534 rc = sqlite3BtreeCreateTable(pCx->ub.pBtx, &pCx->pgnoRoot,
94535 BTREE_BLOBKEY | pOp->p5);
94537 assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
94538 assert( pKeyInfo->db==db );
94539 assert( pKeyInfo->enc==ENC(db) );
94540 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
94541 pKeyInfo, pCx->uc.pCursor);
94543 pCx->isTable = 0;
94545 pCx->pgnoRoot = SCHEMA_ROOT;
94546 rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
94547 0, pCx->uc.pCursor);
94548 pCx->isTable = 1;
94551 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
94553 sqlite3BtreeClose(pCx->ub.pBtx);
94558 pCx->nullRow = 1;
94566 ** tables using an external merge-sort algorithm.
94568 ** If argument P3 is non-zero, then it indicates that the sorter may
94575 assert( pOp->p1>=0 );
94576 assert( pOp->p2>=0 );
94577 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_SORTER);
94579 pCx->pKeyInfo = pOp->p4.pKeyInfo;
94580 assert( pCx->pKeyInfo->db==db );
94581 assert( pCx->pKeyInfo->enc==ENC(db) );
94582 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
94596 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
94597 pC = p->apCsr[pOp->p1];
94599 if( (pC->seqCount++)==0 ){
94613 ** A pseudo-table created by this opcode is used to hold a single
94616 ** is the only cursor opcode that works with a pseudo-table.
94619 ** the pseudo-table.
94624 assert( pOp->p1>=0 );
94625 assert( pOp->p3>=0 );
94626 pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);
94628 pCx->nullRow = 1;
94629 pCx->seekResult = pOp->p2;
94630 pCx->isTable = 1;
94631 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
94633 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
94635 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
94636 assert( pOp->p5==0 );
94643 ** currently open, this instruction is a no-op.
94646 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
94647 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
94648 p->apCsr[pOp->p1] = 0;
94657 ** table or index for cursor P1 are used. P4 is a 64-bit integer
94660 ** by the cursor. The high-order bit is set if any column after
94665 pC = p->apCsr[pOp->p1];
94666 assert( pC->eCurType==CURTYPE_BTREE );
94667 pC->maskUsed = *(u64*)pOp->p4.pI64;
94675 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
94702 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
94720 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
94738 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
94774 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
94775 assert( pOp->p2!=0 );
94776 pC = p->apCsr[pOp->p1];
94778 assert( pC->eCurType==CURTYPE_BTREE );
94782 assert( pC->isOrdered );
94783 assert( pC->uc.pCursor!=0 );
94784 oc = pOp->opcode;
94786 pC->nullRow = 0;
94788 pC->seekOp = pOp->opcode;
94791 pC->deferredMoveto = 0;
94792 pC->cacheStatus = CACHE_STALE;
94793 if( pC->isTable ){
94796 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
94802 pIn3 = &aMem[pOp->p3];
94803 flags3 = pIn3->flags;
94808 newType = pIn3->flags; /* Record the type after applying numeric affinity */
94809 pIn3->flags = flags3; /* But convert the type back to its original */
94820 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
94825 c = sqlite3IntFloatCompare(iKey, pIn3->u.r);
94831 ** (x > 4.9) -> (x >= 5)
94832 ** (x <= 4.9) -> (x < 5)
94835 assert( OP_SeekGE==(OP_SeekGT-1) );
94836 assert( OP_SeekLT==(OP_SeekLE-1) );
94838 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
94850 rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)iKey, 0, &res);
94851 pC->movetoTarget = iKey; /* Used by OP_Delete */
94861 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
94863 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
94865 assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
94866 assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
94873 nField = pOp->p4.i;
94874 assert( pOp->p4type==P4_INT32 );
94876 r.pKeyInfo = pC->pKeyInfo;
94881 ** r.default_rc = -1;
94886 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
94887 assert( oc!=OP_SeekGT || r.default_rc==-1 );
94888 assert( oc!=OP_SeekLE || r.default_rc==-1 );
94892 r.aMem = &aMem[pOp->p3];
94898 if( i>0 ) REGISTER_TRACE(pOp->p3+i, &r.aMem[i]);
94903 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &res);
94918 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
94934 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
94947 res = sqlite3BtreeEof(pC->uc.pCursor);
94951 assert( pOp->p2>0 );
94964 ** Synopsis: Scan-ahead up to P1 rows
94976 ** This opcode helps to optimize IN operators on a multi-column index
94979 ** of the b-tree instead. A correct answer is obtained if this opcode
94980 ** is omitted or is a no-op.
94987 ** then this opcode is a no-op and control passes through into the OP_SeekGE.
94999 ** This.P5 is true (non-zero) then a jump is made to This.P2. The P5==0
95039 /* If pOp->p5 is clear, then pOp->p2 points to the first instruction past the
95042 assert( pOp->p2>=(int)(pOp-aOp)+2 );
95044 if( pOp->p5==0 ){
95046 assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
95047 assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
95048 assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
95049 assert( aOp[pOp->p2-1].opcode==OP_IdxGT
95050 || aOp[pOp->p2-1].opcode==OP_IdxGE );
95051 testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
95054 assert( pOp->p2==(int)(pOp-aOp)+2 );
95055 assert( aOp[pOp->p2-1].opcode==OP_SeekGE );
95059 assert( pOp->p1>0 );
95060 pC = p->apCsr[pOp[1].p1];
95062 assert( pC->eCurType==CURTYPE_BTREE );
95063 assert( !pC->isTable );
95064 if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
95066 if( db->flags&SQLITE_VdbeTrace ){
95067 printf("... cursor not valid - fall through\n");
95072 nStep = pOp->p1;
95074 r.pKeyInfo = pC->pKeyInfo;
95091 if( res>0 && pOp->p5==0 ){
95095 if( db->flags&SQLITE_VdbeTrace ){
95096 printf("... %d steps and then skip\n", pOp->p1 - nStep);
95106 if( db->flags&SQLITE_VdbeTrace ){
95107 printf("... %d steps and then success\n", pOp->p1 - nStep);
95116 if( db->flags&SQLITE_VdbeTrace ){
95117 printf("... fall through after %d steps\n", pOp->p1);
95123 nStep--;
95124 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
95149 ** early, thus saving work. This is part of the IN-early-out optimization.
95151 ** P1 must be a valid b-tree cursor.
95155 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95156 pC = p->apCsr[pOp->p1];
95158 assert( pOp->p3>=pOp->p2 );
95159 if( pC->seekHit<pOp->p2 ){
95161 if( db->flags&SQLITE_VdbeTrace ){
95162 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p2);
95165 pC->seekHit = pOp->p2;
95166 }else if( pC->seekHit>pOp->p3 ){
95168 if( db->flags&SQLITE_VdbeTrace ){
95169 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p3);
95172 pC->seekHit = pOp->p3;
95186 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95187 pCur = p->apCsr[pOp->p1];
95188 VdbeBranchTaken(pCur==0 || pCur->nullRow, 2);
95189 if( pCur==0 || pCur->nullRow ){
95250 ** This opcode is used in IN clause processing for a multi-column key.
95252 ** left-most element, and if there are no matches on the most recent
95271 ** record are not-NULL then a check is done to determine if any row in the
95287 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95288 pC = p->apCsr[pOp->p1];
95291 if( db->flags&SQLITE_VdbeTrace ){
95292 printf("seekHit is %d\n", pC->seekHit);
95295 if( pC->seekHit>=pOp->p4.i ) break;
95309 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
95312 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95313 assert( pOp->p4type==P4_INT32 );
95314 pC = p->apCsr[pOp->p1];
95317 pC->seekOp = pOp->opcode;
95319 r.aMem = &aMem[pOp->p3];
95320 assert( pC->eCurType==CURTYPE_BTREE );
95321 assert( pC->uc.pCursor!=0 );
95322 assert( pC->isTable==0 );
95323 r.nField = (u16)pOp->p4.i;
95326 r.pKeyInfo = pC->pKeyInfo;
95332 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
95335 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &pC->seekResult);
95338 assert( r.aMem->flags & MEM_Blob );
95339 assert( pOp->opcode!=OP_NoConflict );
95343 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
95345 sqlite3VdbeRecordUnpack(pC->pKeyInfo, r.aMem->n, r.aMem->z, pIdxKey);
95346 pIdxKey->default_rc = 0;
95347 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &pC->seekResult);
95353 alreadyExists = (pC->seekResult==0);
95354 pC->nullRow = 1-alreadyExists;
95355 pC->deferredMoveto = 0;
95356 pC->cacheStatus = CACHE_STALE;
95357 if( pOp->opcode==OP_Found ){
95365 if( pOp->opcode==OP_NoConflict ){
95377 if( pOp->opcode==OP_IfNoHope ){
95378 pC->seekHit = pOp->p4.i;
95400 ** (with arbitrary multi-value keys).
95419 ** P3 register to contain a non-integer value, in which case the jump is
95423 ** (with arbitrary multi-value keys).
95437 pIn3 = &aMem[pOp->p3];
95438 testcase( pIn3->flags & MEM_Int );
95439 testcase( pIn3->flags & MEM_IntReal );
95440 testcase( pIn3->flags & MEM_Real );
95441 testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
95442 if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
95443 /* If pIn3->u.i does not contain an integer, compute iKey as the
95457 pIn3 = &aMem[pOp->p3];
95458 assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
95459 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95460 iKey = pIn3->u.i;
95462 pC = p->apCsr[pOp->p1];
95465 if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
95467 assert( pC->isTable );
95468 assert( pC->eCurType==CURTYPE_BTREE );
95469 pCrsr = pC->uc.pCursor;
95474 pC->movetoTarget = iKey; /* Used by OP_Delete */
95475 pC->nullRow = 0;
95476 pC->cacheStatus = CACHE_STALE;
95477 pC->deferredMoveto = 0;
95479 pC->seekResult = res;
95482 if( pOp->p2==0 ){
95501 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95502 assert( p->apCsr[pOp->p1]!=0 );
95503 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
95505 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
95538 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95539 pC = p->apCsr[pOp->p1];
95541 assert( pC->isTable );
95542 assert( pC->eCurType==CURTYPE_BTREE );
95543 assert( pC->uc.pCursor!=0 );
95546 ** thing) is obtained in a two-step algorithm.
95558 assert( pC->isTable );
95570 if( !pC->useRandomRowid ){
95571 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
95576 v = 1; /* IMP: R-61914-48074 */
95578 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
95579 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
95581 pC->useRandomRowid = 1;
95583 v++; /* IMP: R-29538-34987 */
95589 if( pOp->p3 ){
95591 assert( pOp->p3>0 );
95592 if( p->pFrame ){
95593 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
95595 assert( pOp->p3<=pFrame->nMem );
95596 pMem = &pFrame->aMem[pOp->p3];
95599 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
95600 pMem = &aMem[pOp->p3];
95605 REGISTER_TRACE(pOp->p3, pMem);
95607 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
95608 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
95609 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
95612 if( v<pMem->u.i+1 ){
95613 v = pMem->u.i + 1;
95615 pMem->u.i = v;
95618 if( pC->useRandomRowid ){
95619 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
95623 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
95629 }while( ((rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)v,
95635 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
95638 assert( v>0 ); /* EV: R-40812-03570 */
95640 pC->deferredMoveto = 0;
95641 pC->cacheStatus = CACHE_STALE;
95643 pOut->u.i = v;
95672 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
95675 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
95676 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
95689 const char *zDb; /* database name - used by the update hook */
95690 Table *pTab; /* Table structure - used by update and pre-update hooks */
95693 pData = &aMem[pOp->p2];
95694 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95696 pC = p->apCsr[pOp->p1];
95698 assert( pC->eCurType==CURTYPE_BTREE );
95699 assert( pC->deferredMoveto==0 );
95700 assert( pC->uc.pCursor!=0 );
95701 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
95702 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
95703 REGISTER_TRACE(pOp->p2, pData);
95706 pKey = &aMem[pOp->p3];
95707 assert( pKey->flags & MEM_Int );
95709 REGISTER_TRACE(pOp->p3, pKey);
95710 x.nKey = pKey->u.i;
95712 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
95713 assert( pC->iDb>=0 );
95714 zDb = db->aDb[pC->iDb].zDbSName;
95715 pTab = pOp->p4.pTab;
95716 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
95723 /* Invoke the pre-update hook, if any */
95725 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
95726 sqlite3VdbePreUpdateHook(p,pC,SQLITE_INSERT,zDb,pTab,x.nKey,pOp->p2,-1);
95728 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
95729 /* Prevent post-update hook from running in cases when it should not */
95733 if( pOp->p5 & OPFLAG_ISNOOP ) break;
95736 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
95737 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
95738 assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
95739 x.pData = pData->z;
95740 x.nData = pData->n;
95741 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
95742 if( pData->flags & MEM_Zero ){
95743 x.nZero = pData->u.nZero;
95748 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
95749 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
95752 pC->deferredMoveto = 0;
95753 pC->cacheStatus = CACHE_STALE;
95755 /* Invoke the update-hook if required. */
95758 assert( db->xUpdateCallback!=0 );
95759 assert( pTab->aCol!=0 );
95760 db->xUpdateCallback(db->pUpdateArg,
95761 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
95762 zDb, pTab->zName, x.nKey);
95770 ** of table - intkey or index. This opcode is used as part of copying
95783 assert( pOp[1].opcode==OP_Insert || pOp->p3==0 );
95784 assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
95786 pDest = p->apCsr[pOp->p1];
95787 pSrc = p->apCsr[pOp->p2];
95788 iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
95789 rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
95801 ** the next Next instruction will be a no-op. As a result, in this case
95815 ** P1 must not be pseudo-table. It has to be a real table with
95819 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
95821 ** this case. Specifically, if one is configured, the pre-update hook is
95822 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
95835 opflags = pOp->p2;
95836 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95837 pC = p->apCsr[pOp->p1];
95839 assert( pC->eCurType==CURTYPE_BTREE );
95840 assert( pC->uc.pCursor!=0 );
95841 assert( pC->deferredMoveto==0 );
95845 if( pOp->p4type==P4_TABLE
95846 && HasRowid(pOp->p4.pTab)
95847 && pOp->p5==0
95848 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
95851 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
95853 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
95854 assert( CORRUPT_DB || pC->movetoTarget==iKey );
95858 /* If the update-hook or pre-update-hook will be invoked, set zDb to
95863 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
95864 assert( pC->iDb>=0 );
95865 assert( pOp->p4.pTab!=0 );
95866 zDb = db->aDb[pC->iDb].zDbSName;
95867 pTab = pOp->p4.pTab;
95868 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
95869 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
95877 /* Invoke the pre-update-hook if required. */
95878 assert( db->xPreUpdateCallback==0 || pTab==pOp->p4.pTab );
95879 if( db->xPreUpdateCallback && pTab ){
95882 || (aMem[pOp->p3].flags & MEM_Int)
95886 zDb, pTab, pC->movetoTarget,
95887 pOp->p3, -1
95894 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
95899 if( p->pFrame==0 ){
95900 if( pC->isEphemeral==0
95901 && (pOp->p5 & OPFLAG_AUXDELETE)==0
95902 && (pC->wrFlag & OPFLAG_FORDELETE)==0
95906 if( pOp->p2 & OPFLAG_NCHANGE ){
95907 nExtraDelete--;
95912 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
95913 pC->cacheStatus = CACHE_STALE;
95914 pC->seekResult = 0;
95917 /* Invoke the update-hook if required. */
95919 p->nChange++;
95920 if( db->xUpdateCallback && ALWAYS(pTab!=0) && HasRowid(pTab) ){
95921 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
95922 pC->movetoTarget);
95923 assert( pC->iDb>=0 );
95937 sqlite3VdbeSetChanges(db, p->nChange);
95938 p->nChange = 0;
95962 pC = p->apCsr[pOp->p1];
95964 assert( pOp->p4type==P4_INT32 );
95965 pIn3 = &aMem[pOp->p3];
95966 nKeyCol = pOp->p4.i;
95982 ** a register that is the source for a pseudo-table cursor created using
95983 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
95990 pOut = &aMem[pOp->p2];
95991 pC = p->apCsr[pOp->p1];
95994 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
95995 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
95997 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
96014 ** of a real table, not a pseudo-table.
96018 ** register will be invalidated as soon as the cursor moves - including
96036 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96037 pC = p->apCsr[pOp->p1];
96039 assert( pC->eCurType==CURTYPE_BTREE );
96041 assert( pC->nullRow==0 );
96042 assert( pC->uc.pCursor!=0 );
96043 pCrsr = pC->uc.pCursor;
96053 assert( pC->deferredMoveto==0 );
96057 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
96063 if( !pOp->p3 ) Deephemeralize(pOut);
96065 REGISTER_TRACE(pOp->p2, pOut);
96086 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96087 pC = p->apCsr[pOp->p1];
96089 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
96090 if( pC->nullRow ){
96091 pOut->flags = MEM_Null;
96093 }else if( pC->deferredMoveto ){
96094 v = pC->movetoTarget;
96096 }else if( pC->eCurType==CURTYPE_VTAB ){
96097 assert( pC->uc.pVCur!=0 );
96098 pVtab = pC->uc.pVCur->pVtab;
96099 pModule = pVtab->pModule;
96100 assert( pModule->xRowid );
96101 rc = pModule->xRowid(pC->uc.pVCur, &v);
96106 assert( pC->eCurType==CURTYPE_BTREE );
96107 assert( pC->uc.pCursor!=0 );
96110 if( pC->nullRow ){
96111 pOut->flags = MEM_Null;
96114 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
96116 pOut->u.i = v;
96127 ** pseudo-cursor that always returns NULL for every column.
96132 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96133 pC = p->apCsr[pOp->p1];
96136 ** pseudo-cursor that always gives null rows. */
96137 pC = allocateCursor(p, pOp->p1, 1, CURTYPE_PSEUDO);
96139 pC->seekResult = 0;
96140 pC->isTable = 1;
96141 pC->noReuse = 1;
96142 pC->uc.pCursor = sqlite3BtreeFakeValidCursor();
96144 pC->nullRow = 1;
96145 pC->cacheStatus = CACHE_STALE;
96146 if( pC->eCurType==CURTYPE_BTREE ){
96147 assert( pC->uc.pCursor!=0 );
96148 sqlite3BtreeClearCursor(pC->uc.pCursor);
96151 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
96184 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96185 pC = p->apCsr[pOp->p1];
96187 assert( pC->eCurType==CURTYPE_BTREE );
96188 pCrsr = pC->uc.pCursor;
96192 pC->seekOp = pOp->opcode;
96194 if( pOp->opcode==OP_SeekEnd ){
96195 assert( pOp->p2==0 );
96196 pC->seekResult = -1;
96202 pC->nullRow = (u8)res;
96203 pC->deferredMoveto = 0;
96204 pC->cacheStatus = CACHE_STALE;
96206 if( pOp->p2>0 ){
96224 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96225 pC = p->apCsr[pOp->p1];
96227 pCrsr = pC->uc.pCursor;
96233 if( ALWAYS(sz>=0) && sqlite3LogEst((u64)sz)<pOp->p3 ) res = 1;
96266 sqlite3_search_count--;
96268 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
96289 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96290 assert( pOp->p5==0 );
96291 pC = p->apCsr[pOp->p1];
96293 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
96296 pC->seekOp = OP_Rewind;
96301 assert( pC->eCurType==CURTYPE_BTREE );
96302 pCrsr = pC->uc.pCursor;
96305 pC->deferredMoveto = 0;
96306 pC->cacheStatus = CACHE_STALE;
96309 pC->nullRow = (u8)res;
96310 assert( pOp->p2>0 && pOp->p2<p->nOp );
96327 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
96336 ** number P5-1 in the prepared statement is incremented.
96352 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
96361 ** number P5-1 in the prepared statement is incremented.
96373 pC = p->apCsr[pOp->p1];
96379 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96380 assert( pOp->p5==0
96381 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
96382 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
96383 pC = p->apCsr[pOp->p1];
96385 assert( pC->deferredMoveto==0 );
96386 assert( pC->eCurType==CURTYPE_BTREE );
96387 assert( pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
96388 || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope
96389 || pC->seekOp==OP_NullRow);
96390 rc = sqlite3BtreePrevious(pC->uc.pCursor, pOp->p3);
96394 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96395 assert( pOp->p5==0
96396 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
96397 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
96398 pC = p->apCsr[pOp->p1];
96400 assert( pC->deferredMoveto==0 );
96401 assert( pC->eCurType==CURTYPE_BTREE );
96402 assert( pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
96403 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
96404 || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
96405 || pC->seekOp==OP_IfNoHope);
96406 rc = sqlite3BtreeNext(pC->uc.pCursor, pOp->p3);
96409 pC->cacheStatus = CACHE_STALE;
96412 pC->nullRow = 0;
96413 p->aCounter[pOp->p5]++;
96421 pC->nullRow = 1;
96437 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
96457 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96458 pC = p->apCsr[pOp->p1];
96462 pIn2 = &aMem[pOp->p2];
96463 assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
96464 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
96465 assert( pC->eCurType==CURTYPE_BTREE );
96466 assert( pC->isTable==0 );
96469 x.nKey = pIn2->n;
96470 x.pKey = pIn2->z;
96471 x.aMem = aMem + pOp->p3;
96472 x.nMem = (u16)pOp->p4.i;
96473 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
96474 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
96475 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
96477 assert( pC->deferredMoveto==0 );
96478 pC->cacheStatus = CACHE_STALE;
96493 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96494 pC = p->apCsr[pOp->p1];
96498 pIn2 = &aMem[pOp->p2];
96499 assert( pIn2->flags & MEM_Blob );
96500 assert( pC->isTable==0 );
96521 ** this (self-correcting and non-critical) error if in writable_schema mode.
96529 assert( pOp->p3>0 );
96530 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
96531 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96532 pC = p->apCsr[pOp->p1];
96534 assert( pC->eCurType==CURTYPE_BTREE );
96536 pCrsr = pC->uc.pCursor;
96538 r.pKeyInfo = pC->pKeyInfo;
96539 r.nField = (u16)pOp->p3;
96541 r.aMem = &aMem[pOp->p2];
96547 }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
96551 assert( pC->deferredMoveto==0 );
96552 pC->cacheStatus = CACHE_STALE;
96553 pC->seekResult = 0;
96570 ** is non-zero, then reading column a(i)-1 from cursor P3 is
96591 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96592 pC = p->apCsr[pOp->p1];
96594 assert( pC->eCurType==CURTYPE_BTREE || IsNullCursor(pC) );
96595 assert( pC->uc.pCursor!=0 );
96596 assert( pC->isTable==0 || IsNullCursor(pC) );
96597 assert( pC->deferredMoveto==0 );
96598 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
96609 if( !pC->nullRow ){
96611 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
96615 if( pOp->opcode==OP_DeferredSeek ){
96616 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
96617 pTabCur = p->apCsr[pOp->p3];
96619 assert( pTabCur->eCurType==CURTYPE_BTREE );
96620 assert( pTabCur->uc.pCursor!=0 );
96621 assert( pTabCur->isTable );
96622 pTabCur->nullRow = 0;
96623 pTabCur->movetoTarget = rowid;
96624 pTabCur->deferredMoveto = 1;
96625 pTabCur->cacheStatus = CACHE_STALE;
96626 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
96627 assert( !pTabCur->isEphemeral );
96628 pTabCur->ub.aAltMap = pOp->p4.ai;
96629 assert( !pC->isEphemeral );
96630 pTabCur->pAltCursor = pC;
96633 pOut->u.i = rowid;
96636 assert( pOp->opcode==OP_IdxRowid );
96637 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
96646 ** already occurred, this instruction is a no-op.
96651 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96652 pC = p->apCsr[pOp->p1];
96653 if( pC->deferredMoveto ){
96712 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96713 pC = p->apCsr[pOp->p1];
96715 assert( pC->isOrdered );
96716 assert( pC->eCurType==CURTYPE_BTREE );
96717 assert( pC->uc.pCursor!=0);
96718 assert( pC->deferredMoveto==0 );
96719 assert( pOp->p4type==P4_INT32 );
96720 r.pKeyInfo = pC->pKeyInfo;
96721 r.nField = (u16)pOp->p4.i;
96722 if( pOp->opcode<OP_IdxLT ){
96723 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
96724 r.default_rc = -1;
96726 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
96729 r.aMem = &aMem[pOp->p3];
96735 REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
96746 assert( pC->eCurType==CURTYPE_BTREE );
96747 pCur = pC->uc.pCursor;
96765 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
96766 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
96767 res = -res;
96769 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
96790 ** value of the root page that moved - its value before the move occurred -
96801 ** and non-autovacuum modes.
96810 assert( p->readOnly==0 );
96811 assert( pOp->p1>1 );
96813 pOut->flags = MEM_Null;
96814 if( db->nVdbeRead > db->nVDestroy+1 ){
96816 p->errorAction = OE_Abort;
96819 iDb = pOp->p3;
96820 assert( DbMaskTest(p->btreeMask, iDb) );
96822 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
96823 pOut->flags = MEM_Int;
96824 pOut->u.i = iMoved;
96828 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
96848 ** If the P3 value is non-zero, then the row change count is incremented
96860 assert( p->readOnly==0 );
96861 assert( DbMaskTest(p->btreeMask, pOp->p2) );
96862 rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, (u32)pOp->p1, &nChange);
96863 if( pOp->p3 ){
96864 p->nChange += nChange;
96865 if( pOp->p3>0 ){
96866 assert( memIsValid(&aMem[pOp->p3]) );
96867 memAboutToChange(p, &aMem[pOp->p3]);
96868 aMem[pOp->p3].u.i += nChange;
96886 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
96887 pC = p->apCsr[pOp->p1];
96890 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
96892 assert( pC->eCurType==CURTYPE_BTREE );
96893 assert( pC->isEphemeral );
96894 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
96903 ** Allocate a new b-tree in the main database file if P1==0 or in the
96907 ** The root page number of the new b-tree is stored in register P2.
96916 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
96917 assert( pOp->p1>=0 && pOp->p1<db->nDb );
96918 assert( DbMaskTest(p->btreeMask, pOp->p1) );
96919 assert( p->readOnly==0 );
96920 pDb = &db->aDb[pOp->p1];
96921 assert( pDb->pBt!=0 );
96922 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
96924 pOut->u.i = pgno;
96934 db->nSqlExec++;
96935 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, 0);
96936 db->nSqlExec--;
96948 ** then runs the new virtual machine. It is thus a re-entrant opcode.
96961 for(iDb=0; iDb<db->nDb; iDb++){
96962 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
96966 iDb = pOp->p1;
96967 assert( iDb>=0 && iDb<db->nDb );
96969 || db->mallocFailed
96970 || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
96973 if( pOp->p4.z==0 ){
96974 sqlite3SchemaClear(db->aDb[iDb].pSchema);
96975 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
96976 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
96977 db->mDbFlags |= DBFLAG_SchemaChange;
96978 p->expired = 0;
96985 initData.pzErrMsg = &p->zErrMsg;
96987 initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
96990 db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
96994 assert( db->init.busy==0 );
96995 db->init.busy = 1;
96998 assert( !db->mallocFailed );
97002 /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
97008 db->init.busy = 0;
97029 assert( pOp->p1>=0 && pOp->p1<db->nDb );
97030 rc = sqlite3AnalysisLoad(db, pOp->p1);
97038 ** Remove the internal (in-memory) data structures that describe
97046 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
97052 ** Remove the internal (in-memory) data structures that describe
97060 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
97066 ** Remove the internal (in-memory) data structures that describe
97074 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
97106 assert( p->bIsReader );
97107 nRoot = pOp->p2;
97108 aRoot = pOp->p4.ai;
97111 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
97112 pnErr = &aMem[pOp->p3];
97113 assert( (pnErr->flags & MEM_Int)!=0 );
97114 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
97115 pIn1 = &aMem[pOp->p1];
97116 assert( pOp->p5<db->nDb );
97117 assert( DbMaskTest(p->btreeMask, pOp->p5) );
97118 z = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1], nRoot,
97119 (int)pnErr->u.i+1, &nErr);
97126 pnErr->u.i -= nErr-1;
97127 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
97144 pIn1 = &aMem[pOp->p1];
97145 pIn2 = &aMem[pOp->p2];
97146 assert( (pIn2->flags & MEM_Int)!=0 );
97147 if( (pIn1->flags & MEM_Blob)==0 ){
97151 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
97166 pIn1 = &aMem[pOp->p1];
97167 assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
97168 if( (pIn1->flags & MEM_Blob)==0
97169 || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
97178 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
97186 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
97195 ** must have P4==0, the final set must have P4==-1, and for all other sets
97200 ** (b) when P4==-1 there is no need to insert the value, as it will
97210 pIn1 = &aMem[pOp->p1];
97211 pIn3 = &aMem[pOp->p3];
97212 iSet = pOp->p4.i;
97213 assert( pIn3->flags&MEM_Int );
97218 if( (pIn1->flags & MEM_Blob)==0 ){
97222 assert( pOp->p4type==P4_INT32 );
97223 assert( iSet==-1 || iSet>=0 );
97225 exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
97230 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
97243 ** cell in an array of values used as arguments to the sub-program. P2
97244 ** contains the address to jump to if the sub-program throws an IGNORE
97247 ** memory required by the sub-vdbe at runtime.
97251 ** If P5 is non-zero, then recursive program invocation is enabled.
97254 int nMem; /* Number of memory registers for sub-program */
97255 int nByte; /* Bytes of runtime space required for sub-program */
97260 SubProgram *pProgram; /* Sub-program to execute */
97263 pProgram = pOp->p4.pProgram;
97264 pRt = &aMem[pOp->p3];
97265 assert( pProgram->nOp>0 );
97268 ** disabled for backwards compatibility (p5 is set if this sub-program
97278 if( pOp->p5 ){
97279 t = pProgram->token;
97280 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
97284 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
97294 if( (pRt->flags&MEM_Blob)==0 ){
97300 nMem = pProgram->nMem + pProgram->nCsr;
97302 if( pProgram->nCsr==0 ) nMem++;
97305 + pProgram->nCsr * sizeof(VdbeCursor*)
97306 + (pProgram->nOp + 7)/8;
97312 pRt->flags = MEM_Blob|MEM_Dyn;
97313 pRt->z = (char*)pFrame;
97314 pRt->n = nByte;
97315 pRt->xDel = sqlite3VdbeFrameMemDel;
97317 pFrame->v = p;
97318 pFrame->nChildMem = nMem;
97319 pFrame->nChildCsr = pProgram->nCsr;
97320 pFrame->pc = (int)(pOp - aOp);
97321 pFrame->aMem = p->aMem;
97322 pFrame->nMem = p->nMem;
97323 pFrame->apCsr = p->apCsr;
97324 pFrame->nCursor = p->nCursor;
97325 pFrame->aOp = p->aOp;
97326 pFrame->nOp = p->nOp;
97327 pFrame->token = pProgram->token;
97329 pFrame->anExec = p->anExec;
97332 pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
97335 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
97337 pMem->flags = MEM_Undefined;
97338 pMem->db = db;
97341 pFrame = (VdbeFrame*)pRt->z;
97342 assert( pRt->xDel==sqlite3VdbeFrameMemDel );
97343 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
97344 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
97345 assert( pProgram->nCsr==pFrame->nChildCsr );
97346 assert( (int)(pOp - aOp)==pFrame->pc );
97349 p->nFrame++;
97350 pFrame->pParent = p->pFrame;
97351 pFrame->lastRowid = db->lastRowid;
97352 pFrame->nChange = p->nChange;
97353 pFrame->nDbChange = p->db->nChange;
97354 assert( pFrame->pAuxData==0 );
97355 pFrame->pAuxData = p->pAuxData;
97356 p->pAuxData = 0;
97357 p->nChange = 0;
97358 p->pFrame = pFrame;
97359 p->aMem = aMem = VdbeFrameMem(pFrame);
97360 p->nMem = pFrame->nChildMem;
97361 p->nCursor = (u16)pFrame->nChildCsr;
97362 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
97363 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
97364 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
97365 p->aOp = aOp = pProgram->aOp;
97366 p->nOp = pProgram->nOp;
97368 p->anExec = 0;
97375 for(i=0; i<p->nMem; i++){
97376 aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
97381 pOp = &aOp[-1];
97387 ** This opcode is only ever present in sub-programs called via the
97401 pFrame = p->pFrame;
97402 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
97414 ** If P1 is non-zero, the database constraint counter is incremented
97419 if( db->flags & SQLITE_DeferFKs ){
97420 db->nDeferredImmCons += pOp->p2;
97421 }else if( pOp->p1 ){
97422 db->nDeferredCons += pOp->p2;
97424 p->nFkConstraint += pOp->p2;
97432 ** This opcode tests if a foreign key constraint-counter is currently zero.
97436 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
97438 ** zero, the jump is taken if the statement constraint-counter is zero
97442 if( pOp->p1 ){
97443 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
97444 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
97446 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
97447 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
97459 ** within a sub-program). Set the value of register P1 to the maximum of
97467 if( p->pFrame ){
97468 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
97469 pIn1 = &pFrame->aMem[pOp->p1];
97471 pIn1 = &aMem[pOp->p1];
97475 pIn2 = &aMem[pOp->p2];
97477 if( pIn1->u.i<pIn2->u.i){
97478 pIn1->u.i = pIn2->u.i;
97485 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
97495 pIn1 = &aMem[pOp->p1];
97496 assert( pIn1->flags&MEM_Int );
97497 VdbeBranchTaken( pIn1->u.i>0, 2);
97498 if( pIn1->u.i>0 ){
97499 pIn1->u.i -= pOp->p3;
97506 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
97519 ** and r[P2] is set to -1.
97525 pIn1 = &aMem[pOp->p1];
97526 pIn3 = &aMem[pOp->p3];
97528 assert( pIn1->flags & MEM_Int );
97529 assert( pIn3->flags & MEM_Int );
97530 x = pIn1->u.i;
97531 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
97539 pOut->u.i = -1;
97541 pOut->u.i = x;
97547 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
97551 ** If it is non-zero (negative or positive) and then also jump to P2.
97555 pIn1 = &aMem[pOp->p1];
97556 assert( pIn1->flags&MEM_Int );
97557 VdbeBranchTaken(pIn1->u.i<0, 2);
97558 if( pIn1->u.i ){
97559 if( pIn1->u.i>0 ) pIn1->u.i--;
97566 ** Synopsis: if (--r[P1])==0 goto P2
97573 if( pOp->p5&0x80 ){
97574 if( p->pSharedBlock!=NULL ){
97575 if( p->totalRows < p->startPos || p->blockFull ){
97576 pIn1 = &aMem[pOp->p1];
97577 assert( pIn1->flags&MEM_Int );
97578 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
97579 VdbeBranchTaken(pIn1->u.i==-1, 2);
97580 if( pIn1->u.i==-1 ) goto jump_to_p2;
97586 pIn1 = &aMem[pOp->p1];
97587 assert( pIn1->flags&MEM_Int );
97588 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
97589 VdbeBranchTaken(pIn1->u.i==0, 2);
97590 if( pIn1->u.i==0 ) goto jump_to_p2;
97639 assert( pOp->p4type==P4_FUNCDEF );
97640 n = pOp->p5;
97641 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
97642 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
97643 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
97645 (sizeof(pCtx[0]) + sizeof(Mem) - sizeof(sqlite3_value*)));
97647 pCtx->pMem = 0;
97648 pCtx->pOut = (Mem*)&(pCtx->argv[n]);
97649 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
97650 pCtx->pFunc = pOp->p4.pFunc;
97651 pCtx->iOp = (int)(pOp - aOp);
97652 pCtx->pVdbe = p;
97653 pCtx->skipFlag = 0;
97654 pCtx->isError = 0;
97655 pCtx->enc = encoding;
97656 pCtx->argc = n;
97657 pOp->p4type = P4_FUNCCTX;
97658 pOp->p4.pCtx = pCtx;
97661 assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
97663 pOp->opcode = OP_AggStep1;
97672 assert( pOp->p4type==P4_FUNCCTX );
97673 pCtx = pOp->p4.pCtx;
97674 pMem = &aMem[pOp->p3];
97677 if( pOp->p1 ){
97680 assert( pMem->uTemp==0x1122e0e3 );
97683 pMem->uTemp = 0x1122e0e3;
97691 if( pCtx->pMem != pMem ){
97692 pCtx->pMem = pMem;
97693 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
97697 for(i=0; i<pCtx->argc; i++){
97698 assert( memIsValid(pCtx->argv[i]) );
97699 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
97703 pMem->n++;
97704 assert( pCtx->pOut->flags==MEM_Null );
97705 assert( pCtx->isError==0 );
97706 assert( pCtx->skipFlag==0 );
97708 if( pOp->p1 ){
97709 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
97712 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
97714 if( pCtx->isError ){
97715 if( pCtx->isError>0 ){
97716 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
97717 rc = pCtx->isError;
97719 if( pCtx->skipFlag ){
97720 assert( pOp[-1].opcode==OP_CollSeq );
97721 i = pOp[-1].p1;
97723 pCtx->skipFlag = 0;
97725 sqlite3VdbeMemRelease(pCtx->pOut);
97726 pCtx->pOut->flags = MEM_Null;
97727 pCtx->isError = 0;
97730 assert( pCtx->pOut->flags==MEM_Null );
97731 assert( pCtx->skipFlag==0 );
97764 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
97765 assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
97766 pMem = &aMem[pOp->p1];
97767 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
97769 if( pOp->p3 ){
97770 memAboutToChange(p, &aMem[pOp->p3]);
97771 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
97772 pMem = &aMem[pOp->p3];
97776 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
97791 ** Checkpoint database P1. This is a no-op if P1 is not currently in
97798 ** mem[P3+2] are initialized to -1.
97805 assert( p->readOnly==0 );
97807 aRes[1] = aRes[2] = -1;
97808 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
97809 || pOp->p2==SQLITE_CHECKPOINT_FULL
97810 || pOp->p2==SQLITE_CHECKPOINT_RESTART
97811 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
97813 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
97819 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
97836 ** Write a string containing the final journal-mode to register P2.
97848 eNew = pOp->p3;
97857 assert( pOp->p1>=0 && pOp->p1<db->nDb );
97858 assert( p->readOnly==0 );
97860 pBt = db->aDb[pOp->p1].pBt;
97875 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
97883 if( !db->autoCommit || db->nVdbeRead>1 ){
97894 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
97922 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
97923 pOut->z = (char *)sqlite3JournalModename(eNew);
97924 pOut->n = sqlite3Strlen30(pOut->z);
97925 pOut->enc = SQLITE_UTF8;
97943 assert( p->readOnly==0 );
97944 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
97945 pOp->p2 ? &aMem[pOp->p2] : 0);
97961 assert( pOp->p1>=0 && pOp->p1<db->nDb );
97962 assert( DbMaskTest(p->btreeMask, pOp->p1) );
97963 assert( p->readOnly==0 );
97964 pBt = db->aDb[pOp->p1].pBt;
97983 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
97993 assert( pOp->p2==0 || pOp->p2==1 );
97994 if( !pOp->p1 ){
97995 sqlite3ExpirePreparedStatements(db, pOp->p2);
97997 p->expired = pOp->p2+1;
98009 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98010 pC = p->apCsr[pOp->p1];
98012 assert( pC->eCurType==CURTYPE_BTREE );
98013 sqlite3BtreeCursorPin(pC->uc.pCursor);
98024 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98025 pC = p->apCsr[pOp->p1];
98027 assert( pC->eCurType==CURTYPE_BTREE );
98028 sqlite3BtreeCursorUnpin(pC->uc.pCursor);
98037 ** the shared-cache feature is enabled.
98043 ** P2 contains the root-page of the table to lock.
98049 u8 isWriteLock = (u8)pOp->p3;
98050 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
98051 int p1 = pOp->p1;
98052 assert( p1>=0 && p1<db->nDb );
98053 assert( DbMaskTest(p->btreeMask, p1) );
98055 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
98058 const char *z = pOp->p4.z;
98080 pVTab = pOp->p4.pVtab;
98082 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
98102 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
98103 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
98104 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
98107 assert( zTab || db->mallocFailed );
98109 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
98124 db->nVDestroy++;
98125 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
98126 db->nVDestroy--;
98127 assert( p->errorAction==OE_Abort && p->usesStmtJournal );
98146 assert( p->bIsReader );
98149 pVtab = pOp->p4.pVtab->pVtab;
98150 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
98154 pModule = pVtab->pModule;
98155 rc = pModule->xOpen(pVtab, &pVCur);
98160 pVCur->pVtab = pVtab;
98163 pCur = allocateCursor(p, pOp->p1, 0, CURTYPE_VTAB);
98165 pCur->uc.pVCur = pVCur;
98166 pVtab->nRef++;
98168 assert( db->mallocFailed );
98169 pModule->xClose(pVCur);
98191 pC = p->apCsr[pOp->p1];
98194 pRhs->pCsr = pC->uc.pCursor;
98195 pRhs->pOut = &aMem[pOp->p3];
98197 pOut->flags = MEM_Null;
98237 pQuery = &aMem[pOp->p3];
98239 pCur = p->apCsr[pOp->p1];
98241 REGISTER_TRACE(pOp->p3, pQuery);
98243 assert( pCur->eCurType==CURTYPE_VTAB );
98244 pVCur = pCur->uc.pVCur;
98245 pVtab = pVCur->pVtab;
98246 pModule = pVtab->pModule;
98249 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
98250 nArg = (int)pArgc->u.i;
98251 iQuery = (int)pQuery->u.i;
98254 apArg = p->apArg;
98258 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
98261 res = pModule->xEof(pVCur);
98262 pCur->nullRow = 0;
98273 ** Store in register P3 the value of the P2-th column of
98274 ** the current row of the virtual-table of cursor P1.
98290 VdbeCursor *pCur = p->apCsr[pOp->p1];
98292 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
98293 pDest = &aMem[pOp->p3];
98295 if( pCur->nullRow ){
98299 assert( pCur->eCurType==CURTYPE_VTAB );
98300 pVtab = pCur->uc.pVCur->pVtab;
98301 pModule = pVtab->pModule;
98302 assert( pModule->xColumn );
98306 assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
98307 if( pOp->p5 & OPFLAG_NOCHNG ){
98309 pDest->flags = MEM_Null|MEM_Zero;
98310 pDest->u.nZero = 0;
98314 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
98321 REGISTER_TRACE(pOp->p3, pDest);
98342 pCur = p->apCsr[pOp->p1];
98344 assert( pCur->eCurType==CURTYPE_VTAB );
98345 if( pCur->nullRow ){
98348 pVtab = pCur->uc.pVCur->pVtab;
98349 pModule = pVtab->pModule;
98350 assert( pModule->xNext );
98358 rc = pModule->xNext(pCur->uc.pVCur);
98361 res = pModule->xEof(pCur->uc.pVCur);
98383 isLegacy = (db->flags & SQLITE_LegacyAlter);
98384 db->flags |= SQLITE_LegacyAlter;
98385 pVtab = pOp->p4.pVtab->pVtab;
98386 pName = &aMem[pOp->p1];
98387 assert( pVtab->pModule->xRename );
98389 assert( p->readOnly==0 );
98390 REGISTER_TRACE(pOp->p1, pName);
98391 assert( pName->flags & MEM_Str );
98392 testcase( pName->enc==SQLITE_UTF8 );
98393 testcase( pName->enc==SQLITE_UTF16BE );
98394 testcase( pName->enc==SQLITE_UTF16LE );
98397 rc = pVtab->pModule->xRename(pVtab, pName->z);
98398 if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
98400 p->expired = 0;
98413 ** invocation. The value in register (P3+P2-1) corresponds to the
98443 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
98444 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
98446 assert( p->readOnly==0 );
98447 if( db->mallocFailed ) goto no_mem;
98449 pVtab = pOp->p4.pVtab->pVtab;
98450 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
98454 pModule = pVtab->pModule;
98455 nArg = pOp->p2;
98456 assert( pOp->p4type==P4_VTAB );
98457 if( ALWAYS(pModule->xUpdate) ){
98458 u8 vtabOnConflict = db->vtabOnConflict;
98459 apArg = p->apArg;
98460 pX = &aMem[pOp->p3];
98467 db->vtabOnConflict = pOp->p5;
98468 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
98469 db->vtabOnConflict = vtabOnConflict;
98471 if( rc==SQLITE_OK && pOp->p1 ){
98472 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
98473 db->lastRowid = rowid;
98475 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
98476 if( pOp->p5==OE_Ignore ){
98479 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
98482 p->nChange++;
98497 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
98517 pBt = db->aDb[pOp->p1].pBt;
98519 if( pOp->p3 ){
98521 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
98523 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
98538 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
98557 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
98566 ** purely non-deterministic. Some built-in date/time functions can be
98567 ** either determinitic of non-deterministic, depending on their arguments.
98568 ** When those function are used in a non-deterministic way, they will check
98579 assert( pOp->p4type==P4_FUNCCTX );
98580 pCtx = pOp->p4.pCtx;
98586 pOut = &aMem[pOp->p3];
98587 if( pCtx->pOut != pOut ){
98588 pCtx->pVdbe = p;
98589 pCtx->pOut = pOut;
98590 pCtx->enc = encoding;
98591 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
98593 assert( pCtx->pVdbe==p );
98597 for(i=0; i<pCtx->argc; i++){
98598 assert( memIsValid(pCtx->argv[i]) );
98599 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
98603 assert( pCtx->isError==0 );
98604 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
98607 if( pCtx->isError ){
98608 if( pCtx->isError>0 ){
98610 rc = pCtx->isError;
98612 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
98613 pCtx->isError = 0;
98617 assert( (pOut->flags&MEM_Str)==0
98618 || pOut->enc==encoding
98619 || db->mallocFailed );
98622 REGISTER_TRACE(pOp->p3, pOut);
98633 pIn1 = &aMem[pOp->p1];
98634 pIn1->flags &= ~MEM_Subtype;
98647 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
98648 pIn1 = &aMem[pOp->p1];
98649 assert( pIn1->flags & MEM_Blob );
98650 assert( pIn1->n>0 );
98653 if( db->flags&SQLITE_VdbeTrace ){
98655 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
98658 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
98661 h %= pIn1->n;
98662 pIn1->z[h/8] |= 1<<(h&7);
98678 ** false positive - if the jump is taken when it should fall through.
98683 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
98684 pIn1 = &aMem[pOp->p1];
98685 assert( (pIn1->flags & MEM_Blob)!=0 );
98686 assert( pIn1->n >= 1 );
98689 if( db->flags&SQLITE_VdbeTrace ){
98691 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
98694 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
98697 h %= pIn1->n;
98698 if( (pIn1->z[h/8] & (1<<(h&7)))==0 ){
98700 p->aCounter[SQLITE_STMTSTATUS_FILTER_HIT]++;
98703 p->aCounter[SQLITE_STMTSTATUS_FILTER_MISS]++;
98723 ** the UTF-8 string contained in P4 is emitted on the trace callback.
98742 ** The "--" string is broken up to prevent false-positives with srcck1.c.
98745 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
98747 ** using the X argument when X begins with "--" and invoking
98750 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
98753 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
98756 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
98757 && p->minWriteFileFormat!=254 /* tag-20220401a */
98758 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
98761 if( db->mTrace & SQLITE_TRACE_LEGACY ){
98763 db->trace.xLegacy(db->pTraceArg, z);
98767 if( db->nVdbeExec>1 ){
98768 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
98769 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
98772 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
98776 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
98779 for(j=0; j<db->nDb; j++){
98780 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
98781 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
98786 if( (db->flags & SQLITE_SqlTrace)!=0
98787 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
98789 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
98793 assert( pOp->p2>0 );
98794 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
98795 if( pOp->opcode==OP_Trace ) break;
98796 for(i=1; i<p->nOp; i++){
98797 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
98799 pOp->p1 = 0;
98801 pOp->p1++;
98802 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
98812 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
98817 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98818 assert( pOp->p4type==P4_EXPR );
98819 pC = p->apCsr[pOp->p1];
98821 assert( pC->eCurType==CURTYPE_BTREE );
98822 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
98823 pOp->p4.pExpr, aMem);
98858 ** a change to the value of the source register for the OP_SCopy will no longer
98880 assert( pOp->p1>0 );
98881 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
98882 pMem = &aMem[pOp->p1];
98883 constMask = pOp->p3;
98884 for(i=0; i<pOp->p2; i++, pMem++){
98886 pMem->pScopyFrom = 0;
98887 if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
98903 ** the same as a no-op. This opcodesnever appears in a real VM program.
98906 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
98913 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
98922 if( endTime>start ) pOrigOp->cycles += endTime - start;
98923 pOrigOp->cnt++;
98933 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
98936 if( db->flags & SQLITE_VdbeTrace ){
98937 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
98940 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
98943 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
98960 if( db->mallocFailed ){
98967 if( db->flags & SQLITE_VdbeTrace ){
98968 const char *zTrace = p->zSql;
98975 printf("ABORT-due-to-error (rc=%d): %s\n", rc, zTrace);
98978 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
98981 p->rc = rc;
98985 (int)(pOp - aOp), p->zSql, p->zErrMsg);
98986 if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
98988 if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
98989 db->flags |= SQLITE_CorruptRdOnly;
98993 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
99001 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
99002 nProgressLimit += db->nProgressOps;
99003 if( db->xProgress(db->pProgressArg) ){
99010 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
99013 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
99037 assert( AtomicLoad(&db->u1.isInterrupted) );
99048 ** The author disclaims copyright to this source code. In place of
99083 ** the b-tree cursor associated with blob handle p to point to row iRow.
99094 ** If an error does occur, then the b-tree cursor is closed. All subsequent
99101 Vdbe *v = (Vdbe *)p->pStmt;
99106 v->aMem[1].flags = MEM_Int;
99107 v->aMem[1].u.i = iRow;
99113 if( v->pc>4 ){
99114 v->pc = 4;
99115 assert( v->aOp[v->pc].opcode==OP_NotExists );
99118 rc = sqlite3_step(p->pStmt);
99121 VdbeCursor *pC = v->apCsr[0];
99124 assert( pC->eCurType==CURTYPE_BTREE );
99125 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
99126 testcase( pC->nHdrParsed==p->iCol );
99127 testcase( pC->nHdrParsed==p->iCol+1 );
99129 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
99133 sqlite3_finalize(p->pStmt);
99134 p->pStmt = 0;
99136 p->iOffset = pC->aType[p->iCol + pC->nField];
99137 p->nByte = sqlite3VdbeSerialTypeLen(type);
99138 p->pCsr = pC->uc.pCursor;
99139 sqlite3BtreeIncrblobCursor(p->pCsr);
99145 }else if( p->pStmt ){
99146 rc = sqlite3_finalize(p->pStmt);
99147 p->pStmt = 0;
99149 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
99152 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
99172 int wrFlag, /* True -> read/write access, false -> read-only */
99176 int iCol; /* Index of zColumn in row-record */
99196 sqlite3_mutex_enter(db->mutex);
99231 pBlob->pTab = pTab;
99232 pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zDbSName;
99235 for(iCol=0; iCol<pTab->nCol; iCol++) {
99236 if( sqlite3StrICmp(pTab->aCol[iCol].zCnName, zColumn)==0 ){
99240 if( iCol==pTab->nCol ){
99255 if( db->flags&SQLITE_ForeignKeys ){
99262 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
99264 for(j=0; j<pFKey->nCol; j++){
99265 if( pFKey->aCol[j].iFrom==iCol ){
99272 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99274 for(j=0; j<pIdx->nKeyCol; j++){
99276 if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
99290 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
99291 assert( pBlob->pStmt || db->mallocFailed );
99292 if( pBlob->pStmt ){
99296 ** of writing code to use the b-tree layer directly is that the
99301 ** Code external to the Vdbe then "borrows" the b-tree cursor and
99306 ** which closes the b-tree cursor and (possibly) commits the
99319 Vdbe *v = (Vdbe *)pBlob->pStmt;
99320 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99324 pTab->pSchema->schema_cookie,
99325 pTab->pSchema->iGeneration);
99327 assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
99333 if( db->mallocFailed==0 ){
99340 aOp[0].p2 = pTab->tnum;
99342 sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
99344 if( db->mallocFailed==0 ){
99348 ** parameter of the other to pTab->tnum. */
99350 aOp[1].p2 = pTab->tnum;
99361 aOp[1].p4.i = pTab->nCol+1;
99362 aOp[3].p2 = pTab->nCol;
99371 pBlob->iCol = iCol;
99372 pBlob->db = db;
99374 if( db->mallocFailed ){
99383 if( rc==SQLITE_OK && db->mallocFailed==0 ){
99386 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
99393 sqlite3_mutex_leave(db->mutex);
99407 sqlite3_stmt *pStmt = p->pStmt;
99408 db = p->db;
99409 sqlite3_mutex_enter(db->mutex);
99411 sqlite3_mutex_leave(db->mutex);
99435 db = p->db;
99436 sqlite3_mutex_enter(db->mutex);
99437 v = (Vdbe*)p->pStmt;
99439 if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
99443 /* If there is no statement handle, then the blob-handle has
99449 ** returned, clean-up the statement handle.
99451 assert( db == v->db );
99452 sqlite3BtreeEnterCursor(p->pCsr);
99455 if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
99456 /* If a pre-update hook is registered and this is a write cursor,
99459 ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
99466 ** using the incremental-blob API, this works. For the sessions module
99470 iKey = sqlite3BtreeIntegerKey(p->pCsr);
99471 assert( v->apCsr[0]!=0 );
99472 assert( v->apCsr[0]->eCurType==CURTYPE_BTREE );
99474 v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1, p->iCol
99479 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
99480 sqlite3BtreeLeaveCursor(p->pCsr);
99483 p->pStmt = 0;
99485 v->rc = rc;
99490 sqlite3_mutex_leave(db->mutex);
99516 return (p && p->pStmt) ? p->nByte : 0;
99535 db = p->db;
99536 sqlite3_mutex_enter(db->mutex);
99538 if( p->pStmt==0 ){
99539 /* If there is no statement handle, then the blob-handle has
99545 ((Vdbe*)p->pStmt)->rc = SQLITE_OK;
99555 assert( rc==SQLITE_OK || p->pStmt==0 );
99556 sqlite3_mutex_leave(db->mutex);
99565 ** 2011-07-09
99567 ** The author disclaims copyright to this source code. In place of
99580 ** The VdbeSorter object implements a multi-threaded external merge sort
99584 ** Here is the (internal, non-API) interface between this module and the
99637 ** an in-memory merge sort. In this case, no temporary files are required
99644 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
99645 ** of PMAs may be created by merging existing PMAs together - for example
99646 ** merging two or more level-0 PMAs together creates a level-1 PMA.
99650 ** page-cache of the main database. Specifically, the threshold is set to
99654 ** If the sorter is running in single-threaded mode, then all PMAs generated
99656 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
99663 ** The sorter is running in multi-threaded mode if (a) the library was built
99664 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
99673 ** sorter is running in single-threaded mode, then these PMAs are merged
99678 ** Or, if running in multi-threaded mode, then a background thread is
99688 ** Rewind() is called, then a hierarchy of incremental-merges is used.
99694 ** If running in multi-threaded mode and there are more than
99707 ** characteristics of the sorter in multi-threaded mode.
99714 ** Hard-coded maximum amount of data to accumulate in memory before flushing
99727 typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
99729 typedef struct SorterList SorterList; /* In-memory list of records */
99742 ** An in-memory list of objects to be sorted.
99751 u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
99774 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
99788 ** aReadr[0] -> Banana
99789 ** aReadr[1] -> Feijoa
99790 ** aReadr[2] -> Elderberry
99791 ** aReadr[3] -> Currant
99792 ** aReadr[4] -> Grapefruit
99793 ** aReadr[5] -> Apple
99794 ** aReadr[6] -> Durian
99795 ** aReadr[7] -> EOF
99804 ** aReadr[5] -> Eggplant
99809 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
99832 ** single-threaded operation, there is exactly one instance of this object
99833 ** and for multi-threaded operation there are two or more instances.
99844 ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
99861 VdbeSorter *pSorter; /* Sorter that owns this sub-task */
99866 SorterFile file; /* Temp file for level-0 PMAs */
99890 SorterList list; /* List of in-memory records */
99933 ** There are two types of IncrMerger object - single (bUseThread==0) and
99934 ** multi-threaded (bUseThread==1).
99936 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
99951 ** A single-threaded IncrMerger does not open any temporary files of its
99953 ** at offset iStartOff of file pTask->file2. And instead of using a
99955 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
99973 ** size. But I/O is more efficient if it occurs in page-sized blocks where
99975 ** the PMA so that aligned, page-size blocks are written.
99978 int eFWErr; /* Non-zero if in an error state */
99992 ** by this module. If using a separate allocation for each in-memory record
100000 ** has finished passing records to the sorter, or when the in-memory buffer
100033 sqlite3_free(pReadr->aAlloc);
100034 sqlite3_free(pReadr->aBuffer);
100035 if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
100036 vdbeIncrFree(pReadr->pIncr);
100057 if( p->aMap ){
100058 *ppOut = &p->aMap[p->iReadOff];
100059 p->iReadOff += nByte;
100063 assert( p->aBuffer );
100066 ** p->nBuffer bytes of data from the file into it. Or, if there are less
100067 ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
100068 iBuf = p->iReadOff % p->nBuffer;
100074 if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
100075 nRead = p->nBuffer;
100077 nRead = (int)(p->iEof - p->iReadOff);
100082 rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
100086 nAvail = p->nBuffer - iBuf;
100089 /* The requested data is available in the in-memory buffer. In this
100092 *ppOut = &p->aBuffer[iBuf];
100093 p->iReadOff += nByte;
100095 /* The requested data is not all available in the in-memory buffer.
100096 ** In this case, allocate space at p->aAlloc[] to copy the requested
100097 ** range into. Then return a copy of pointer p->aAlloc to the caller. */
100100 /* Extend the p->aAlloc[] allocation if required. */
100101 if( p->nAlloc<nByte ){
100103 sqlite3_int64 nNew = MAX(128, 2*(sqlite3_int64)p->nAlloc);
100105 aNew = sqlite3Realloc(p->aAlloc, nNew);
100107 p->nAlloc = nNew;
100108 p->aAlloc = aNew;
100112 ** p->aAlloc[]. */
100113 memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
100114 p->iReadOff += nAvail;
100115 nRem = nByte - nAvail;
100117 /* The following loop copies up to p->nBuffer bytes per iteration into
100118 ** the p->aAlloc[] buffer. */
100125 if( nRem>p->nBuffer ) nCopy = p->nBuffer;
100128 assert( aNext!=p->aAlloc );
100129 memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
100130 nRem -= nCopy;
100133 *ppOut = p->aAlloc;
100146 if( p->aMap ){
100147 p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
100149 iBuf = p->iReadOff % p->nBuffer;
100150 if( iBuf && (p->nBuffer-iBuf)>=9 ){
100151 p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
100178 if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
100179 sqlite3_file *pFd = pFile->pFd;
100180 if( pFd->pMethods->iVersion>=3 ){
100181 rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
100201 assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
100204 if( pReadr->aMap ){
100205 sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
100206 pReadr->aMap = 0;
100208 pReadr->iReadOff = iOff;
100209 pReadr->iEof = pFile->iEof;
100210 pReadr->pFd = pFile->pFd;
100212 rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
100213 if( rc==SQLITE_OK && pReadr->aMap==0 ){
100214 int pgsz = pTask->pSorter->pgsz;
100215 int iBuf = pReadr->iReadOff % pgsz;
100216 if( pReadr->aBuffer==0 ){
100217 pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
100218 if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
100219 pReadr->nBuffer = pgsz;
100222 int nRead = pgsz - iBuf;
100223 if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
100224 nRead = (int)(pReadr->iEof - pReadr->iReadOff);
100227 pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
100245 if( pReadr->iReadOff>=pReadr->iEof ){
100246 IncrMerger *pIncr = pReadr->pIncr;
100250 if( rc==SQLITE_OK && pIncr->bEof==0 ){
100252 pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
100270 pReadr->nKey = (int)nRec;
100271 rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
100280 ** starting at offset iStart and ending at offset iEof-1. This function
100296 assert( pFile->iEof>iStart );
100297 assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
100298 assert( pReadr->aBuffer==0 );
100299 assert( pReadr->aMap==0 );
100305 pReadr->iEof = pReadr->iReadOff + nByte;
100322 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
100326 UnpackedRecord *r2 = pTask->pUnpacked;
100328 sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
100336 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
100340 ** it is assumed that (pTask->pUnpacked) contains the unpacked version
100341 ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
100344 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
100349 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
100353 UnpackedRecord *r2 = pTask->pUnpacked;
100355 sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
100368 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
100383 res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
100385 res = n1 - n2;
100389 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
100395 assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
100396 if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
100397 res = res * -1;
100410 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
100432 if( (res = v1[i] - v2[i])!=0 ){
100434 res = v1[0] & 0x80 ? -1 : +1;
100440 res = s1 - s2;
100445 res = -1;
100447 res = s1 - s2;
100452 if( *v1 & 0x80 ) res = -1;
100459 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
100464 }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
100465 assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
100466 res = res * -1;
100475 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
100478 ** is non-zero and the sorter is able to guarantee a stable sort, nField
100486 ** The sorter can guarantee a stable sort when running in single-threaded
100487 ** mode, but not in multi-threaded mode.
100499 KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
100500 int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
100514 nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
100522 nWorker = SORTER_MAX_MERGE_COUNT-1;
100526 assert( pCsr->pKeyInfo );
100527 assert( !pCsr->isEphemeral );
100528 assert( pCsr->eCurType==CURTYPE_SORTER );
100529 szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nKeyField-1)*sizeof(CollSeq*);
100533 pCsr->uc.pSorter = pSorter;
100537 Btree *pBt = db->aDb[0].pBt;
100538 pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
100539 memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
100540 pKeyInfo->db = 0;
100542 pKeyInfo->nKeyField = nField;
100545 pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(pBt);
100547 pSorter->nTask = nWorker + 1;
100548 pSorter->iPrev = (u8)(nWorker - 1);
100549 pSorter->bUseThreads = (pSorter->nTask>1);
100550 pSorter->db = db;
100551 for(i=0; i<pSorter->nTask; i++){
100552 SortSubtask *pTask = &pSorter->aTask[i];
100553 pTask->pSorter = pSorter;
100559 pSorter->mnPmaSize = szPma * pgsz;
100561 mxCache = db->aDb[0].pSchema->cache_size;
100563 /* A negative cache-size value C indicates that the cache is abs(C)
100565 mxCache = mxCache * -1024;
100570 pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
100575 assert( pSorter->iMemory==0 );
100576 pSorter->nMemory = pgsz;
100577 pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
100578 if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
100582 if( pKeyInfo->nAllField<13
100583 && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
100584 && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0
100586 pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
100601 pNext = p->u.pNext;
100611 sqlite3DbFree(db, pTask->pUnpacked);
100613 /* pTask->list.aMemory can only be non-zero if it was handed memory
100615 if( pTask->list.aMemory ){
100616 sqlite3_free(pTask->list.aMemory);
100620 assert( pTask->list.aMemory==0 );
100621 vdbeSorterRecordFree(0, pTask->list.pList);
100623 if( pTask->file.pFd ){
100624 sqlite3OsCloseFree(pTask->file.pFd);
100626 if( pTask->file2.pFd ){
100627 sqlite3OsCloseFree(pTask->file2.pFd);
100635 int iTask = (pTask - pTask->pSorter->aTask);
100636 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
100650 int iTask = (pTask - pTask->pSorter->aTask);
100651 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
100661 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
100674 ** Join thread pTask->thread.
100678 if( pTask->pThread ){
100680 int bDone = pTask->bDone;
100684 (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
100687 assert( pTask->bDone==1 );
100688 pTask->bDone = 0;
100689 pTask->pThread = 0;
100702 assert( pTask->pThread==0 && pTask->bDone==0 );
100703 return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
100708 ** level-0 PMAs.
100717 ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
100720 ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
100721 for(i=pSorter->nTask-1; i>=0; i--){
100722 SortSubtask *pTask = &pSorter->aTask[i];
100752 pNew->nTree = N;
100753 pNew->pTask = 0;
100754 pNew->aReadr = (PmaReader*)&pNew[1];
100755 pNew->aTree = (int*)&pNew->aReadr[N];
100766 for(i=0; i<pMerger->nTree; i++){
100767 vdbePmaReaderClear(&pMerger->aReadr[i]);
100780 if( pIncr->bUseThread ){
100781 vdbeSorterJoinThread(pIncr->pTask);
100782 if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
100783 if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
100786 vdbeMergeEngineFree(pIncr->pMerger);
100797 assert( pSorter->bUseThreads || pSorter->pReader==0 );
100799 if( pSorter->pReader ){
100800 vdbePmaReaderClear(pSorter->pReader);
100801 sqlite3DbFree(db, pSorter->pReader);
100802 pSorter->pReader = 0;
100805 vdbeMergeEngineFree(pSorter->pMerger);
100806 pSorter->pMerger = 0;
100807 for(i=0; i<pSorter->nTask; i++){
100808 SortSubtask *pTask = &pSorter->aTask[i];
100810 pTask->pSorter = pSorter;
100812 if( pSorter->list.aMemory==0 ){
100813 vdbeSorterRecordFree(0, pSorter->list.pList);
100815 pSorter->list.pList = 0;
100816 pSorter->list.szPMA = 0;
100817 pSorter->bUsePMA = 0;
100818 pSorter->iMemory = 0;
100819 pSorter->mxKeysize = 0;
100820 sqlite3DbFree(db, pSorter->pUnpacked);
100821 pSorter->pUnpacked = 0;
100829 assert( pCsr->eCurType==CURTYPE_SORTER );
100830 pSorter = pCsr->uc.pSorter;
100833 sqlite3_free(pSorter->list.aMemory);
100835 pCsr->uc.pSorter = 0;
100841 ** The first argument is a file-handle open on a temporary file. The file
100850 if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
100864 ** Allocate space for a file-handle and open a temporary file. If successful,
100865 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
100875 rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
100892 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
100896 if( pTask->pUnpacked==0 ){
100897 pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
100898 if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
100899 pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
100900 pTask->pUnpacked->errCode = 0;
100921 res = pTask->xCompare(
100922 pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
100927 pp = &p1->u.pNext;
100928 p1 = p1->u.pNext;
100935 pp = &p2->u.pNext;
100936 p2 = p2->u.pNext;
100952 if( p->typeMask==SORTER_TYPE_INTEGER ){
100954 }else if( p->typeMask==SORTER_TYPE_TEXT ){
100961 ** Sort the linked list of records headed at pTask->pList. Return
100974 p = pList->pList;
100975 pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
100980 if( pList->aMemory ){
100981 if( (u8*)p==pList->aMemory ){
100984 assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
100985 pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
100988 pNext = p->u.pNext;
100991 p->u.pNext = 0;
101005 pList->pList = p;
101007 assert( pTask->pUnpacked->errCode==SQLITE_OK
101008 || pTask->pUnpacked->errCode==SQLITE_NOMEM
101010 return pTask->pUnpacked->errCode;
101014 ** Initialize a PMA-writer object.
101023 p->aBuffer = (u8*)sqlite3Malloc(nBuf);
101024 if( !p->aBuffer ){
101025 p->eFWErr = SQLITE_NOMEM_BKPT;
101027 p->iBufEnd = p->iBufStart = (iStart % nBuf);
101028 p->iWriteOff = iStart - p->iBufStart;
101029 p->nBuffer = nBuf;
101030 p->pFd = pFd;
101040 while( nRem>0 && p->eFWErr==0 ){
101042 if( nCopy>(p->nBuffer - p->iBufEnd) ){
101043 nCopy = p->nBuffer - p->iBufEnd;
101046 memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
101047 p->iBufEnd += nCopy;
101048 if( p->iBufEnd==p->nBuffer ){
101049 p->eFWErr = sqlite3OsWrite(p->pFd,
101050 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
101051 p->iWriteOff + p->iBufStart
101053 p->iBufStart = p->iBufEnd = 0;
101054 p->iWriteOff += p->nBuffer;
101056 assert( p->iBufEnd<p->nBuffer );
101058 nRem -= nCopy;
101063 ** Flush any buffered data to disk and clean up the PMA-writer object.
101064 ** The results of using the PMA-writer after this call are undefined.
101073 if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
101074 p->eFWErr = sqlite3OsWrite(p->pFd,
101075 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
101076 p->iWriteOff + p->iBufStart
101079 *piEof = (p->iWriteOff + p->iBufEnd);
101080 sqlite3_free(p->aBuffer);
101081 rc = p->eFWErr;
101098 ** Write the current contents of in-memory linked-list pList to a level-0
101099 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
101107 ** * One or more records packed end-to-end in order of ascending keys.
101112 sqlite3 *db = pTask->pSorter->db;
101117 /* Set iSz to the expected size of file pTask->file after writing the PMA.
101119 i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
101124 assert( pList->szPMA>0 );
101127 if( pTask->file.pFd==0 ){
101128 rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
101129 assert( rc!=SQLITE_OK || pTask->file.pFd );
101130 assert( pTask->file.iEof==0 );
101131 assert( pTask->nPMA==0 );
101136 vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
101148 vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
101149 pTask->file.iEof);
101150 pTask->nPMA++;
101151 vdbePmaWriteVarint(&writer, pList->szPMA);
101152 for(p=pList->pList; p; p=pNext){
101153 pNext = p->u.pNext;
101154 vdbePmaWriteVarint(&writer, p->nVal);
101155 vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
101156 if( pList->aMemory==0 ) sqlite3_free(p);
101158 pList->pList = p;
101159 rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
101163 assert( rc!=SQLITE_OK || pList->pList==0 );
101164 assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
101180 int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
101181 SortSubtask *pTask = pMerger->pTask;
101184 rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
101195 pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
101196 pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
101198 for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
101201 if( pReadr1->pFd==0 ){
101203 }else if( pReadr2->pFd==0 ){
101204 iRes = -1;
101206 iRes = pTask->xCompare(pTask, &bCached,
101207 pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
101213 ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
101218 ** was actually called above, then pTask->pUnpacked now contains
101227 pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
101228 pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
101231 if( pReadr1->pFd ) bCached = 0;
101232 pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
101233 pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
101236 *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
101239 return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
101244 ** The main routine for background threads that write level-0 PMAs.
101249 assert( pTask->bDone==0 );
101250 rc = vdbeSorterListToPMA(pTask, &pTask->list);
101251 pTask->bDone = 1;
101262 pSorter->bUsePMA = 1;
101263 return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
101268 int nWorker = (pSorter->nTask-1);
101272 pSorter->bUsePMA = 1;
101274 /* Select a sub-task to sort and flush the current list of in-memory
101275 ** records to disk. If the sorter is running in multi-threaded mode,
101276 ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
101277 ** the background thread from a sub-tasks previous turn is still running,
101278 ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
101279 ** fall back to using the final sub-task. The first (pSorter->nTask-1)
101280 ** sub-tasks are prefered as they use background threads - the final
101281 ** sub-task uses the main thread. */
101283 int iTest = (pSorter->iPrev + i + 1) % nWorker;
101284 pTask = &pSorter->aTask[iTest];
101285 if( pTask->bDone ){
101288 if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
101294 rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
101301 assert( pTask->pThread==0 && pTask->bDone==0 );
101302 assert( pTask->list.pList==0 );
101303 assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
101305 aMem = pTask->list.aMemory;
101307 pSorter->iPrev = (u8)(pTask - pSorter->aTask);
101308 pTask->list = pSorter->list;
101309 pSorter->list.pList = 0;
101310 pSorter->list.szPMA = 0;
101312 pSorter->list.aMemory = aMem;
101313 pSorter->nMemory = sqlite3MallocSize(aMem);
101314 }else if( pSorter->list.aMemory ){
101315 pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
101316 if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
101342 assert( pCsr->eCurType==CURTYPE_SORTER );
101343 pSorter = pCsr->uc.pSorter;
101344 getVarint32NR((const u8*)&pVal->z[1], t);
101346 pSorter->typeMask &= SORTER_TYPE_INTEGER;
101348 pSorter->typeMask &= SORTER_TYPE_TEXT;
101350 pSorter->typeMask = 0;
101358 ** If using the single large allocation mode (pSorter->aMemory!=0), then
101365 ** * The total memory allocated for the in-memory list is greater
101366 ** than (page-size * cache-size), or
101368 ** * The total memory allocated for the in-memory list is greater
101369 ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
101371 nReq = pVal->n + sizeof(SorterRecord);
101372 nPMA = pVal->n + sqlite3VarintLen(pVal->n);
101373 if( pSorter->mxPmaSize ){
101374 if( pSorter->list.aMemory ){
101375 bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
101378 (pSorter->list.szPMA > pSorter->mxPmaSize)
101379 || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
101384 pSorter->list.szPMA = 0;
101385 pSorter->iMemory = 0;
101386 assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
101390 pSorter->list.szPMA += nPMA;
101391 if( nPMA>pSorter->mxKeysize ){
101392 pSorter->mxKeysize = nPMA;
101395 if( pSorter->list.aMemory ){
101396 int nMin = pSorter->iMemory + nReq;
101398 if( nMin>pSorter->nMemory ){
101400 sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory;
101401 int iListOff = -1;
101402 if( pSorter->list.pList ){
101403 iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
101406 if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
101408 aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
101411 pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
101413 pSorter->list.aMemory = aNew;
101414 pSorter->nMemory = nNew;
101417 pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
101418 pSorter->iMemory += ROUND8(nReq);
101419 if( pSorter->list.pList ){
101420 pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
101427 pNew->u.pNext = pSorter->list.pList;
101430 memcpy(SRVAL(pNew), pVal->z, pVal->n);
101431 pNew->nVal = pVal->n;
101432 pSorter->list.pList = pNew;
101438 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
101440 ** except that the number-of-bytes varint is omitted from the start.
101445 i64 iStart = pIncr->iStartOff;
101446 SorterFile *pOut = &pIncr->aFile[1];
101447 SortSubtask *pTask = pIncr->pTask;
101448 MergeEngine *pMerger = pIncr->pMerger;
101450 assert( pIncr->bEof==0 );
101454 vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
101457 PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
101458 int nKey = pReader->nKey;
101463 if( pReader->pFd==0 ) break;
101464 if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
101468 vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
101469 assert( pIncr->pMerger->pTask==pTask );
101470 rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
101473 rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
101482 ** multi-threaded IncrMerger objects.
101487 pIncr->pTask->bDone = 1;
101496 assert( pIncr->bUseThread );
101497 return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
101507 ** For single-threaded objects, this is accomplished by literally reading
101508 ** keys from pIncr->pMerger and repopulating aFile[0].
101510 ** For multi-threaded objects, all that is required is to wait until the
101522 if( pIncr->bUseThread ){
101523 rc = vdbeSorterJoinThread(pIncr->pTask);
101526 SorterFile f0 = pIncr->aFile[0];
101527 pIncr->aFile[0] = pIncr->aFile[1];
101528 pIncr->aFile[1] = f0;
101532 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
101533 pIncr->bEof = 1;
101542 pIncr->aFile[0] = pIncr->aFile[1];
101543 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
101544 pIncr->bEof = 1;
101566 pIncr->pMerger = pMerger;
101567 pIncr->pTask = pTask;
101568 pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
101569 pTask->file2.iEof += pIncr->mxSz;
101580 ** Set the "use-threads" flag on object pIncr.
101583 pIncr->bUseThread = 1;
101584 pIncr->pTask->file2.iEof -= pIncr->mxSz;
101591 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
101597 int iOut /* Store the result in pMerger->aTree[iOut] */
101605 assert( iOut<pMerger->nTree && iOut>0 );
101607 if( iOut>=(pMerger->nTree/2) ){
101608 i1 = (iOut - pMerger->nTree/2) * 2;
101611 i1 = pMerger->aTree[iOut*2];
101612 i2 = pMerger->aTree[iOut*2+1];
101615 p1 = &pMerger->aReadr[i1];
101616 p2 = &pMerger->aReadr[i2];
101618 if( p1->pFd==0 ){
101620 }else if( p2->pFd==0 ){
101623 SortSubtask *pTask = pMerger->pTask;
101626 assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
101627 res = pTask->xCompare(
101628 pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
101637 pMerger->aTree[iOut] = iRes;
101644 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
101690 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
101694 assert( pMerger->pTask==0 );
101695 pMerger->pTask = pTask;
101697 nTree = pMerger->nTree;
101702 ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
101705 ** on this PmaReader before any of the multi-threaded PmaReaders takes
101706 ** better advantage of multi-processor hardware. */
101707 rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
101709 rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
101714 for(i=pMerger->nTree-1; i>0; i--){
101717 return pTask->pUnpacked->errCode;
101722 ** incremental-reader (pReadr->pIncr!=0). This function serves to open
101724 ** object at (pReadr->pIncr).
101727 ** in the sub-tree headed by pReadr are also initialized. Data is then
101732 ** to be a multi-threaded PmaReader and this function is being called in a
101733 ** background thread. In this case all PmaReaders in the sub-tree are
101741 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
101742 ** this entire function is being run by thread (pTask->thread), that will
101746 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
101747 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
101755 IncrMerger *pIncr = pReadr->pIncr;
101756 SortSubtask *pTask = pIncr->pTask;
101757 sqlite3 *db = pTask->pSorter->db;
101759 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
101762 rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
101764 /* Set up the required files for pIncr. A multi-theaded IncrMerge object
101765 ** requires two temp files to itself, whereas a single-threaded object
101766 ** only requires a region of pTask->file2. */
101768 int mxSz = pIncr->mxSz;
101770 if( pIncr->bUseThread ){
101771 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
101773 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
101777 /*if( !pIncr->bUseThread )*/{
101778 if( pTask->file2.pFd==0 ){
101779 assert( pTask->file2.iEof>0 );
101780 rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
101781 pTask->file2.iEof = 0;
101784 pIncr->aFile[1].pFd = pTask->file2.pFd;
101785 pIncr->iStartOff = pTask->file2.iEof;
101786 pTask->file2.iEof += mxSz;
101792 if( rc==SQLITE_OK && pIncr->bUseThread ){
101794 ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
101796 ** pIncr->pTask->thread.
101825 pReader->pIncr->pTask->bDone = 1;
101831 ** If the PmaReader passed as the first argument is not an incremental-reader
101832 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
101836 ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
101842 IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
101846 assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
101847 if( pIncr->bUseThread ){
101849 rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
101860 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
101861 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
101866 ** first PMA to read from pTask->file. Assuming no error occurs, it is
101874 i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
101875 MergeEngine **ppOut /* OUT: New merge-engine */
101887 PmaReader *pReadr = &pNew->aReadr[i];
101888 rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
101889 iOff = pReadr->iEof;
101906 ** nPMA<=16 -> TreeDepth() == 0
101907 ** nPMA<=256 -> TreeDepth() == 1
101908 ** nPMA<=65536 -> TreeDepth() == 2
101921 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
101949 PmaReader *pReadr = &p->aReadr[iIter];
101951 if( pReadr->pIncr==0 ){
101956 rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
101960 p = pReadr->pIncr->pMerger;
101966 p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
101975 ** that has already written two or more level-0 PMAs to one or more temp
101993 /* If the sorter uses more than one task, then create the top-level
101995 ** one PmaReader per sub-task. */
101996 assert( pSorter->bUseThreads || pSorter->nTask==1 );
101997 if( pSorter->nTask>1 ){
101998 pMain = vdbeMergeEngineNew(pSorter->nTask);
102003 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
102004 SortSubtask *pTask = &pSorter->aTask[iTask];
102005 assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
102006 if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
102008 int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
102011 if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
102012 rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
102018 for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
102019 MergeEngine *pMerger = 0; /* New level-0 PMA merger */
102020 int nReader; /* Number of level-0 PMAs to merge */
102022 nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
102033 rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
102058 ** (for multi-threaded sorters) so that it can be used to iterate through
102065 SortSubtask *pTask0 = &pSorter->aTask[0];
102068 sqlite3 *db = pTask0->pSorter->db;
102071 for(i=0; i<pSorter->nTask; i++){
102072 pSorter->aTask[i].xCompare = xCompare;
102079 assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
102080 if( pSorter->bUseThreads ){
102083 SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
102087 pSorter->pReader = pReadr;
102091 rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
102093 vdbeIncrMergerSetThreads(pReadr->pIncr);
102094 for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
102096 if( (pIncr = pMain->aReadr[iTask].pIncr) ){
102098 assert( pIncr->pTask!=pLast );
102101 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
102106 ** b) If it is using task (nTask-1), it is configured to run
102107 ** in single-threaded mode. This is important, as the
102111 PmaReader *p = &pMain->aReadr[iTask];
102112 assert( p->pIncr==0 || (
102113 (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
102114 && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
102128 pSorter->pMerger = pMain;
102149 assert( pCsr->eCurType==CURTYPE_SORTER );
102150 pSorter = pCsr->uc.pSorter;
102155 ** from the in-memory list. */
102156 if( pSorter->bUsePMA==0 ){
102157 if( pSorter->list.pList ){
102159 rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
102166 /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
102170 assert( pSorter->list.pList );
102180 assert( pSorter->pReader==0 );
102201 assert( pCsr->eCurType==CURTYPE_SORTER );
102202 pSorter = pCsr->uc.pSorter;
102203 assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
102204 if( pSorter->bUsePMA ){
102205 assert( pSorter->pReader==0 || pSorter->pMerger==0 );
102206 assert( pSorter->bUseThreads==0 || pSorter->pReader );
102207 assert( pSorter->bUseThreads==1 || pSorter->pMerger );
102209 if( pSorter->bUseThreads ){
102210 rc = vdbePmaReaderNext(pSorter->pReader);
102211 if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
102214 /*if( !pSorter->bUseThreads )*/ {
102216 assert( pSorter->pMerger!=0 );
102217 assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
102218 rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
102222 SorterRecord *pFree = pSorter->list.pList;
102223 pSorter->list.pList = pFree->u.pNext;
102224 pFree->u.pNext = 0;
102225 if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
102226 rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
102240 if( pSorter->bUsePMA ){
102243 if( pSorter->bUseThreads ){
102244 pReader = pSorter->pReader;
102247 /*if( !pSorter->bUseThreads )*/{
102248 pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
102250 *pnKey = pReader->nKey;
102251 pKey = pReader->aKey;
102253 *pnKey = pSorter->list.pList->nVal;
102254 pKey = SRVAL(pSorter->list.pList);
102266 assert( pCsr->eCurType==CURTYPE_SORTER );
102267 pSorter = pCsr->uc.pSorter;
102272 pOut->n = nKey;
102274 memcpy(pOut->z, pKey, nKey);
102307 assert( pCsr->eCurType==CURTYPE_SORTER );
102308 pSorter = pCsr->uc.pSorter;
102309 r2 = pSorter->pUnpacked;
102310 pKeyInfo = pCsr->pKeyInfo;
102312 r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
102314 r2->nField = nKeyCol;
102316 assert( r2->nField==nKeyCol );
102321 if( r2->aMem[i].flags & MEM_Null ){
102322 *pRes = -1;
102327 *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
102334 ** 2020-03-23
102336 ** The author disclaims copyright to this source code. In place of
102345 ** This file implements virtual-tables for examining the bytecode content
102352 /* An instance of the bytecode() table-valued function.
102356 sqlite3_vtab base; /* Base class - must be first */
102365 sqlite3_vtab_cursor base; /* Base class - must be first */
102380 ** Create a new bytecode() table-valued function.
102424 pNew->db = db;
102425 pNew->bTablesUsed = isTabUsed*2;
102448 sqlite3VdbeMemInit(&pCur->sub, pVTab->db, 1);
102449 *ppCursor = &pCur->base;
102457 sqlite3_free(pCur->zP4);
102458 pCur->zP4 = 0;
102459 sqlite3VdbeMemRelease(&pCur->sub);
102460 sqlite3VdbeMemSetNull(&pCur->sub);
102461 if( pCur->needFinalize ){
102462 sqlite3_finalize(pCur->pStmt);
102464 pCur->pStmt = 0;
102465 pCur->needFinalize = 0;
102466 pCur->zType = 0;
102467 pCur->zSchema = 0;
102468 pCur->zName = 0;
102487 bytecodevtab *pTab = (bytecodevtab*)cur->pVtab;
102489 if( pCur->zP4 ){
102490 sqlite3_free(pCur->zP4);
102491 pCur->zP4 = 0;
102493 if( pCur->zName ){
102494 pCur->zName = 0;
102495 pCur->zType = 0;
102496 pCur->zSchema = 0;
102499 (Vdbe*)pCur->pStmt,
102500 pCur->showSubprograms ? &pCur->sub : 0,
102501 pTab->bTablesUsed,
102502 &pCur->iRowid,
102503 &pCur->iAddr,
102504 &pCur->aOp);
102506 sqlite3VdbeMemSetNull(&pCur->sub);
102507 pCur->aOp = 0;
102518 return pCur->aOp==0;
102531 bytecodevtab *pVTab = (bytecodevtab*)cur->pVtab;
102532 Op *pOp = pCur->aOp + pCur->iAddr;
102533 if( pVTab->bTablesUsed ){
102537 if( i<=2 && pCur->zType==0 ){
102540 int iDb = pOp->p3;
102541 Pgno iRoot = (Pgno)pOp->p2;
102542 sqlite3 *db = pVTab->db;
102543 pSchema = db->aDb[iDb].pSchema;
102544 pCur->zSchema = db->aDb[iDb].zDbSName;
102545 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
102547 if( !IsVirtual(pTab) && pTab->tnum==iRoot ){
102548 pCur->zName = pTab->zName;
102549 pCur->zType = "table";
102553 if( pCur->zName==0 ){
102554 for(k=sqliteHashFirst(&pSchema->idxHash); k; k=sqliteHashNext(k)){
102556 if( pIdx->tnum==iRoot ){
102557 pCur->zName = pIdx->zName;
102558 pCur->zType = "index";
102568 sqlite3_result_int(ctx, pCur->iAddr);
102571 sqlite3_result_text(ctx, (char*)sqlite3OpcodeName(pOp->opcode),
102572 -1, SQLITE_STATIC);
102575 sqlite3_result_int(ctx, pOp->p1);
102578 sqlite3_result_int(ctx, pOp->p2);
102581 sqlite3_result_int(ctx, pOp->p3);
102585 if( pCur->zP4==0 ){
102586 pCur->zP4 = sqlite3VdbeDisplayP4(pVTab->db, pOp);
102589 sqlite3_result_text(ctx, pCur->zP4, -1, SQLITE_STATIC);
102592 char *zCom = sqlite3VdbeDisplayComment(pVTab->db, pOp, pCur->zP4);
102593 sqlite3_result_text(ctx, zCom, -1, sqlite3_free);
102598 sqlite3_result_int(ctx, pOp->p5);
102601 Op *aOp = pCur->aOp;
102603 assert( aOp[0].p4.z==0 || strncmp(aOp[0].p4.z,"-" "- ",3)==0 );
102604 if( pCur->iRowid==pCur->iAddr+1 ){
102607 sqlite3_result_text(ctx, aOp[0].p4.z+3, -1, SQLITE_STATIC);
102614 sqlite3_result_text(ctx, pCur->zType, -1, SQLITE_STATIC);
102617 sqlite3_result_text(ctx, pCur->zSchema, -1, SQLITE_STATIC);
102620 sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC);
102623 sqlite3_result_int(ctx, pOp->opcode==OP_OpenWrite);
102635 *pRowid = pCur->iRowid;
102651 bytecodevtab *pVTab = (bytecodevtab *)pVtabCursor->pVtab;
102655 pCur->iRowid = 0;
102656 pCur->iAddr = 0;
102657 pCur->showSubprograms = idxNum==0;
102664 rc = sqlite3_prepare_v2(pVTab->db, zSql, -1, &pCur->pStmt, 0);
102665 pCur->needFinalize = 1;
102668 pCur->pStmt = (sqlite3_stmt*)sqlite3_value_pointer(argv[0],"stmt-pointer");
102670 if( pCur->pStmt==0 ){
102671 pVTab->base.zErrMsg = sqlite3_mprintf(
102673 pVTab->bTablesUsed ? "tables_used" : "bytecode"
102695 int iBaseCol = pVTab->bTablesUsed ? 4 : 8;
102696 pIdxInfo->estimatedCost = (double)100;
102697 pIdxInfo->estimatedRows = 100;
102698 pIdxInfo->idxNum = 0;
102699 for(i=0, p=pIdxInfo->aConstraint; i<pIdxInfo->nConstraint; i++, p++){
102700 if( p->usable==0 ) continue;
102701 if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==iBaseCol+1 ){
102703 pIdxInfo->aConstraintUsage[i].omit = 1;
102704 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
102706 if( p->op==SQLITE_INDEX_CONSTRAINT_ISNULL && p->iColumn==iBaseCol ){
102707 pIdxInfo->aConstraintUsage[i].omit = 1;
102708 pIdxInfo->idxNum = 1;
102763 ** The author disclaims copyright to this source code. In place of
102772 ** This file contains code use to implement an in-memory rollback journal.
102773 ** The in-memory rollback journal is used to journal transactions for
102776 ** Update: The in-memory journal is also used to temporarily cache
102777 ** smaller journals that are not critical for power-loss recovery.
102795 ** The zChunk array is always at least 8 bytes in size - usually much more.
102812 #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
102824 ** This structure is a subclass of sqlite3_file. Each open memory-journal
102829 int nChunkSize; /* In-memory chunk-size */
102832 FileChunk *pFirst; /* Head of in-memory chunk-list */
102842 ** Read data from the in-memory journal file. This is the implementation
102857 if( (iAmt+iOfst)>p->endpoint.iOffset ){
102860 assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
102861 if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
102863 for(pChunk=p->pFirst;
102864 ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
102865 pChunk=pChunk->pNext
102867 iOff += p->nChunkSize;
102870 pChunk = p->readpoint.pChunk;
102874 iChunkOffset = (int)(iOfst%p->nChunkSize);
102876 int iSpace = p->nChunkSize - iChunkOffset;
102877 int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
102878 memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
102880 nRead -= iSpace;
102882 } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
102883 p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
102884 p->readpoint.pChunk = pChunk;
102896 pNext = pIter->pNext;
102915 for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
102917 nChunk = copy.endpoint.iOffset - iOff;
102919 rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
102924 /* No error has occurred. Free the in-memory buffers. */
102930 ** the original before returning. This way, SQLite uses the in-memory
102931 ** journal data to roll back changes made to the internal page-cache
102958 if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
102968 /* An in-memory journal file should only ever be appended to. Random
102970 ** the in-memory journal is being used by a connection using the
102971 ** atomic-write optimization. In this case the first 28 bytes of the
102973 assert( iOfst<=p->endpoint.iOffset );
102974 if( iOfst>0 && iOfst!=p->endpoint.iOffset ){
102977 if( iOfst==0 && p->pFirst ){
102978 assert( p->nChunkSize>iAmt );
102979 memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
102982 FileChunk *pChunk = p->endpoint.pChunk;
102983 int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
102984 int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
102989 FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
102993 pNew->pNext = 0;
102995 assert( p->pFirst );
102996 pChunk->pNext = pNew;
102998 assert( !p->pFirst );
102999 p->pFirst = pNew;
103001 pChunk = p->endpoint.pChunk = pNew;
103005 memcpy((u8*)pChunk->zChunk + iChunkOffset, zWrite, iSpace);
103007 nWrite -= iSpace;
103008 p->endpoint.iOffset += iSpace;
103017 ** Truncate the in-memory file.
103021 assert( p->endpoint.pChunk==0 || p->endpoint.pChunk->pNext==0 );
103022 if( size<p->endpoint.iOffset ){
103025 memjrnlFreeChunks(p->pFirst);
103026 p->pFirst = 0;
103028 i64 iOff = p->nChunkSize;
103029 for(pIter=p->pFirst; ALWAYS(pIter) && iOff<size; pIter=pIter->pNext){
103030 iOff += p->nChunkSize;
103033 memjrnlFreeChunks(pIter->pNext);
103034 pIter->pNext = 0;
103038 p->endpoint.pChunk = pIter;
103039 p->endpoint.iOffset = size;
103040 p->readpoint.pChunk = 0;
103041 p->readpoint.iOffset = 0;
103051 memjrnlFreeChunks(p->pFirst);
103059 ** syncing an in-memory journal is a no-op.
103071 *pSize = (sqlite_int64) p->endpoint.iOffset;
103106 ** all content is always stored in main-memory. Finally, if nSpill is a
103107 ** positive value, then the journal file is initially created in-memory
103123 /* Zero the file-handle object. If nSpill was passed zero, initialize
103126 ** made on the journal file-handle. */
103133 p->nChunkSize = nSpill;
103135 p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
103136 assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
103139 pJfd->pMethods = (const sqlite3_io_methods*)&MemJournalMethods;
103140 p->nSpill = nSpill;
103141 p->flags = flags;
103142 p->zJournal = zName;
103143 p->pVfs = pVfs;
103148 ** Open an in-memory journal file.
103151 sqlite3JournalOpen(0, 0, pJfd, 0, -1);
103158 ** in-memory-only journal file (i.e. is one that was opened with a +ve
103165 if( pJfd->pMethods==&MemJournalMethods && (
103167 p->nSpill>0
103172 NEVER(p->nSpill>0)
103175 || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
103185 ** The file-handle passed as the only argument is open on a journal file.
103190 return p->pMethods==&MemJournalMethods;
103195 ** pVfs to create the underlying on-disk files.
103198 return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
103206 ** The author disclaims copyright to this source code. In place of
103229 for(pWin=pList; pWin; pWin=pWin->pNextWin){
103231 rc = sqlite3WalkExprList(pWalker, pWin->pOrderBy);
103233 rc = sqlite3WalkExprList(pWalker, pWin->pPartition);
103235 rc = sqlite3WalkExpr(pWalker, pWin->pFilter);
103237 rc = sqlite3WalkExpr(pWalker, pWin->pStart);
103239 rc = sqlite3WalkExpr(pWalker, pWin->pEnd);
103261 ** return from the top-level walk call.
103271 rc = pWalker->xExprCallback(pWalker, pExpr);
103274 assert( pExpr->x.pList==0 || pExpr->pRight==0 );
103275 if( pExpr->pLeft && walkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
103276 if( pExpr->pRight ){
103278 pExpr = pExpr->pRight;
103282 if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
103284 if( pExpr->x.pList ){
103285 if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
103289 if( walkWindowList(pWalker, pExpr->y.pWin, 1) ) return WRC_Abort;
103310 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
103311 if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
103318 ** This is a no-op callback for Walker->xSelectCallback2. If this
103319 ** callback is set, then the Select->pWinDefn list is traversed.
103324 /* No-op */
103334 if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
103335 if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
103336 if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
103337 if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
103338 if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
103339 if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
103341 if( p->pWinDefn ){
103343 if( pWalker->xSelectCallback2==sqlite3WalkWinDefnDummyCallback
103344 || ((pParse = pWalker->pParse)!=0 && IN_RENAME_OBJECT)
103346 || pWalker->xSelectCallback2==sqlite3SelectPopWith
103351 int rc = walkWindowList(pWalker, p->pWinDefn, 0);
103371 pSrc = p->pSrc;
103373 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
103374 if( pItem->pSelect && sqlite3WalkSelect(pWalker, pItem->pSelect) ){
103377 if( pItem->fg.isTabFunc
103378 && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
103390 ** on the compound select chain, p->pPrior.
103395 ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
103402 ** is a no-op returning WRC_Continue.
103407 if( pWalker->xSelectCallback==0 ) return WRC_Continue;
103409 rc = pWalker->xSelectCallback(pWalker, p);
103416 if( pWalker->xSelectCallback2 ){
103417 pWalker->xSelectCallback2(pWalker, p);
103419 p = p->pPrior;
103429 pWalker->walkerDepth++;
103434 pWalker->walkerDepth--;
103439 ** No-op routine for the parse-tree walker.
103453 ** No-op routine for the parse-tree walker for SELECT statements.
103466 ** The author disclaims copyright to this source code. In place of
103493 ** is a helper function - a callback for the tree walker.
103498 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
103512 ** Turn the pExpr expression into an alias for the iCol-th column of the
103533 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
103537 Expr *pOrig; /* The iCol-th column of the result set */
103541 assert( iCol>=0 && iCol<pEList->nExpr );
103542 pOrig = pEList->a[iCol].pExpr;
103544 db = pParse->db;
103546 if( db->mallocFailed ){
103552 if( pExpr->op==TK_COLLATE ){
103554 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
103560 if( ALWAYS(pExpr->y.pWin!=0) ){
103561 pExpr->y.pWin->pOwner = pExpr;
103583 if( pItem->fg.eEName!=ENAME_TAB ) return 0;
103584 zSpan = pItem->zEName;
103602 ** Return TRUE if the double-quoted string mis-feature should be supported.
103605 if( db->init.busy ) return 1; /* Always support for legacy schemas */
103606 if( pTopNC->ncFlags & NC_IsDDL ){
103608 if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
103611 return (db->flags & SQLITE_DqsDDL)!=0;
103614 return (db->flags & SQLITE_DqsDML)!=0;
103619 ** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
103626 n = pExpr->iColumn;
103628 pExTab = pExpr->y.pTab;
103630 if( (pExTab->tabFlags & TF_HasGenerated)!=0
103631 && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
103633 testcase( pExTab->nCol==BMS-1 );
103634 testcase( pExTab->nCol==BMS );
103635 return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
103637 testcase( n==BMS-1 );
103639 if( n>=BMS ) n = BMS-1;
103653 SrcItem *pMatch, /* Source table containing the column */
103656 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
103658 pNew->iTable = pMatch->iCursor;
103659 pNew->iColumn = iColumn;
103660 pNew->y.pTab = pMatch->pTab;
103661 assert( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 );
103669 ** that name in the set of source tables in pSrcList and make the pExpr
103670 ** expression node refer back to that source column. The following changes
103673 ** pExpr->iDb Set the index in db->aDb[] of the database X
103675 ** pExpr->iTable Set to the cursor number for the table obtained
103677 ** pExpr->y.pTab Points to the Table structure of X.Y (even if
103679 ** pExpr->iColumn Set to the column number within the table.
103680 ** pExpr->op Set to TK_COLUMN.
103681 ** pExpr->pLeft Any expression this points to is deleted
103682 ** pExpr->pRight Any expression this points to is deleted.
103706 sqlite3 *db = pParse->db; /* The database connection */
103711 int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
103721 /* Initialize the node to no-match */
103722 pExpr->iTable = -1;
103730 testcase( pNC->ncFlags & NC_PartIdx );
103731 testcase( pNC->ncFlags & NC_IsCheck );
103732 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
103739 for(i=0; i<db->nDb; i++){
103740 assert( db->aDb[i].zDbSName );
103741 if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
103742 pSchema = db->aDb[i].pSchema;
103746 if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
103749 pSchema = db->aDb[0].pSchema;
103750 zDb = db->aDb[0].zDbSName;
103755 /* Start at the inner-most context and move outward until a match is found */
103759 SrcList *pSrcList = pNC->pSrcList;
103762 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
103764 pTab = pItem->pTab;
103765 assert( pTab!=0 && pTab->zName!=0 );
103766 assert( pTab->nCol>0 || pParse->nErr );
103767 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
103768 if( pItem->fg.isNestedFrom ){
103773 ** This pItem -------------^
103776 assert( pItem->pSelect!=0 );
103777 pEList = pItem->pSelect->pEList;
103779 assert( pEList->nExpr==pTab->nCol );
103780 for(j=0; j<pEList->nExpr; j++){
103781 if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){
103785 if( pItem->fg.isUsing==0
103786 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
103794 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
103795 /* An INNER or LEFT JOIN. Use the left-most table */
103798 if( (pItem->fg.jointype & JT_LEFT)==0 ){
103799 /* A RIGHT JOIN. Use the right-most table */
103805 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
103811 pExpr->iColumn = j;
103812 pEList->a[j].fg.bUsed = 1;
103814 if( pEList->a[j].fg.bUsingTerm ) break;
103822 if( pTab->pSchema!=pSchema ) continue;
103825 zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
103831 if( IN_RENAME_OBJECT && pItem->zAlias ){
103832 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
103836 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
103837 if( pCol->hName==hCol
103838 && sqlite3StrICmp(pCol->zCnName, zCol)==0
103841 if( pItem->fg.isUsing==0
103842 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
103850 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
103851 /* An INNER or LEFT JOIN. Use the left-most table */
103854 if( (pItem->fg.jointype & JT_LEFT)==0 ){
103855 /* A RIGHT JOIN. Use the right-most table */
103861 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
103866 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
103867 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
103868 if( pItem->fg.isNestedFrom ){
103880 pExpr->iTable = pMatch->iCursor;
103882 pExpr->y.pTab = pMatch->pTab;
103883 if( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ){
103886 pSchema = pExpr->y.pTab->pSchema;
103899 if( pParse->pTriggerTab!=0 ){
103900 int op = pParse->eTriggerOp;
103902 if( pParse->bReturning ){
103903 if( (pNC->ncFlags & NC_UBaseReg)!=0
103904 && (zTab==0 || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0)
103906 pExpr->iTable = op!=TK_DELETE;
103907 pTab = pParse->pTriggerTab;
103910 pExpr->iTable = 1;
103911 pTab = pParse->pTriggerTab;
103913 pExpr->iTable = 0;
103914 pTab = pParse->pTriggerTab;
103919 if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){
103920 Upsert *pUpsert = pNC->uNC.pUpsert;
103922 pTab = pUpsert->pUpsertSrc->a[0].pTab;
103923 pExpr->iTable = EXCLUDED_TABLE_NUMBER;
103931 pSchema = pTab->pSchema;
103933 for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
103934 if( pCol->hName==hCol
103935 && sqlite3StrICmp(pCol->zCnName, zCol)==0
103937 if( iCol==pTab->iPKey ){
103938 iCol = -1;
103943 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
103944 /* IMP: R-51414-32910 */
103945 iCol = -1;
103947 if( iCol<pTab->nCol ){
103951 if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
103952 testcase( iCol==(-1) );
103955 pExpr->iColumn = iCol;
103956 pExpr->y.pTab = pTab;
103959 pExpr->iTable = pNC->uNC.pUpsert->regData +
103967 pExpr->y.pTab = pTab;
103968 if( pParse->bReturning ){
103970 pExpr->op2 = TK_COLUMN;
103971 pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
103974 pExpr->iColumn = (i16)iCol;
103978 pExpr->affExpr = SQLITE_AFF_INTEGER;
103979 }else if( pExpr->iTable==0 ){
103982 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
103986 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
104002 && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
104004 && ALWAYS(VisibleRowid(pMatch->pTab))
104007 pExpr->iColumn = -1;
104008 pExpr->affExpr = SQLITE_AFF_INTEGER;
104013 ** might refer to an result-set alias. This happens, for example, when
104023 ** The ability to use an output result-set column in the WHERE, GROUP BY,
104030 && (pNC->ncFlags & NC_UEList)!=0
104033 pEList = pNC->uNC.pEList;
104035 for(j=0; j<pEList->nExpr; j++){
104036 char *zAs = pEList->a[j].zEName;
104037 if( pEList->a[j].fg.eEName==ENAME_NAME
104041 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
104042 assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 );
104043 assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 );
104044 pOrig = pEList->a[j].pExpr;
104045 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
104050 && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
104075 pNC = pNC->pNext;
104082 ** supplied) and the value of Z is enclosed in double-quotes, then
104087 ** Because no reference was made to outer contexts, the pNC->nRef
104091 assert( pExpr->op==TK_ID );
104095 /* If a double-quoted identifier does not match any known column name,
104099 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
104110 "double-quoted string literal: \"%w\"", zCol);
104112 sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
104114 pExpr->op = TK_STRING;
104115 memset(&pExpr->y, 0, sizeof(pExpr->y));
104135 if( pFJMatch->nExpr==cnt-1 ){
104139 sqlite3ExprDelete(db, pExpr->pLeft);
104140 pExpr->pLeft = 0;
104141 sqlite3ExprDelete(db, pExpr->pRight);
104142 pExpr->pRight = 0;
104144 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
104145 pExpr->op = TK_FUNCTION;
104146 pExpr->u.zToken = "coalesce";
104147 pExpr->x.pList = pFJMatch;
104163 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
104164 pParse->checkSchema = 1;
104165 pTopNC->nNcErr++;
104171 sqlite3ExprDelete(db, pExpr->pLeft);
104172 pExpr->pLeft = 0;
104173 sqlite3ExprDelete(db, pExpr->pRight);
104174 pExpr->pRight = 0;
104192 if( pExpr->iColumn>=0 && pMatch!=0 ){
104193 pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
104196 pExpr->op = eNewExprOp;
104201 if( pParse->db->xAuth
104202 && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER)
104204 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
104211 pTopNC->nRef++;
104213 pTopNC = pTopNC->pNext;
104228 SrcItem *pItem = &pSrc->a[iSrc];
104231 pTab = p->y.pTab = pItem->pTab;
104232 p->iTable = pItem->iCursor;
104233 if( p->y.pTab->iPKey==iCol ){
104234 p->iColumn = -1;
104236 p->iColumn = (ynVar)iCol;
104237 if( (pTab->tabFlags & TF_HasGenerated)!=0
104238 && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
104240 testcase( pTab->nCol==63 );
104241 testcase( pTab->nCol==64 );
104242 pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
104245 testcase( iCol==BMS-1 );
104246 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
104255 ** pNC->ncFlags values determined by validMask.
104277 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
104279 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
104282 else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
104285 if( pExpr ) pExpr->op = TK_NULL;
104286 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
104290 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
104294 ** Return 1024 times this value. Or return -1 if p is not a floating point
104298 double r = -1.0;
104299 if( p->op!=TK_FLOAT ) return -1;
104301 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
104303 if( r>1.0 ) return -1;
104322 pNC = pWalker->u.pNC;
104324 pParse = pNC->pParse;
104325 assert( pParse==pWalker->pParse );
104328 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
104329 SrcList *pSrcList = pNC->pSrcList;
104331 for(i=0; i<pNC->pSrcList->nSrc; i++){
104332 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
104336 switch( pExpr->op ){
104344 SrcList *pSrcList = pNC->pSrcList;
104346 assert( pSrcList && pSrcList->nSrc>=1 );
104347 pItem = pSrcList->a;
104348 pExpr->op = TK_COLUMN;
104350 pExpr->y.pTab = pItem->pTab;
104351 pExpr->iTable = pItem->iCursor;
104352 pExpr->iColumn--;
104353 pExpr->affExpr = SQLITE_AFF_INTEGER;
104359 ** "expr IS NOT NULL" --> "TRUE"
104360 ** "expr IS NULL" --> "FALSE"
104365 ** If this optimization occurs, also restore the NameContext ref-counts
104376 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
104377 anRef[i] = p->nRef;
104379 sqlite3WalkExpr(pWalker, pExpr->pLeft);
104380 if( 0==sqlite3ExprCanBeNull(pExpr->pLeft) && !IN_RENAME_OBJECT ){
104383 if( pExpr->op==TK_NOTNULL ){
104384 pExpr->u.zToken = "true";
104387 pExpr->u.zToken = "false";
104390 pExpr->op = TK_TRUEFALSE;
104391 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
104392 p->nRef = anRef[i];
104394 sqlite3ExprDelete(pParse->db, pExpr->pLeft);
104395 pExpr->pLeft = 0;
104405 ** be one call to lookupName(). Then the compiler will in-line
104415 if( pExpr->op==TK_ID ){
104419 zColumn = pExpr->u.zToken;
104421 Expr *pLeft = pExpr->pLeft;
104422 testcase( pNC->ncFlags & NC_IdxExpr );
104423 testcase( pNC->ncFlags & NC_GenCol );
104426 pRight = pExpr->pRight;
104427 if( pRight->op==TK_ID ){
104430 assert( pRight->op==TK_DOT );
104432 zDb = pLeft->u.zToken;
104433 pLeft = pRight->pLeft;
104434 pRight = pRight->pRight;
104437 zTable = pLeft->u.zToken;
104438 zColumn = pRight->u.zToken;
104442 sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
104451 ExprList *pList = pExpr->x.pList; /* The argument list */
104452 int n = pList ? pList->nExpr : 0; /* Number of arguments */
104458 u8 enc = ENC(pParse->db); /* The database encoding */
104459 int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
104461 Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
104464 zId = pExpr->u.zToken;
104465 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
104467 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
104474 is_agg = pDef->xFinalize!=0;
104475 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
104478 pExpr->iTable = exprProbability(pList->a[1].pExpr);
104479 if( pExpr->iTable<0 ){
104483 pNC->nNcErr++;
104486 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
104488 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
104489 ** short-hand for likelihood(X,0.0625).
104490 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
104492 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
104495 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
104500 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
104505 pNC->nNcErr++;
104507 pExpr->op = TK_NULL;
104512 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
104519 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
104520 /* Clearly non-deterministic functions like random(), but also
104526 sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
104530 pExpr->op2 = pNC->ncFlags & NC_SelfRef;
104531 if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
104533 if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
104534 && pParse->nested==0
104535 && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
104537 /* Internal-use-only functions are disallowed unless the
104539 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
104544 if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
104553 assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
104554 || (pDef->xValue==0 && pDef->xInverse==0)
104555 || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
104557 if( pDef && pDef->xValue==0 && pWin ){
104561 pNC->nNcErr++;
104563 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
104564 || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
104565 || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
104568 if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
104574 pNC->nNcErr++;
104578 if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
104580 pNC->nNcErr++;
104584 else if( no_such_func && pParse->db->init.busy==0
104586 && pParse->explain==0
104590 pNC->nNcErr++;
104594 pNC->nNcErr++;
104599 "FILTER may not be used with non-aggregate %#T()",
104602 pNC->nNcErr++;
104610 pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
104612 pNC->ncFlags &= ~NC_AllowAgg;
104625 Select *pSel = pNC->pWinSelect;
104626 assert( pWin==0 || (ExprUseYWin(pExpr) && pWin==pExpr->y.pWin) );
104628 sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
104629 if( pParse->db->mallocFailed ) break;
104631 sqlite3WalkExprList(pWalker, pWin->pPartition);
104632 sqlite3WalkExprList(pWalker, pWin->pOrderBy);
104633 sqlite3WalkExpr(pWalker, pWin->pFilter);
104635 pNC->ncFlags |= NC_HasWin;
104640 pExpr->op = TK_AGG_FUNCTION;
104641 pExpr->op2 = 0;
104644 sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
104649 && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
104651 pExpr->op2++;
104652 pNC2 = pNC2->pNext;
104658 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
104659 testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
104660 pNC2->ncFlags |= NC_HasAgg
104661 | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
104665 pNC->ncFlags |= savedAllowFlags;
104667 /* FIX ME: Compute pExpr->affinity based on the expected return
104674 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
104677 testcase( pExpr->op==TK_IN );
104679 int nRef = pNC->nRef;
104680 testcase( pNC->ncFlags & NC_IsCheck );
104681 testcase( pNC->ncFlags & NC_PartIdx );
104682 testcase( pNC->ncFlags & NC_IdxExpr );
104683 testcase( pNC->ncFlags & NC_GenCol );
104684 if( pNC->ncFlags & NC_SelfRef ){
104687 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
104689 assert( pNC->nRef>=nRef );
104690 if( nRef!=pNC->nRef ){
104692 pNC->ncFlags |= NC_VarSelect;
104698 testcase( pNC->ncFlags & NC_IsCheck );
104699 testcase( pNC->ncFlags & NC_PartIdx );
104700 testcase( pNC->ncFlags & NC_IdxExpr );
104701 testcase( pNC->ncFlags & NC_GenCol );
104708 Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
104712 if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
104715 if( pRight->op==TK_TRUEFALSE ){
104716 pExpr->op2 = pExpr->op;
104717 pExpr->op = TK_TRUTH;
104731 if( pParse->db->mallocFailed ) break;
104732 assert( pExpr->pLeft!=0 );
104733 nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
104734 if( pExpr->op==TK_BETWEEN ){
104736 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
104738 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
104741 assert( pExpr->pRight!=0 );
104742 nRight = sqlite3ExprVectorSize(pExpr->pRight);
104745 testcase( pExpr->op==TK_EQ );
104746 testcase( pExpr->op==TK_NE );
104747 testcase( pExpr->op==TK_LT );
104748 testcase( pExpr->op==TK_LE );
104749 testcase( pExpr->op==TK_GT );
104750 testcase( pExpr->op==TK_GE );
104751 testcase( pExpr->op==TK_IS );
104752 testcase( pExpr->op==TK_ISNOT );
104753 testcase( pExpr->op==TK_BETWEEN );
104755 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
104760 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
104761 return pParse->nErr ? WRC_Abort : WRC_Continue;
104768 ** to the AS-name of one of the terms of the expression list. If it is,
104785 if( pE->op==TK_ID ){
104788 zCol = pE->u.zToken;
104789 for(i=0; i<pEList->nExpr; i++){
104790 if( pEList->a[i].fg.eEName==ENAME_NAME
104791 && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
104809 ** Attempt to match pE against result set columns in the left-most
104811 ** as an indication to the caller that it should sort by the i-th column.
104812 ** The left-most column is 1. In other words, the value returned is the
104816 ** If there is no match, return 0. Return -1 if an error occurs.
104828 u8 savedSuppErr; /* Saved value of db->suppressErr */
104831 pEList = pSelect->pEList;
104837 nc.pSrcList = pSelect->pSrc;
104841 db = pParse->db;
104842 savedSuppErr = db->suppressErr;
104843 db->suppressErr = 1;
104845 db->suppressErr = savedSuppErr;
104849 ** in the result set. Return an 1-based index of the matching
104850 ** result-set entry.
104852 for(i=0; i<pEList->nExpr; i++){
104853 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
104863 ** Generate an ORDER BY or GROUP BY term out-of-range error.
104868 int i, /* The index (1-based) of the term out of range */
104873 "%r %s BY term out of range - should be "
104875 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
104887 ** beginning with the left-most SELECT and working toward the right.
104903 pOrderBy = pSelect->pOrderBy;
104905 db = pParse->db;
104906 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
104910 for(i=0; i<pOrderBy->nExpr; i++){
104911 pOrderBy->a[i].fg.done = 0;
104913 pSelect->pNext = 0;
104914 while( pSelect->pPrior ){
104915 pSelect->pPrior->pNext = pSelect;
104916 pSelect = pSelect->pPrior;
104921 pEList = pSelect->pEList;
104923 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
104924 int iCol = -1;
104926 if( pItem->fg.done ) continue;
104927 pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
104930 if( iCol<=0 || iCol>pEList->nExpr ){
104931 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
104949 if( !db->mallocFailed ){
104965 pNew->flags |= EP_IntValue;
104966 pNew->u.iValue = iCol;
104967 if( pItem->pExpr==pE ){
104968 pItem->pExpr = pNew;
104970 Expr *pParent = pItem->pExpr;
104971 assert( pParent->op==TK_COLLATE );
104972 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
104973 assert( pParent->pLeft==pE );
104974 pParent->pLeft = pNew;
104977 pItem->u.x.iOrderByCol = (u16)iCol;
104979 pItem->fg.done = 1;
104984 pSelect = pSelect->pNext;
104986 for(i=0; i<pOrderBy->nExpr; i++){
104987 if( pOrderBy->a[i].fg.done==0 ){
105004 ** return non-zero. Return zero if no errors are seen.
105013 sqlite3 *db = pParse->db;
105017 if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
105018 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
105022 pEList = pSelect->pEList;
105024 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
105025 if( pItem->u.x.iOrderByCol ){
105026 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
105027 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
105030 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
105043 Window *pWin = pExpr->y.pWin;
105054 if( pSelect->pWin ){
105072 ** If the order-by term is an integer I between 1 and N (where N is the
105074 ** in the resolution is a copy of the I-th result-set expression. If
105075 ** the order-by term is an identifier that corresponds to the AS-name of
105076 ** a result-set expression, then the term resolves to a copy of the
105077 ** result-set expression. Otherwise, the expression is resolved in
105078 ** the usual way - using sqlite3ResolveExprNames().
105097 nResult = pSelect->pEList->nExpr;
105098 pParse = pNC->pParse;
105099 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
105100 Expr *pE = pItem->pExpr;
105104 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
105106 /* If an AS-name match is found, mark this ORDER BY column as being
105107 ** a copy of the iCol-th result-set column. The subsequent call to
105109 ** copy of the iCol-th result-set expression. */
105110 pItem->u.x.iOrderByCol = (u16)iCol;
105117 ** order-by term to a copy of the result-set expression */
105122 pItem->u.x.iOrderByCol = (u16)iCol;
105127 pItem->u.x.iOrderByCol = 0;
105131 for(j=0; j<pSelect->pEList->nExpr; j++){
105132 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
105137 pItem->u.x.iOrderByCol = j+1;
105155 Select *pLeftmost; /* Left-most of SELECT of a compound */
105160 if( p->selFlags & SF_Resolved ){
105163 pOuterNC = pWalker->u.pNC;
105164 pParse = pWalker->pParse;
105165 db = pParse->db;
105175 if( (p->selFlags & SF_Expanded)==0 ){
105177 return pParse->nErr ? WRC_Abort : WRC_Prune;
105180 isCompound = p->pPrior!=0;
105184 assert( (p->selFlags & SF_Expanded)!=0 );
105185 assert( (p->selFlags & SF_Resolved)==0 );
105186 assert( db->suppressErr==0 ); /* SF_Resolved not set if errors suppressed */
105187 p->selFlags |= SF_Resolved;
105196 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
105202 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
105203 ** as if it were part of the sub-query, not the parent. This block
105204 ** moves the pOrderBy down to the sub-query. It will be moved back
105206 if( p->selFlags & SF_Converted ){
105207 Select *pSub = p->pSrc->a[0].pSelect;
105208 assert( p->pSrc->nSrc==1 && p->pOrderBy );
105209 assert( pSub->pPrior && pSub->pOrderBy==0 );
105210 pSub->pOrderBy = p->pOrderBy;
105211 p->pOrderBy = 0;
105216 for(i=0; i<p->pSrc->nSrc; i++){
105217 SrcItem *pItem = &p->pSrc->a[i];
105218 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
105219 int nRef = pOuterNC ? pOuterNC->nRef : 0;
105220 const char *zSavedContext = pParse->zAuthContext;
105222 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
105223 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
105224 pParse->zAuthContext = zSavedContext;
105225 if( pParse->nErr ) return WRC_Abort;
105226 assert( db->mallocFailed==0 );
105229 ** expressions in the sub-select were resolved, the sub-select
105235 assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
105236 pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
105241 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
105242 ** resolve the result-set expression list.
105245 sNC.pSrcList = p->pSrc;
105249 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
105252 /* If there are no aggregate functions in the result-set, and no GROUP BY
105255 assert( (p->selFlags & SF_Aggregate)==0 );
105256 pGroupBy = p->pGroupBy;
105260 p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
105265 /* Add the output column list to the name-context before parsing the
105271 ** re-evaluated for each reference to it.
105274 sNC.uNC.pEList = p->pEList;
105276 if( p->pHaving ){
105277 if( (p->selFlags & SF_Aggregate)==0 ){
105278 sqlite3ErrorMsg(pParse, "HAVING clause on a non-aggregate query");
105281 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
105283 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
105285 /* Resolve names in table-valued-function arguments */
105286 for(i=0; i<p->pSrc->nSrc; i++){
105287 SrcItem *pItem = &p->pSrc->a[i];
105288 if( pItem->fg.isTabFunc
105289 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
105298 for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
105299 if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
105300 || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
105315 ** the sub-query back to the parent query. At this point each term
105319 if( p->selFlags & SF_Converted ){
105320 Select *pSub = p->pSrc->a[0].pSelect;
105321 p->pOrderBy = pSub->pOrderBy;
105322 pSub->pOrderBy = 0;
105327 ** below, after all of the result-sets for all of the elements of
105330 ** If there is an ORDER BY clause on a term of a compound-select other
105331 ** than the right-most term, then that is a syntax error. But the error
105335 if( p->pOrderBy!=0
105336 && isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
105337 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
105341 if( db->mallocFailed ){
105352 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
105355 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
105356 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
105366 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
105367 sqlite3SelectWrongNumTermsError(pParse, p->pNext);
105373 p = p->pPrior;
105389 ** table columns and result-set columns. At the same time, do error
105397 ** the symbolic name assigned to an ATTACH-ed database.
105408 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
105412 ** To resolve result-set references, look for expression nodes of the
105413 ** form Z (with no X and Y prefix) where the Z matches the right-hand
105414 ** size of an AS clause in the result-set of a SELECT. The Z expression
105415 ** is replaced by a copy of the left-hand side of the result-set expression.
105416 ** Table-name and function resolution occurs on the substituted expression
105443 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
105444 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
105445 w.pParse = pNC->pParse;
105447 w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
105451 w.pParse->nHeight += pExpr->nHeight;
105452 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
105458 w.pParse->nHeight -= pExpr->nHeight;
105462 testcase( pNC->ncFlags & NC_HasAgg );
105463 testcase( pNC->ncFlags & NC_HasWin );
105464 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
105465 pNC->ncFlags |= savedHasAgg;
105466 return pNC->nNcErr>0 || w.pParse->nErr>0;
105482 w.pParse = pNC->pParse;
105487 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
105488 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
105489 for(i=0; i<pList->nExpr; i++){
105490 Expr *pExpr = pList->a[i].pExpr;
105493 w.pParse->nHeight += pExpr->nHeight;
105494 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
105500 w.pParse->nHeight -= pExpr->nHeight;
105504 testcase( pNC->ncFlags & NC_HasAgg );
105505 testcase( pNC->ncFlags & NC_HasWin );
105506 if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
105507 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
105508 savedHasAgg |= pNC->ncFlags &
105510 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
105512 if( w.pParse->nErr>0 ) return WRC_Abort;
105514 pNC->ncFlags |= savedHasAgg;
105520 ** decendents of the SELECT, including compounds off of p->pPrior,
105551 ** ------------
105559 ** nodes of the expression is set to -1 and the Expr.iColumn value is
105571 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
105572 NameContext sNC; /* Name context for pParse->pNewTable */
105582 sSrc.a[0].zName = pTab->zName;
105584 sSrc.a[0].iCursor = -1;
105585 if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
105586 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
105604 ** The author disclaims copyright to this source code. In place of
105625 if( iCol<0 || NEVER(iCol>=pTab->nCol) ) return SQLITE_AFF_INTEGER;
105626 return pTab->aCol[iCol].affinity;
105633 ** or a sub-select with a column as the return value, then the
105648 assert( pExpr->op==TK_COLLATE
105649 || pExpr->op==TK_IF_NULL_ROW
105650 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
105651 pExpr = pExpr->pLeft;
105654 op = pExpr->op;
105655 if( op==TK_REGISTER ) op = pExpr->op2;
105658 assert( pExpr->y.pTab!=0 );
105659 return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
105663 assert( pExpr->x.pSelect!=0 );
105664 assert( pExpr->x.pSelect->pEList!=0 );
105665 assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
105666 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
105671 return sqlite3AffinityType(pExpr->u.zToken, 0);
105675 assert( pExpr->pLeft!=0 && ExprUseXSelect(pExpr->pLeft) );
105676 assert( pExpr->iColumn < pExpr->iTable );
105677 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
105679 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
105684 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
105686 return pExpr->affExpr;
105694 ** If a memory allocation error occurs, that fact is recorded in pParse->db
105703 if( pCollName->n>0 ){
105704 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
105706 pNew->pLeft = pExpr;
105707 pNew->flags |= EP_Collate|EP_Skip;
105729 assert( pExpr->op==TK_COLLATE );
105730 pExpr = pExpr->pLeft;
105744 assert( pExpr->x.pList->nExpr>0 );
105745 assert( pExpr->op==TK_FUNCTION );
105746 pExpr = pExpr->x.pList->a[0].pExpr;
105748 assert( pExpr->op==TK_COLLATE );
105749 pExpr = pExpr->pLeft;
105770 sqlite3 *db = pParse->db;
105774 int op = p->op;
105775 if( op==TK_REGISTER ) op = p->op2;
105779 assert( p->y.pTab!=0 );
105780 if( (j = p->iColumn)>=0 ){
105781 const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]);
105787 p = p->pLeft;
105792 p = p->x.pList->a[0].pExpr;
105797 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
105800 if( p->flags & EP_Collate ){
105801 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
105802 p = p->pLeft;
105804 Expr *pNext = p->pRight;
105807 assert( p->x.pList==0 || p->pRight==0 );
105808 if( p->x.pList!=0 && !db->mallocFailed ){
105810 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
105811 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
105812 pNext = p->x.pList->a[i].pExpr;
105841 if( p==0 ) p = pParse->db->pDfltColl;
105852 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
105884 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
105885 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
105886 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
105887 assert( pExpr->pLeft );
105888 aff = sqlite3ExprAffinity(pExpr->pLeft);
105889 if( pExpr->pRight ){
105890 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
105892 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
105949 if( pLeft->flags & EP_Collate ){
105951 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
105972 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
105974 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
105995 if( pParse->nErr ) return 0;
106002 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
106004 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
106024 ** is a sub-select, return the number of columns in the sub-select. For
106028 u8 op = pExpr->op;
106029 if( op==TK_REGISTER ) op = pExpr->op2;
106032 return pExpr->x.pList->nExpr;
106035 return pExpr->x.pSelect->pEList->nExpr;
106042 ** Return a pointer to a subexpression of pVector that is the i-th
106052 ** just the expression for the i-th term of the result set, and may
106057 assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );
106059 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
106060 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
106062 return pVector->x.pSelect->pEList->a[i].pExpr;
106065 return pVector->x.pList->a[i].pExpr;
106074 ** the iField-th column of the vector expression pVector.
106094 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
106099 if( pVector->op==TK_SELECT ){
106107 ** pLeft->iTable: First in an array of register holding result, or 0
106119 pRet->iTable = nField;
106120 pRet->iColumn = iField;
106121 pRet->pLeft = pVector;
106124 if( pVector->op==TK_VECTOR ){
106127 ppVector = &pVector->x.pList->a[iField].pExpr;
106135 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
106143 ** sub-select returns more than one column, the first in an array
106151 if( pExpr->op==TK_SELECT ){
106159 ** Argument pVector points to a vector expression - either a TK_VECTOR
106167 ** containing the results of the sub-select.
106184 u8 op = pVector->op;
106188 return pVector->iTable+iField;
106192 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
106197 *ppExpr = pVector->x.pList->a[iField].pExpr;
106210 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
106211 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
106212 ** otherwise: op==pExpr->op and p5==0
106221 Vdbe *v = pParse->pVdbe;
106222 Expr *pLeft = pExpr->pLeft;
106223 Expr *pRight = pExpr->pRight;
106234 if( pParse->nErr ) return;
106239 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
106240 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
106241 || pExpr->op==TK_LT || pExpr->op==TK_GT
106242 || pExpr->op==TK_LE || pExpr->op==TK_GE
106244 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
106245 || (pExpr->op==TK_ISNOT && op==TK_NE) );
106246 assert( p5==0 || pExpr->op!=op );
106247 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
106275 if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){
106285 if( i==nLeft-1 ){
106293 if( i==nLeft-2 ) opx = op;
106311 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
106332 if( p->nHeight>*pnHeight ){
106333 *pnHeight = p->nHeight;
106340 for(i=0; i<p->nExpr; i++){
106341 heightOfExpr(p->a[i].pExpr, pnHeight);
106347 for(p=pSelect; p; p=p->pPrior){
106348 heightOfExpr(p->pWhere, pnHeight);
106349 heightOfExpr(p->pHaving, pnHeight);
106350 heightOfExpr(p->pLimit, pnHeight);
106351 heightOfExprList(p->pEList, pnHeight);
106352 heightOfExprList(p->pGroupBy, pnHeight);
106353 heightOfExprList(p->pOrderBy, pnHeight);
106368 int nHeight = p->pLeft ? p->pLeft->nHeight : 0;
106369 if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){
106370 nHeight = p->pRight->nHeight;
106373 heightOfSelect(p->x.pSelect, &nHeight);
106374 }else if( p->x.pList ){
106375 heightOfExprList(p->x.pList, &nHeight);
106376 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
106378 p->nHeight = nHeight + 1;
106390 if( pParse->nErr ) return;
106392 sqlite3ExprCheckHeight(pParse, p->nHeight);
106410 if( pParse->nErr ) return;
106411 if( p && ExprUseXList(p) && p->x.pList ){
106412 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
106429 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
106433 ** can be translated into a 32-bit integer, then the token is not
106450 if( op!=TK_INTEGER || pToken->z==0
106451 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
106452 nExtra = pToken->n+1;
106459 pNew->op = (u8)op;
106460 pNew->iAgg = -1;
106463 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
106464 pNew->u.iValue = iValue;
106466 pNew->u.zToken = (char*)&pNew[1];
106467 assert( pToken->z!=0 || pToken->n==0 );
106468 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
106469 pNew->u.zToken[pToken->n] = 0;
106470 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
106476 pNew->nHeight = 1;
106483 ** Allocate a new expression node from a zero-terminated token that has
106510 assert( db->mallocFailed );
106515 assert( pRoot->x.pSelect==0 );
106517 pRoot->pRight = pRight;
106518 pRoot->flags |= EP_Propagate & pRight->flags;
106520 pRoot->nHeight = pRight->nHeight+1;
106522 pRoot->nHeight = 1;
106526 pRoot->pLeft = pLeft;
106527 pRoot->flags |= EP_Propagate & pLeft->flags;
106529 if( pLeft->nHeight>=pRoot->nHeight ){
106530 pRoot->nHeight = pLeft->nHeight+1;
106541 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
106551 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
106554 p->op = op & 0xff;
106555 p->iAgg = -1;
106556 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
106557 sqlite3ExprCheckHeight(pParse, p->nHeight);
106559 sqlite3ExprDelete(pParse->db, pLeft);
106560 sqlite3ExprDelete(pParse->db, pRight);
106571 pExpr->x.pSelect = pSelect;
106575 assert( pParse->db->mallocFailed );
106576 sqlite3SelectDelete(pParse->db, pSelect);
106603 for(ii=0; ii<pEList->nExpr; ii++){
106605 Expr *pExpr = pEList->a[ii].pExpr;
106607 if( pExpr->op==TK_VECTOR ){
106609 nExprElem = pExpr->x.pList->nExpr;
106614 sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d",
106620 pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0);
106621 pExpr->x.pList = 0;
106624 pSel->op = TK_ALL;
106625 pSel->pPrior = pRet;
106631 if( pRet && pRet->pPrior ){
106632 pRet->selFlags |= SF_MultiValue;
106634 sqlite3ExprListDelete(pParse->db, pEList);
106647 sqlite3 *db = pParse->db;
106674 sqlite3 *db = pParse->db;
106682 pNew->w.iOfst = (int)(pToken->z - pParse->zTail);
106684 && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]
106685 && !pParse->nested
106689 pNew->x.pList = pList;
106701 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
106703 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
106704 ** top-level SQL
106714 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
106716 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
106717 || (pParse->db->flags & SQLITE_TrustedSchema)==0
106740 ** the SQL statement comes from an external source.
106748 sqlite3 *db = pParse->db;
106754 z = pExpr->u.zToken;
106761 x = (ynVar)(++pParse->nVar);
106769 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
106770 i = z[1]-'0'; /* The common case of ?N for a single digit N */
106773 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
106777 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
106778 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
106779 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
106781 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
106782 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
106786 if( x>pParse->nVar ){
106787 pParse->nVar = (int)x;
106789 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
106797 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
106799 x = (ynVar)(++pParse->nVar);
106804 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
106807 pExpr->iColumn = x;
106808 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
106810 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
106820 assert( !ExprUseUValue(p) || p->u.iValue>=0 );
106822 assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
106823 assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
106826 assert( p->pLeft==0 );
106827 assert( p->pRight==0 );
106828 assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
106829 assert( !ExprUseXList(p) || p->x.pList==0 );
106834 assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );
106835 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
106836 if( p->pRight ){
106838 sqlite3ExprDeleteNN(db, p->pRight);
106841 sqlite3SelectDelete(db, p->x.pSelect);
106843 sqlite3ExprListDelete(db, p->x.pList);
106846 sqlite3WindowDelete(db, p->y.pWin);
106865 }else if( p->pOn ){
106866 sqlite3ExprDeleteNN(db, p->pOn);
106867 }else if( p->pUsing ){
106868 sqlite3IdListDelete(db, p->pUsing);
106880 ** pExpr to the pParse->pConstExpr list with a register number of 0.
106896 sqlite3ExprDeleteNN(pParse->db, p);
106922 ** The dupedExprStructSize() function returns two values OR-ed together:
106935 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
106941 ** to reduce a pristine expression tree from the parser. The implementation
106950 if( 0==flags || p->op==TK_SELECT_COLUMN
106960 if( p->pLeft || p->x.pList ){
106963 assert( p->pRight==0 );
106977 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
106978 nByte += sqlite3Strlen30NN(p->u.zToken)+1;
107001 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
107010 ** to store the copy of expression p, the copies of p->u.zToken
107011 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
107040 ** by the copy of the p->u.zToken string (if any).
107045 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
107046 nToken = sqlite3Strlen30(p->u.zToken) + 1;
107057 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
107062 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
107063 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
107064 pNew->flags |= staticFlag;
107070 /* Copy the p->u.zToken string, if any. */
107072 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
107073 memcpy(zToken, p->u.zToken, nToken);
107076 if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
107077 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
107079 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
107081 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
107085 /* Fill in pNew->pLeft and pNew->pRight. */
107089 pNew->pLeft = p->pLeft ?
107090 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
107091 pNew->pRight = p->pRight ?
107092 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
107096 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
107105 if( pNew->op==TK_SELECT_COLUMN ){
107106 pNew->pLeft = p->pLeft;
107107 assert( p->pRight==0 || p->pRight==p->pLeft
107108 || ExprHasProperty(p->pLeft, EP_Subquery) );
107110 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
107112 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
107122 ** and the db->mallocFailed flag set.
107128 sqlite3_int64 nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
107132 pRet->nCte = p->nCte;
107133 for(i=0; i<p->nCte; i++){
107134 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
107135 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
107136 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
107137 pRet->a[i].eM10d = p->a[i].eM10d;
107152 ** objects found there, assembling them onto the linked list at Select->pWin.
107155 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
107156 Select *pSelect = pWalker->u.pSelect;
107157 Window *pWin = pExpr->y.pWin;
107160 assert( pWin->ppThis==0 );
107166 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
107186 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
107195 ** part of the in-memory representation of the database schema.
107212 pNew->nExpr = p->nExpr;
107213 pNew->nAlloc = p->nAlloc;
107214 pItem = pNew->a;
107215 pOldItem = p->a;
107216 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
107217 Expr *pOldExpr = pOldItem->pExpr;
107219 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
107221 && pOldExpr->op==TK_SELECT_COLUMN
107222 && (pNewExpr = pItem->pExpr)!=0
107224 if( pNewExpr->pRight ){
107225 pPriorSelectColOld = pOldExpr->pRight;
107226 pPriorSelectColNew = pNewExpr->pRight;
107227 pNewExpr->pLeft = pNewExpr->pRight;
107229 if( pOldExpr->pLeft!=pPriorSelectColOld ){
107230 pPriorSelectColOld = pOldExpr->pLeft;
107232 pNewExpr->pRight = pPriorSelectColNew;
107234 pNewExpr->pLeft = pPriorSelectColNew;
107237 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
107238 pItem->fg = pOldItem->fg;
107239 pItem->fg.done = 0;
107240 pItem->u = pOldItem->u;
107259 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
107262 pNew->nSrc = pNew->nAlloc = p->nSrc;
107263 for(i=0; i<p->nSrc; i++){
107264 SrcItem *pNewItem = &pNew->a[i];
107265 const SrcItem *pOldItem = &p->a[i];
107267 pNewItem->pSchema = pOldItem->pSchema;
107268 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
107269 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
107270 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
107271 pNewItem->fg = pOldItem->fg;
107272 pNewItem->iCursor = pOldItem->iCursor;
107273 pNewItem->addrFillSub = pOldItem->addrFillSub;
107274 pNewItem->regReturn = pOldItem->regReturn;
107275 if( pNewItem->fg.isIndexedBy ){
107276 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
107278 pNewItem->u2 = pOldItem->u2;
107279 if( pNewItem->fg.isCte ){
107280 pNewItem->u2.pCteUse->nUse++;
107282 if( pNewItem->fg.isTabFunc ){
107283 pNewItem->u1.pFuncArg =
107284 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
107286 pTab = pNewItem->pTab = pOldItem->pTab;
107288 pTab->nTabRef++;
107290 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
107291 if( pOldItem->fg.isUsing ){
107292 assert( pNewItem->fg.isUsing );
107293 pNewItem->u3.pUsing = sqlite3IdListDup(db, pOldItem->u3.pUsing);
107295 pNewItem->u3.pOn = sqlite3ExprDup(db, pOldItem->u3.pOn, flags);
107297 pNewItem->colUsed = pOldItem->colUsed;
107306 assert( p->eU4!=EU4_EXPR );
107307 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew)+(p->nId-1)*sizeof(p->a[0]) );
107309 pNew->nId = p->nId;
107310 pNew->eU4 = p->eU4;
107311 for(i=0; i<p->nId; i++){
107312 struct IdList_item *pNewItem = &pNew->a[i];
107313 const struct IdList_item *pOldItem = &p->a[i];
107314 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
107315 pNewItem->u4 = pOldItem->u4;
107326 for(p=pDup; p; p=p->pPrior){
107329 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
107330 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
107331 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
107332 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
107333 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
107334 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
107335 pNew->op = p->op;
107336 pNew->pNext = pNext;
107337 pNew->pPrior = 0;
107338 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
107339 pNew->iLimit = 0;
107340 pNew->iOffset = 0;
107341 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
107342 pNew->addrOpenEphm[0] = -1;
107343 pNew->addrOpenEphm[1] = -1;
107344 pNew->nSelectRow = p->nSelectRow;
107345 pNew->pWith = sqlite3WithDup(db, p->pWith);
107347 pNew->pWin = 0;
107348 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
107349 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
107351 pNew->selId = p->selId;
107352 if( db->mallocFailed ){
107356 pNew->pNext = 0;
107361 pp = &pNew->pPrior;
107382 ** Reason: This routine assumes that the number of slots in pList->a[]
107387 ** NULL is returned. If non-NULL is returned, then it is guaranteed
107398 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList)+sizeof(pList->a[0])*4 );
107403 pList->nAlloc = 4;
107404 pList->nExpr = 1;
107405 pItem = &pList->a[0];
107407 pItem->pExpr = pExpr;
107417 pList->nAlloc *= 2;
107419 sizeof(*pList)+(pList->nAlloc-1)*sizeof(pList->a[0]));
107427 pItem = &pList->a[pList->nExpr++];
107429 pItem->pExpr = pExpr;
107439 return sqlite3ExprListAppendNew(pParse->db,pExpr);
107441 if( pList->nAlloc<pList->nExpr+1 ){
107442 return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr);
107444 pItem = &pList->a[pList->nExpr++];
107446 pItem->pExpr = pExpr;
107467 sqlite3 *db = pParse->db;
107470 int iFirst = pList ? pList->nExpr : 0;
107481 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
107483 pColumns->nId, n);
107487 for(i=0; i<pColumns->nId; i++){
107488 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId);
107489 assert( pSubExpr!=0 || db->mallocFailed );
107493 assert( pList->nExpr==iFirst+i+1 );
107494 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
107495 pColumns->a[i].zName = 0;
107499 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
107500 Expr *pFirst = pList->a[iFirst].pExpr;
107502 assert( pFirst->op==TK_SELECT_COLUMN );
107506 pFirst->pRight = pExpr;
107511 pFirst->iTable = pColumns->nId;
107526 assert( p->nExpr>0 );
107538 pItem = &p->a[p->nExpr-1];
107539 assert( pItem->fg.bNulls==0 );
107543 pItem->fg.sortFlags = (u8)iSortOrder;
107546 pItem->fg.bNulls = 1;
107548 pItem->fg.sortFlags |= KEYINFO_ORDER_BIGNULL;
107558 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
107567 assert( pList!=0 || pParse->db->mallocFailed!=0 );
107568 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
107571 assert( pList->nExpr>0 );
107572 pItem = &pList->a[pList->nExpr-1];
107573 assert( pItem->zEName==0 );
107574 assert( pItem->fg.eEName==ENAME_NAME );
107575 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
107577 /* If dequote==0, then pName->z does not point to part of a DDL
107579 ** to the token-map. */
107580 sqlite3Dequote(pItem->zEName);
107582 sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName);
107593 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
107602 sqlite3 *db = pParse->db;
107603 assert( pList!=0 || db->mallocFailed!=0 );
107605 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
107606 assert( pList->nExpr>0 );
107607 if( pItem->zEName==0 ){
107608 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
107609 pItem->fg.eEName = ENAME_SPAN;
107623 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
107624 testcase( pEList && pEList->nExpr==mx );
107625 testcase( pEList && pEList->nExpr==mx+1 );
107626 if( pEList && pEList->nExpr>mx ){
107635 int i = pList->nExpr;
107636 struct ExprList_item *pItem = pList->a;
107637 assert( pList->nExpr>0 );
107640 sqlite3ExprDelete(db, pItem->pExpr);
107641 if( pItem->zEName ) sqlite3DbNNFreeNN(db, pItem->zEName);
107643 }while( --i>0 );
107651 ** Return the bitwise-OR of all Expr.flags fields in the given
107658 for(i=0; i<pList->nExpr; i++){
107659 Expr *pExpr = pList->a[i].pExpr;
107661 m |= pExpr->flags;
107667 ** This is a SELECT-node callback for the expression walker that
107669 ** pWalker->eCode to zero and abort.
107675 pWalker->eCode = 0;
107696 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
107701 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
107703 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
107705 pExpr->op = TK_TRUEFALSE;
107718 assert( pExpr->op==TK_TRUEFALSE );
107720 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
107721 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
107722 return pExpr->u.zToken[4]==0;
107740 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
107741 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
107742 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
107744 pExpr = pExpr->op==TK_AND ? pRight : pLeft;
107746 pExpr = pExpr->op==TK_AND ? pLeft : pRight;
107761 ** sqlite3ExprIsConstant() pWalker->eCode==1
107762 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
107763 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
107764 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
107781 /* If pWalker->eCode is 2 then any term of the expression that comes from
107784 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_OuterON) ){
107785 pWalker->eCode = 0;
107789 switch( pExpr->op ){
107791 ** and either pWalker->eCode==4 or 5 or the function has the
107794 if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
107797 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
107800 pWalker->eCode = 0;
107813 testcase( pExpr->op==TK_ID );
107814 testcase( pExpr->op==TK_COLUMN );
107815 testcase( pExpr->op==TK_AGG_FUNCTION );
107816 testcase( pExpr->op==TK_AGG_COLUMN );
107817 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
107820 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
107827 testcase( pExpr->op==TK_REGISTER );
107828 testcase( pExpr->op==TK_IF_NULL_ROW );
107829 testcase( pExpr->op==TK_DOT );
107830 pWalker->eCode = 0;
107833 if( pWalker->eCode==5 ){
107837 pExpr->op = TK_NULL;
107838 }else if( pWalker->eCode==4 ){
107841 pWalker->eCode = 0;
107846 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
107847 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
107865 ** Walk an expression tree. Return non-zero if the expression is constant
107868 ** For the purposes of this function, a double-quoted string (ex: "abc")
107869 ** is considered a variable but a single-quoted string (ex: 'abc') is
107877 ** Walk an expression tree. Return non-zero if
107886 ** can be added to the pParse->pConstExpr list and evaluated once when
107894 ** Walk an expression tree. Return non-zero if the expression is constant
107896 ** expression must not refer to any non-deterministic function nor any
107904 ** Check pExpr to see if it is an invariant constraint on data source pSrc.
107911 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
107913 ** (2) pExpr cannot use subqueries or non-deterministic functions.
107927 if( pSrc->fg.jointype & JT_LTORJ ){
107930 if( pSrc->fg.jointype & JT_LEFT ){
107932 if( pExpr->w.iJoin!=pSrc->iCursor ) return 0; /* rule (4b) */
107936 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor); /* rules (1), (2) */
107944 ExprList *pGroupBy = pWalker->u.pGroupBy;
107949 for(i=0; i<pGroupBy->nExpr; i++){
107950 Expr *p = pGroupBy->a[i].pExpr;
107951 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
107952 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
107959 /* Check if pExpr is a sub-select. If so, consider it variable. */
107961 pWalker->eCode = 0;
107969 ** Walk the expression tree passed as the first argument. Return non-zero
107977 ** assumes that no other collating sequence will have a finer-grained
108000 ** in a CREATE TABLE statement. Return non-zero if the expression is
108001 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
108015 ** For the purposes of this function, a double-quoted string (ex: "abc")
108016 ** is considered a variable but a single-quoted string (ex: 'abc') is
108044 ** to fit in a 32-bit integer, return 1 and put the value of the integer
108046 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
108052 /* If an expression is an integer literal that fits in a signed 32-bit
108054 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
108055 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
108057 if( p->flags & EP_IntValue ){
108058 *pValue = p->u.iValue;
108061 switch( p->op ){
108063 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
108068 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
108070 *pValue = -v;
108097 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
108098 p = p->pLeft;
108101 op = p->op;
108102 if( op==TK_REGISTER ) op = p->op2;
108112 p->y.pTab==0 || /* Reference to column of index on expression */
108113 (p->iColumn>=0
108114 && p->y.pTab->aCol!=0 /* Possible due to prior error */
108115 && p->y.pTab->aCol[p->iColumn].notNull==0);
108135 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
108136 if( p->op==TK_UMINUS ) unaryMinus = 1;
108137 p = p->pLeft;
108139 op = p->op;
108140 if( op==TK_REGISTER ) op = p->op2;
108155 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
108156 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
108165 ** Return TRUE if the given string is a row-id column name.
108190 p = pX->x.pSelect;
108191 if( p->pPrior ) return 0; /* Not a compound SELECT */
108192 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
108193 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
108194 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
108197 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
108198 if( p->pLimit ) return 0; /* Has no LIMIT clause */
108199 if( p->pWhere ) return 0; /* Has no WHERE clause */
108200 pSrc = p->pSrc;
108202 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
108203 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
108204 pTab = pSrc->a[0].pTab;
108208 pEList = p->pEList;
108211 for(i=0; i<pEList->nExpr; i++){
108212 Expr *pRes = pEList->a[i].pExpr;
108213 if( pRes->op!=TK_COLUMN ) return 0;
108214 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
108222 ** Generate code that checks the left-most column of index table iCur to see if
108224 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
108242 ** right-hand side. Return TRUE if that list is constant.
108248 pLHS = pIn->pLeft;
108249 pIn->pLeft = 0;
108251 pIn->pLeft = pLHS;
108261 ** The job of this routine is to find or create a b-tree object that can
108265 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
108268 ** The returned value of this function indicates the b-tree type, as follows:
108270 ** IN_INDEX_ROWID - The cursor was opened on a database table.
108271 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
108272 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
108273 ** IN_INDEX_EPH - The cursor was opened on a specially created and
108275 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
108278 ** An existing b-tree might be used if the RHS expression pX is a simple
108285 ** pX->iTable made to point to the ephemeral table instead of an
108288 ** will be set on pX and the pX->y.sub fields will be set to show where
108297 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
108298 ** through the set members) then the b-tree must not contain duplicates.
108300 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
108303 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
108306 ** index can be found with the specified <columns> as its left-most.
108310 ** routine might decide that creating an ephemeral b-tree for membership
108315 ** When the b-tree is being used for membership tests, the calling function
108324 ** the value in that register will be NULL if the b-tree contains one or more
108325 ** NULL values, and it will be some non-NULL value if the b-tree contains no
108354 assert( pX->op==TK_IN );
108356 iTab = pParse->nTab++;
108365 ExprList *pEList = pX->x.pSelect->pEList;
108366 for(i=0; i<pEList->nExpr; i++){
108367 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
108369 if( i==pEList->nExpr ){
108377 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
108378 sqlite3 *db = pParse->db; /* Database connection */
108381 ExprList *pEList = p->pEList;
108382 int nExpr = pEList->nExpr;
108384 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
108385 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
108386 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
108387 pTab = p->pSrc->a[0].pTab;
108390 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
108393 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
108396 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
108404 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
108416 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
108417 int iCol = pEList->a[i].pExpr->iColumn;
108439 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
108442 if( pIdx->nColumn<nExpr ) continue;
108443 if( pIdx->pPartIdxWhere!=0 ) continue;
108444 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
108446 testcase( pIdx->nColumn==BMS-2 );
108447 testcase( pIdx->nColumn==BMS-1 );
108448 if( pIdx->nColumn>=BMS-1 ) continue;
108450 if( pIdx->nKeyCol>nExpr
108451 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
108459 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
108460 Expr *pRhs = pEList->a[i].pExpr;
108464 assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
108466 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
108467 assert( pIdx->azColl[j] );
108468 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
108480 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
108481 if( colUsed==(MASKBIT(nExpr)-1) ){
108485 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
108486 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
108488 VdbeComment((v, "%s", pIdx->zName));
108490 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
108494 i64 mask = (1<<nExpr)-1;
108498 *prRhsHasNull = ++pParse->nMem;
108520 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
108522 pParse->nTab--; /* Back out the allocation of the unused cursor */
108523 iTab = -1; /* Cursor is not allocated */
108528 /* Could not find an existing table or index to use as the RHS b-tree.
108531 u32 savedNQueryLoop = pParse->nQueryLoop;
108535 pParse->nQueryLoop = 0;
108537 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
108539 assert( pX->op==TK_IN );
108544 pParse->nQueryLoop = savedNQueryLoop;
108549 n = sqlite3ExprVectorSize(pX->pLeft);
108560 ** function allocates and returns a nul-terminated string containing
108567 Expr *pLeft = pExpr->pLeft;
108569 Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0;
108572 assert( pExpr->op==TK_IN );
108573 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
108580 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
108596 ** "sub-select returns N columns - expected M"
108599 if( pParse->nErr==0 ){
108600 const char *zFmt = "sub-select returns %d columns - expected %d";
108608 ** it is not permitted. If pExpr is a sub-select vector, this routine
108611 ** "sub-select returns N columns - expected 1"
108620 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
108634 ** x IN (4,5,11) -- IN operator with list on right-hand side
108635 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
108639 ** table is computed, the cursor number is also stored in pExpr->iTable,
108663 v = pParse->pVdbe;
108669 ** * The right-hand side is a correlated subquery
108670 ** * The right-hand side is an expression list containing variables
108676 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
108685 pExpr->x.pSelect->selId));
108688 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
108689 pExpr->y.sub.iAddr);
108690 assert( iTab!=pExpr->iTable );
108691 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
108700 pExpr->y.sub.regReturn = ++pParse->nMem;
108701 pExpr->y.sub.iAddr =
108702 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
108708 pLeft = pExpr->pLeft;
108714 pExpr->iTable = iTab;
108715 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
108718 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
108723 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
108731 Select *pSelect = pExpr->x.pSelect;
108732 ExprList *pEList = pSelect->pEList;
108735 addrOnce?"":"CORRELATED ", pSelect->selId
108739 if( ALWAYS(pEList->nExpr==nVal) ){
108746 pSelect->iLimit = 0;
108747 testcase( pSelect->selFlags & SF_Distinct );
108749 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
108750 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
108751 sqlite3SelectDelete(pParse->db, pCopy);
108752 sqlite3DbFree(pParse->db, dest.zAffSdst);
108759 assert( pEList->nExpr>0 );
108763 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
108764 pParse, p, pEList->a[i].pExpr
108768 }else if( ALWAYS(pExpr->x.pList!=0) ){
108778 ExprList *pList = pExpr->x.pList;
108789 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
108795 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
108796 Expr *pE2 = pItem->pExpr;
108800 ** this code only executes once. Because for a non-constant
108804 sqlite3VdbeChangeToNoop(v, addrOnce-1);
108826 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
108827 || pParse->nErr );
108828 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
108829 pExpr->y.sub.iAddr, 1);
108840 ** (SELECT a FROM b) -- subquery
108841 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
108845 ** Return the register that holds the result. For a multi-column SELECT,
108847 ** return value is the register of the left-most result column.
108859 Vdbe *v = pParse->pVdbe;
108861 if( pParse->nErr ) return 0;
108862 testcase( pExpr->op==TK_EXISTS );
108863 testcase( pExpr->op==TK_SELECT );
108864 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
108866 pSel = pExpr->x.pSelect;
108871 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
108873 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
108874 pExpr->y.sub.iAddr);
108875 return pExpr->iTable;
108882 pExpr->y.sub.regReturn = ++pParse->nMem;
108883 pExpr->y.sub.iAddr =
108884 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
108889 ** * The right-hand side is a correlated subquery
108890 ** * The right-hand side is an expression list containing variables
108911 addrOnce?"":"CORRELATED ", pSel->selId));
108912 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
108913 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
108914 pParse->nMem += nReg;
108915 if( pExpr->op==TK_SELECT ){
108919 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
108926 if( pSel->pLimit ){
108927 /* The subquery already has a limit. If the pre-existing limit is X
108929 sqlite3 *db = pParse->db;
108932 pLimit->affExpr = SQLITE_AFF_NUMERIC;
108934 sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
108936 sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft);
108937 pSel->pLimit->pLeft = pLimit;
108939 /* If there is no pre-existing limit add a limit of 1 */
108940 pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
108941 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
108943 pSel->iLimit = 0;
108945 pExpr->op2 = pExpr->op;
108946 pExpr->op = TK_ERROR;
108949 pExpr->iTable = rReg = dest.iSDParm;
108957 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
108958 || pParse->nErr );
108959 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
108960 pExpr->y.sub.iAddr, 1);
108970 ** sub-select on the RHS of the IN() operator has the same number of
108972 ** a sub-query, that the LHS is a vector of size 1.
108975 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
108976 if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){
108977 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
108978 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
108982 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
108996 ** The left-hand side (LHS) is a scalar or vector expression. The
108997 ** right-hand side (RHS) is an array of zero or more scalar values, or a
109012 ** See the separate in-operator.md documentation file in the canonical
109013 ** SQLite source tree for additional information.
109036 int addrTop; /* Top of the step-6 loop */
109038 u8 okConstFactor = pParse->okConstFactor;
109041 pLeft = pExpr->pLeft;
109044 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
109046 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
109048 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
109054 v = pParse->pVdbe;
109062 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
109067 ** nVector-1. */
109087 assert( pParse->okConstFactor==okConstFactor );
109088 pParse->okConstFactor = 0;
109090 pParse->okConstFactor = okConstFactor;
109107 ** This is step (1) in the in-operator.md optimized algorithm.
109117 pList = pExpr->x.pList;
109118 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
109123 for(ii=0; ii<pList->nExpr; ii++){
109124 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
109125 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
109129 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
109133 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
109134 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
109135 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
109136 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
109167 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
109168 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
109175 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
109180 /* In this case, the RHS is the ROWID of table b-tree and so we also
109181 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
109199 /* Step 4. If the RHS is known to be non-NULL and we did not find
109259 sqlite3DbFree(pParse->db, aiMap);
109260 sqlite3DbFree(pParse->db, zAff);
109267 ** value described by z[0..n-1] into register iMem.
109269 ** The z[] string will probably not be zero-terminated. But the
109278 if( negateFlag ) value = -value;
109287 ** text z[0..n-1] into register iMem.
109289 ** Expr.u.zToken is always UTF8 and zero-terminated.
109292 Vdbe *v = pParse->pVdbe;
109293 if( pExpr->flags & EP_IntValue ){
109294 int i = pExpr->u.iValue;
109296 if( negFlag ) i = -i;
109301 const char *z = pExpr->u.zToken;
109306 sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr);
109311 negFlag?"-":"",pExpr);
109319 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
109327 ** appropriate for the iIdxCol-th column of index pIdx.
109336 i16 iTabCol = pIdx->aiColumn[iIdxCol];
109338 assert( pIdx->aColExpr );
109339 assert( pIdx->aColExpr->nExpr>iIdxCol );
109340 pParse->iSelfTab = iTabCur + 1;
109341 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
109342 pParse->iSelfTab = 0;
109344 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
109361 Vdbe *v = pParse->pVdbe;
109363 assert( pParse->iSelfTab!=0 );
109364 if( pParse->iSelfTab>0 ){
109365 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
109370 if( pCol->affinity>=SQLITE_AFF_TEXT ){
109371 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
109378 ** Generate code to extract the value of the iCol-th column of a table.
109390 if( iCol<0 || iCol==pTab->iPKey ){
109392 VdbeComment((v, "%s.rowid", pTab->zName));
109400 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
109402 if( pCol->colFlags & COLFLAG_BUSY ){
109404 pCol->zCnName);
109406 int savedSelfTab = pParse->iSelfTab;
109407 pCol->colFlags |= COLFLAG_BUSY;
109408 pParse->iSelfTab = iTabCur+1;
109410 pParse->iSelfTab = savedSelfTab;
109411 pCol->colFlags &= ~COLFLAG_BUSY;
109430 ** Generate code that will extract the iColumn-th column from
109444 assert( pParse->pVdbe!=0 );
109445 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
109447 VdbeOp *pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
109448 if( pOp->opcode==OP_Column ) pOp->p5 = p5;
109454 ** Generate code to move content from registers iFrom...iFrom+nReg-1
109455 ** over to iTo..iTo+nReg-1.
109458 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
109469 p->op2 = p->op;
109470 p->op = TK_REGISTER;
109471 p->iTable = iReg;
109492 if( p->op==TK_SELECT ){
109500 iResult = pParse->nMem+1;
109501 pParse->nMem += nResult;
109504 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
109512 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
109516 if( sqlite3VdbeGetLastOp(v)->opcode==OP_Copy ){
109523 ** in-line rather than by using the usual callbacks.
109532 Vdbe *v = pParse->pVdbe;
109535 nFarg = pFarg->nExpr;
109536 assert( nFarg>0 ); /* All in-line functions have at least one argument */
109539 /* Attempt a direct implementation of the built-in COALESCE() and
109541 ** arguments past the first non-NULL argument.
109546 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
109550 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
109565 Expr *pArg = pFarg->a[0].pExpr;
109566 if( pArg->op==TK_COLUMN && pArg->iTable>=0 ){
109567 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
109575 /* The UNLIKELY() function is a no-op. The result is the value
109579 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
109584 ** Test-only SQL functions that are only usable if enabled
109592 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
109601 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
109610 pA1 = pFarg->a[1].pExpr;
109611 if( pA1->op==TK_COLUMN ){
109613 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable),
109629 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
109631 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
109640 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxExpr.
109652 for(p=pParse->pIdxExpr; p; p=p->pIENext){
109653 int iDataCur = p->iDataCur;
109655 if( pParse->iSelfTab ){
109656 if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
109657 iDataCur = -1;
109659 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue;
109660 v = pParse->pVdbe;
109662 if( p->bMaybeNullRow ){
109667 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
109669 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
109670 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
109672 p = pParse->pIdxExpr;
109673 pParse->pIdxExpr = 0;
109675 pParse->pIdxExpr = p;
109678 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
109679 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
109683 return -1; /* Not found */
109699 Vdbe *v = pParse->pVdbe; /* The VM under construction */
109702 int regFree1 = 0; /* If non-zero free this temporary register */
109703 int regFree2 = 0; /* If non-zero free this temporary register */
109708 assert( target>0 && target<=pParse->nMem );
109714 }else if( pParse->pIdxExpr!=0
109721 op = pExpr->op;
109725 AggInfo *pAggInfo = pExpr->pAggInfo;
109728 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
109729 pCol = &pAggInfo->aCol[pExpr->iAgg];
109730 if( !pAggInfo->directMode ){
109731 assert( pCol->iMem>0 );
109732 return pCol->iMem;
109733 }else if( pAggInfo->useSortingIdx ){
109734 Table *pTab = pCol->pTab;
109735 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
109736 pCol->iSorterColumn, target);
109737 if( pCol->iColumn<0 ){
109738 VdbeComment((v,"%s.rowid",pTab->zName));
109741 pTab->zName, pTab->aCol[pCol->iColumn].zCnName));
109742 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
109752 int iTab = pExpr->iTable;
109756 ** constraints, and that constant is coded by the pExpr->pLeft
109762 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
109764 assert( pExpr->y.pTab!=0 );
109765 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
109771 &zAff[(aff-'B')*2], P4_STATIC);
109776 if( pParse->iSelfTab<0 ){
109780 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
109786 int iCol = pExpr->iColumn;
109788 pTab = pExpr->y.pTab;
109791 assert( iCol<pTab->nCol );
109793 return -1-pParse->iSelfTab;
109795 pCol = pTab->aCol + iCol;
109797 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
109799 if( pCol->colFlags & COLFLAG_GENERATED ){
109800 if( pCol->colFlags & COLFLAG_BUSY ){
109802 pCol->zCnName);
109805 pCol->colFlags |= COLFLAG_BUSY;
109806 if( pCol->colFlags & COLFLAG_NOTAVAIL ){
109809 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
109813 if( pCol->affinity==SQLITE_AFF_REAL ){
109823 iTab = pParse->iSelfTab - 1;
109827 assert( pExpr->y.pTab!=0 );
109828 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
109829 pExpr->iColumn, iTab, target,
109830 pExpr->op2);
109844 codeReal(v, pExpr->u.zToken, 0, target);
109850 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
109858 assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed );
109868 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
109869 assert( pExpr->u.zToken[1]=='\'' );
109870 z = &pExpr->u.zToken[2];
109871 n = sqlite3Strlen30(z) - 1;
109880 assert( pExpr->u.zToken!=0 );
109881 assert( pExpr->u.zToken[0]!=0 );
109882 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
109883 if( pExpr->u.zToken[1]!=0 ){
109884 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
109885 assert( pExpr->u.zToken[0]=='?' || (z && !strcmp(pExpr->u.zToken, z)) );
109886 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
109892 return pExpr->iTable;
109897 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
109904 sqlite3AffinityType(pExpr->u.zToken, 0));
109912 /* fall-through */
109919 Expr *pLeft = pExpr->pLeft;
109924 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
109926 codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,
109968 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
109969 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
109976 Expr *pLeft = pExpr->pLeft;
109978 if( pLeft->op==TK_INTEGER ){
109982 }else if( pLeft->op==TK_FLOAT ){
109984 codeReal(v, pLeft->u.zToken, 1, target);
109993 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
110003 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
110011 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
110013 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
110014 bNormal = pExpr->op2==TK_IS;
110026 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
110036 AggInfo *pInfo = pExpr->pAggInfo;
110038 || NEVER(pExpr->iAgg<0)
110039 || NEVER(pExpr->iAgg>=pInfo->nFunc)
110044 return pInfo->aFunc[pExpr->iAgg].iMem;
110055 sqlite3 *db = pParse->db; /* The database connection */
110061 return pExpr->y.pWin->regResult;
110068 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
110072 pFarg = pExpr->x.pList;
110073 nFarg = pFarg ? pFarg->nExpr : 0;
110075 zId = pExpr->u.zToken;
110078 if( pDef==0 && pParse->explain ){
110082 if( pDef==0 || pDef->xFinalize!=0 ){
110086 if( pDef->funcFlags & SQLITE_FUNC_INLINE ){
110087 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
110088 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
110090 SQLITE_PTR_TO_INT(pDef->pUserData), target);
110091 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
110096 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
110100 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
110101 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
110106 r1 = pParse->nMem+1;
110107 pParse->nMem += nFarg;
110117 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
110120 assert( pFarg->a[0].pExpr!=0 );
110121 exprOp = pFarg->a[0].pExpr->op;
110125 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
110126 pFarg->a[0].pExpr->op2 =
110127 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
110150 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
110152 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
110155 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
110156 if( !pColl ) pColl = db->pDfltColl;
110160 pDef, pExpr->op2);
110176 if( pParse->db->mallocFailed ){
110180 && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1
110190 Expr *pLeft = pExpr->pLeft;
110191 if( pLeft->iTable==0 || pParse->withinRJSubrtn > pLeft->op2 ){
110192 pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft);
110193 pLeft->op2 = pParse->withinRJSubrtn;
110195 assert( pLeft->op==TK_SELECT || pLeft->op==TK_ERROR );
110197 if( pExpr->iTable!=n ){
110199 pExpr->iTable, n);
110201 return pLeft->iTable + pExpr->iColumn;
110224 ** X is stored in pExpr->pLeft.
110225 ** Y is stored in pExpr->pList->a[0].pExpr.
110226 ** Z is stored in pExpr->pList->a[1].pExpr.
110234 && ALWAYS(pExpr->pLeft)
110235 && pExpr->pLeft->op==TK_FUNCTION
110237 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
110245 pExpr = pExpr->pLeft;
110246 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */
110251 pExpr = pExpr->pLeft;
110252 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
110257 ** to a column in the new.* or old.* pseudo-tables available to
110259 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
110260 ** is set to the column of the pseudo-table to read, or to -1 to
110265 ** to reference another column of the old.* pseudo-table, where
110267 ** set to (n+1), where n is the number of columns in each pseudo-table.
110268 ** For a reference to any other column in the new.* pseudo-table, p1
110277 ** p1==0 -> old.rowid p1==3 -> new.rowid
110278 ** p1==1 -> old.a p1==4 -> new.a
110279 ** p1==2 -> old.b p1==5 -> new.b
110286 pTab = pExpr->y.pTab;
110287 iCol = pExpr->iColumn;
110288 p1 = pExpr->iTable * (pTab->nCol+1) + 1
110291 assert( pExpr->iTable==0 || pExpr->iTable==1 );
110292 assert( iCol>=-1 && iCol<pTab->nCol );
110293 assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
110294 assert( p1>=0 && p1<(pTab->nCol*2+2) );
110298 (pExpr->iTable ? "new" : "old"),
110299 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName)
110306 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
110308 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
110321 ** that derive from the right-hand table of a LEFT JOIN. The
110322 ** Expr.iTable value is the table number for the right-hand table.
110328 u8 okConstFactor = pParse->okConstFactor;
110329 AggInfo *pAggInfo = pExpr->pAggInfo;
110331 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
110332 if( !pAggInfo->directMode ){
110333 inReg = pAggInfo->aCol[pExpr->iAgg].iMem;
110336 if( pExpr->pAggInfo->useSortingIdx ){
110337 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
110338 pAggInfo->aCol[pExpr->iAgg].iSorterColumn,
110344 addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
110347 ** really constant because they originate from the right-hand side
110349 pParse->okConstFactor = 0;
110350 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
110351 pParse->okConstFactor = okConstFactor;
110368 ** X (if it exists) is in pExpr->pLeft.
110369 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
110372 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
110389 sqlite3 *db = pParse->db;
110391 assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 );
110392 assert(pExpr->x.pList->nExpr > 0);
110393 pEList = pExpr->x.pList;
110394 aListelem = pEList->a;
110395 nExpr = pEList->nExpr;
110397 if( (pX = pExpr->pLeft)!=0 ){
110399 if( db->mallocFailed ){
110403 testcase( pX->op==TK_COLUMN );
110411 ** The value in regFree1 might get SCopy-ed into the file result.
110416 for(i=0; i<nExpr-1; i=i+2){
110424 testcase( pTest->op==TK_COLUMN );
110426 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
110432 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
110443 assert( pExpr->affExpr==OE_Rollback
110444 || pExpr->affExpr==OE_Abort
110445 || pExpr->affExpr==OE_Fail
110446 || pExpr->affExpr==OE_Ignore
110448 if( !pParse->pTriggerTab && !pParse->nested ){
110450 "RAISE() may only be used within a trigger-program");
110453 if( pExpr->affExpr==OE_Abort ){
110457 if( pExpr->affExpr==OE_Ignore ){
110459 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
110463 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
110464 pExpr->affExpr, pExpr->u.zToken, 0, 0);
110500 p = pParse->pConstExpr;
110504 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
110505 if( pItem->fg.reusable
110506 && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0
110508 return pItem->u.iConstExprReg;
110512 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
110514 Vdbe *v = pParse->pVdbe;
110518 pParse->okConstFactor = 0;
110519 if( !pParse->db->mallocFailed ){
110520 if( regDest<0 ) regDest = ++pParse->nMem;
110523 pParse->okConstFactor = 1;
110524 sqlite3ExprDelete(pParse->db, pExpr);
110529 struct ExprList_item *pItem = &p->a[p->nExpr-1];
110530 pItem->fg.reusable = regDest<0;
110531 if( regDest<0 ) regDest = ++pParse->nMem;
110532 pItem->u.iConstExprReg = regDest;
110534 pParse->pConstExpr = p;
110557 && pExpr->op!=TK_REGISTER
110561 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
110584 assert( target>0 && target<=pParse->nMem );
110585 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
110586 if( pParse->pVdbe==0 ) return;
110595 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
110605 sqlite3 *db = pParse->db;
110607 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
110618 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
110630 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
110649 int srcReg, /* Source registers if SQLITE_ECEL_REF */
110655 Vdbe *v = pParse->pVdbe;
110658 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
110659 n = pList->nExpr;
110661 for(pItem=pList->a, i=0; i<n; i++, pItem++){
110662 Expr *pExpr = pItem->pExpr;
110664 if( pItem->fg.bSorterRef ){
110665 i--;
110666 n--;
110669 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
110671 i--;
110672 n--;
110674 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
110685 && (pOp=sqlite3VdbeGetLastOp(v))->opcode==OP_Copy
110686 && pOp->p1+pOp->p3+1==inReg
110687 && pOp->p2+pOp->p3+1==target+i
110688 && pOp->p5==0 /* The do-not-merge flag must be clear */
110690 pOp->p3++;
110732 sqlite3 *db = pParse->db;
110739 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
110740 if( db->mallocFailed==0 ){
110746 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
110749 compRight.pRight = pExpr->x.pList->a[1].pExpr;
110759 pDel->flags |= EP_OuterON;
110793 Vdbe *v = pParse->pVdbe;
110803 op = pExpr->op;
110813 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
110815 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
110819 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
110820 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
110826 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
110833 isNot = pExpr->op2==TK_ISNOT;
110834 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
110838 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
110841 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
110859 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
110861 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
110862 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
110863 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
110883 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
110911 /* No-op */
110936 Vdbe *v = pParse->pVdbe;
110947 /* The value of pExpr->op and op are related as follows:
110949 ** pExpr->op op
110950 ** --------- ----------
110960 ** For other values of pExpr->op, op is undefined and unused.
110965 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
110969 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
110970 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
110971 assert( pExpr->op!=TK_NE || op==OP_Eq );
110972 assert( pExpr->op!=TK_EQ || op==OP_Ne );
110973 assert( pExpr->op!=TK_LT || op==OP_Ge );
110974 assert( pExpr->op!=TK_LE || op==OP_Gt );
110975 assert( pExpr->op!=TK_GT || op==OP_Le );
110976 assert( pExpr->op!=TK_GE || op==OP_Lt );
110978 switch( pExpr->op ){
110984 }else if( pExpr->op==TK_AND ){
110986 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
110987 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
110991 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
110993 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
111000 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
111007 isNot = pExpr->op2==TK_ISNOT;
111008 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
111013 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
111018 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
111025 testcase( pExpr->op==TK_IS );
111026 testcase( pExpr->op==TK_ISNOT );
111027 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
111036 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
111038 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
111039 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
111040 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
111058 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
111088 /* no-op */
111109 sqlite3 *db = pParse->db;
111111 if( db->mallocFailed==0 ){
111121 ** If pExpr is a simple SQL value - an integer, real, string, blob
111122 ** or NULL value - then the VDBE currently being prepared is configured
111123 ** to re-prepare each time a new value is bound to variable pVar.
111126 ** same as that currently bound to variable pVar, non-zero is returned.
111139 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
111141 iVar = pVar->iColumn;
111142 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
111143 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
111146 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
111161 ** other than the top-level COLLATE operator.
111163 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
111175 ** this routine is used, it does not hurt to get an extra 2 - that
111180 ** pParse->pReprepare can be matched against literals in pB. The
111181 ** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
111196 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
111199 combinedFlags = pA->flags | pB->flags;
111201 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
111206 if( pA->op!=pB->op || pA->op==TK_RAISE ){
111207 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
111210 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
111213 if( pA->op==TK_AGG_COLUMN && pB->op==TK_COLUMN
111214 && pB->iTable<0 && pA->iTable==iTab
111223 if( pA->u.zToken ){
111224 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
111225 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
111227 assert( pA->op==pB->op );
111232 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
111237 }else if( pA->op==TK_NULL ){
111239 }else if( pA->op==TK_COLLATE ){
111240 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
111242 if( pB->u.zToken!=0
111243 && pA->op!=TK_COLUMN
111244 && pA->op!=TK_AGG_COLUMN
111245 && strcmp(pA->u.zToken,pB->u.zToken)!=0
111250 if( (pA->flags & (EP_Distinct|EP_Commuted))
111251 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
111255 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
111256 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
111257 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
111258 if( pA->op!=TK_STRING
111259 && pA->op!=TK_TRUEFALSE
111262 if( pA->iColumn!=pB->iColumn ) return 2;
111263 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
111264 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
111277 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
111280 ** This routine might return non-zero for equivalent ExprLists. The
111286 ** always differs from a non-NULL pointer.
111292 if( pA->nExpr!=pB->nExpr ) return 1;
111293 for(i=0; i<pA->nExpr; i++){
111295 Expr *pExprA = pA->a[i].pExpr;
111296 Expr *pExprB = pB->a[i].pExpr;
111297 if( pA->a[i].fg.sortFlags!=pB->a[i].fg.sortFlags ) return 1;
111304 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
111315 ** Return non-zero if Expr p can only be true if pNN is not NULL.
111317 ** Or if seenNot is true, return non-zero if Expr p can only be
111318 ** non-NULL if pNN is not NULL
111325 int seenNot /* Return true only if p can be any non-NULL value */
111330 return pNN->op!=TK_NULL;
111332 switch( p->op ){
111335 assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) );
111336 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
111341 pList = p->x.pList;
111343 assert( pList->nExpr==2 );
111345 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
111346 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
111350 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
111370 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
111377 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
111381 if( p->op2!=TK_IS ) return 0;
111382 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
111386 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
111409 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
111426 if( pE2->op==TK_OR
111427 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
111428 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
111432 if( pE2->op==TK_NOTNULL
111433 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
111442 ** If the expression node requires that the table at pWalker->iCur
111443 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
111446 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
111447 ** (never setting pWalker->eCode) is a harmless missed optimization.
111450 testcase( pExpr->op==TK_AGG_COLUMN );
111451 testcase( pExpr->op==TK_AGG_FUNCTION );
111453 switch( pExpr->op ){
111464 testcase( pExpr->op==TK_ISNOT );
111465 testcase( pExpr->op==TK_ISNULL );
111466 testcase( pExpr->op==TK_NOTNULL );
111467 testcase( pExpr->op==TK_IS );
111468 testcase( pExpr->op==TK_OR );
111469 testcase( pExpr->op==TK_VECTOR );
111470 testcase( pExpr->op==TK_CASE );
111471 testcase( pExpr->op==TK_IN );
111472 testcase( pExpr->op==TK_FUNCTION );
111473 testcase( pExpr->op==TK_TRUTH );
111476 if( pWalker->u.iCur==pExpr->iTable ){
111477 pWalker->eCode = 1;
111483 if( pWalker->eCode==0 ){
111484 sqlite3WalkExpr(pWalker, pExpr->pLeft);
111485 if( pWalker->eCode ){
111486 pWalker->eCode = 0;
111487 sqlite3WalkExpr(pWalker, pExpr->pRight);
111493 if( sqlite3WalkExpr(pWalker, pExpr->pLeft)==WRC_Abort ){
111494 assert( pWalker->eCode );
111508 Expr *pLeft = pExpr->pLeft;
111509 Expr *pRight = pExpr->pRight;
111510 testcase( pExpr->op==TK_EQ );
111511 testcase( pExpr->op==TK_NE );
111512 testcase( pExpr->op==TK_LT );
111513 testcase( pExpr->op==TK_LE );
111514 testcase( pExpr->op==TK_GT );
111515 testcase( pExpr->op==TK_GE );
111518 assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) );
111519 assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) );
111520 if( (pLeft->op==TK_COLUMN
111521 && ALWAYS(pLeft->y.pTab!=0)
111522 && IsVirtual(pLeft->y.pTab))
111523 || (pRight->op==TK_COLUMN
111524 && ALWAYS(pRight->y.pTab!=0)
111525 && IsVirtual(pRight->y.pTab))
111537 ** Return true (non-zero) if expression p can only be true if at least
111538 ** one column of table iTab is non-null. In other words, return true
111555 ** be non-NULL, then the LEFT JOIN can be safely converted into an
111562 if( p->op==TK_NOTNULL ){
111563 p = p->pLeft;
111565 while( p->op==TK_AND ){
111566 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab) ) return 1;
111567 p = p->pRight;
111593 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
111594 ** pWalker->u.pIdxCover->pIdx.
111597 if( pExpr->op==TK_COLUMN
111598 && pExpr->iTable==pWalker->u.pIdxCover->iCur
111599 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
111601 pWalker->eCode = 1;
111653 struct RefSrcList *p = pWalker->u.pRefSrcList;
111654 SrcList *pSrc = pSelect->pSrc;
111657 if( pSrc->nSrc==0 ) return WRC_Continue;
111658 j = p->nExclude;
111659 p->nExclude += pSrc->nSrc;
111660 piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int));
111662 p->nExclude = 0;
111665 p->aiExclude = piNew;
111667 for(i=0; i<pSrc->nSrc; i++, j++){
111668 p->aiExclude[j] = pSrc->a[i].iCursor;
111673 struct RefSrcList *p = pWalker->u.pRefSrcList;
111674 SrcList *pSrc = pSelect->pSrc;
111675 if( p->nExclude ){
111676 assert( p->nExclude>=pSrc->nSrc );
111677 p->nExclude -= pSrc->nSrc;
111683 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
111686 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
111690 if( pExpr->op==TK_COLUMN
111691 || pExpr->op==TK_AGG_COLUMN
111694 struct RefSrcList *p = pWalker->u.pRefSrcList;
111695 SrcList *pSrc = p->pRef;
111696 int nSrc = pSrc ? pSrc->nSrc : 0;
111698 if( pExpr->iTable==pSrc->a[i].iCursor ){
111699 pWalker->eCode |= 1;
111703 for(i=0; i<p->nExclude && p->aiExclude[i]!=pExpr->iTable; i++){}
111704 if( i>=p->nExclude ){
111705 pWalker->eCode |= 2;
111720 ** -1 pExpr only references no tables at all, or it only
111729 assert( pParse->db!=0 );
111736 x.db = pParse->db;
111738 assert( pExpr->op==TK_AGG_FUNCTION );
111740 sqlite3WalkExprList(&w, pExpr->x.pList);
111743 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
111746 if( x.aiExclude ) sqlite3DbNNFreeNN(pParse->db, x.aiExclude);
111752 return -1;
111764 ** The copy is stored on pParse->pConstExpr with a register number of 0.
111771 && pExpr->pAggInfo!=0
111773 AggInfo *pAggInfo = pExpr->pAggInfo;
111774 int iAgg = pExpr->iAgg;
111775 Parse *pParse = pWalker->pParse;
111776 sqlite3 *db = pParse->db;
111777 if( pExpr->op!=TK_AGG_FUNCTION ){
111778 assert( pExpr->op==TK_AGG_COLUMN || pExpr->op==TK_IF_NULL_ROW );
111779 assert( iAgg>=0 && iAgg<pAggInfo->nColumn );
111780 if( pAggInfo->aCol[iAgg].pCExpr==pExpr ){
111783 pAggInfo->aCol[iAgg].pCExpr = pExpr;
111788 assert( pExpr->op==TK_AGG_FUNCTION );
111789 assert( iAgg>=0 && iAgg<pAggInfo->nFunc );
111790 if( pAggInfo->aFunc[iAgg].pFExpr==pExpr ){
111793 pAggInfo->aFunc[iAgg].pFExpr = pExpr;
111808 pWalker->pParse = pParse;
111809 pWalker->xExprCallback = agginfoPersistExprCb;
111810 pWalker->xSelectCallback = sqlite3SelectWalkNoop;
111814 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
111819 pInfo->aCol = sqlite3ArrayAllocate(
111821 pInfo->aCol,
111822 sizeof(pInfo->aCol[0]),
111823 &pInfo->nColumn,
111830 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
111835 pInfo->aFunc = sqlite3ArrayAllocate(
111837 pInfo->aFunc,
111838 sizeof(pInfo->aFunc[0]),
111839 &pInfo->nFunc,
111852 NameContext *pNC = pWalker->u.pNC;
111853 Parse *pParse = pNC->pParse;
111854 SrcList *pSrcList = pNC->pSrcList;
111855 AggInfo *pAggInfo = pNC->uNC.pAggInfo;
111857 assert( pNC->ncFlags & NC_UAggInfo );
111858 switch( pExpr->op ){
111862 testcase( pExpr->op==TK_AGG_COLUMN );
111863 testcase( pExpr->op==TK_COLUMN );
111864 testcase( pExpr->op==TK_IF_NULL_ROW );
111868 SrcItem *pItem = pSrcList->a;
111869 for(i=0; i<pSrcList->nSrc; i++, pItem++){
111872 if( pExpr->iTable==pItem->iCursor ){
111876 ** Make an entry for the column in pAggInfo->aCol[] if there
111880 pCol = pAggInfo->aCol;
111881 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
111882 if( pCol->iTable==pExpr->iTable
111883 && pCol->iColumn==pExpr->iColumn
111884 && pExpr->op!=TK_IF_NULL_ROW
111889 if( (k>=pAggInfo->nColumn)
111890 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
111892 pCol = &pAggInfo->aCol[k];
111894 pCol->pTab = pExpr->y.pTab;
111895 pCol->iTable = pExpr->iTable;
111896 pCol->iColumn = pExpr->iColumn;
111897 pCol->iMem = ++pParse->nMem;
111898 pCol->iSorterColumn = -1;
111899 pCol->pCExpr = pExpr;
111900 if( pAggInfo->pGroupBy && pExpr->op!=TK_IF_NULL_ROW ){
111902 ExprList *pGB = pAggInfo->pGroupBy;
111903 struct ExprList_item *pTerm = pGB->a;
111904 n = pGB->nExpr;
111906 Expr *pE = pTerm->pExpr;
111907 if( pE->op==TK_COLUMN
111908 && pE->iTable==pExpr->iTable
111909 && pE->iColumn==pExpr->iColumn
111911 pCol->iSorterColumn = j;
111916 if( pCol->iSorterColumn<0 ){
111917 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
111920 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
111923 ** pAggInfo->aCol[] entry.
111926 pExpr->pAggInfo = pAggInfo;
111927 if( pExpr->op==TK_COLUMN ){
111928 pExpr->op = TK_AGG_COLUMN;
111930 pExpr->iAgg = (i16)k;
111932 } /* endif pExpr->iTable==pItem->iCursor */
111938 if( (pNC->ncFlags & NC_InAggFunc)==0
111939 && pWalker->walkerDepth==pExpr->op2
111944 struct AggInfo_func *pItem = pAggInfo->aFunc;
111945 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
111946 if( pItem->pFExpr==pExpr ) break;
111947 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
111951 if( i>=pAggInfo->nFunc ){
111952 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
111954 u8 enc = ENC(pParse->db);
111955 i = addAggInfoFunc(pParse->db, pAggInfo);
111958 pItem = &pAggInfo->aFunc[i];
111959 pItem->pFExpr = pExpr;
111960 pItem->iMem = ++pParse->nMem;
111962 pItem->pFunc = sqlite3FindFunction(pParse->db,
111963 pExpr->u.zToken,
111964 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
111965 if( pExpr->flags & EP_Distinct ){
111966 pItem->iDistinct = pParse->nTab++;
111968 pItem->iDistinct = -1;
111972 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
111976 pExpr->iAgg = (i16)i;
111977 pExpr->pAggInfo = pAggInfo;
111989 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
112004 assert( pNC->pSrcList!=0 );
112018 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
112019 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
112028 if( pParse->nTempReg==0 ){
112029 return ++pParse->nMem;
112031 return pParse->aTempReg[--pParse->nTempReg];
112041 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
112042 pParse->aTempReg[pParse->nTempReg++] = iReg;
112053 i = pParse->iRangeReg;
112054 n = pParse->nRangeReg;
112056 pParse->iRangeReg += nReg;
112057 pParse->nRangeReg -= nReg;
112059 i = pParse->nMem+1;
112060 pParse->nMem += nReg;
112070 if( nReg>pParse->nRangeReg ){
112071 pParse->nRangeReg = nReg;
112072 pParse->iRangeReg = iReg;
112079 ** Always invoke this procedure after coding a subroutine or co-routine
112081 ** the sub/co-routine does not use registers in common with the code that
112082 ** invokes the sub/co-routine.
112085 pParse->nTempReg = 0;
112086 pParse->nRangeReg = 0;
112097 if( pParse->nRangeReg>0
112098 && pParse->iRangeReg+pParse->nRangeReg > iFirst
112099 && pParse->iRangeReg <= iLast
112103 for(i=0; i<pParse->nTempReg; i++){
112104 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
112117 ** The author disclaims copyright to this source code. In place of
112140 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
112145 if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
112147 || (pTab->tabFlags & TF_Eponymous)!=0
112148 || ( (pTab->tabFlags & TF_Shadow)!=0
112149 && sqlite3ReadOnlyShadowTables(pParse->db)
112153 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
112173 pParse->colNamesSet = 1;
112197 ** Generate VM code to replace any double-quoted strings (but not double-quoted
112199 ** database zDb with their single-quoted equivalents. If argument bTemp is
112225 Vdbe *v = pParse->pVdbe;
112228 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5);
112229 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5);
112245 char *zName = 0; /* NULL-terminated version of pName */
112246 sqlite3 *db = pParse->db; /* Database connection */
112247 int nTabName; /* Number of UTF-8 characters in zTabName */
112250 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
112252 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
112253 assert( pSrc->nSrc==1 );
112254 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
112256 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
112258 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
112259 zDb = db->aDb[iDb].zDbSName;
112289 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
112296 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
112307 if( pVTab->pVtab->pModule->xRename==0 ){
112323 /* figure out how many UTF-8 characters are in zName */
112324 zTabName = pTab->zName;
112325 nTabName = sqlite3Utf8CharLen(zTabName, -1);
112362 zDb, zName, pTab->zName);
112383 ** of any resources used by the v-table implementation (including other
112388 int i = ++pParse->nMem;
112423 ** The Table structure pParse->pNewTable was extended to include
112427 Table *pNew; /* Copy of pParse->pNewTable */
112432 char *zCol; /* Null-terminated column definition */
112439 db = pParse->db;
112440 assert( db->pParse==pParse );
112441 if( pParse->nErr ) return;
112442 assert( db->mallocFailed==0 );
112443 pNew = pParse->pNewTable;
112447 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
112448 zDb = db->aDb[iDb].zDbSName;
112449 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
112450 pCol = &pNew->aCol[pNew->nCol-1];
112457 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
112467 if( pCol->colFlags & COLFLAG_PRIMKEY ){
112471 if( pNew->pIndex ){
112476 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
112481 assert( pDflt==0 || pDflt->op==TK_SPAN );
112482 if( pDflt && pDflt->pLeft->op==TK_NULL ){
112486 if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
112488 "Cannot add a REFERENCES column with non-NULL default value");
112490 if( pCol->notNull && !pDflt ){
112505 assert( db->mallocFailed == 1 );
112510 "Cannot add a column with non-constant default");
112514 }else if( pCol->colFlags & COLFLAG_STORED ){
112520 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
112522 char *zEnd = &zCol[pColDef->n-1];
112524 *zEnd-- = '\0';
112535 zDb, pNew->u.tab.addColOffset, zCol, pNew->u.tab.addColOffset,
112550 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
112560 if( pNew->pCheck!=0
112561 || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
112577 ** This function is called by the parser after the table-name in
112578 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
112579 ** pSrc is the full-name of the table being altered.
112597 sqlite3 *db = pParse->db;
112600 assert( pParse->pNewTable==0 );
112602 if( db->mallocFailed ) goto exit_begin_add_column;
112603 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
112624 assert( pTab->u.tab.addColOffset>0 );
112625 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112636 pParse->pNewTable = pNew;
112637 pNew->nTabRef = 1;
112638 pNew->nCol = pTab->nCol;
112639 assert( pNew->nCol>0 );
112640 nAlloc = (((pNew->nCol-1)/8)*8)+8;
112641 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
112642 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
112643 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
112644 if( !pNew->aCol || !pNew->zName ){
112645 assert( db->mallocFailed );
112648 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
112649 for(i=0; i<pNew->nCol; i++){
112650 Column *pCol = &pNew->aCol[i];
112651 pCol->zCnName = sqlite3DbStrDup(db, pCol->zCnName);
112652 pCol->hName = sqlite3StrIHash(pCol->zCnName);
112655 pNew->u.tab.pDfltList = sqlite3ExprListDup(db, pTab->u.tab.pDfltList, 0);
112656 pNew->pSchema = db->aDb[iDb].pSchema;
112657 pNew->u.tab.addColOffset = pTab->u.tab.addColOffset;
112658 pNew->nTabRef = 1;
112669 ** it loads an error message into pParse and returns non-zero.
112689 zType, pTab->zName
112706 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
112710 sqlite3 *db = pParse->db; /* Database connection */
112720 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
112728 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
112730 zDb = db->aDb[iSchema].zDbSName;
112734 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
112743 for(iCol=0; iCol<pTab->nCol; iCol++){
112744 if( 0==sqlite3StrICmp(pTab->aCol[iCol].zCnName, zOld) ) break;
112746 if( iCol==pTab->nCol ){
112751 /* Ensure the schema contains no double-quoted strings */
112762 assert( pNew->n>0 );
112763 bQuote = sqlite3Isquote(pNew->z[0]);
112770 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
112771 pTab->zName
112778 zDb, pTab->zName, iCol, zNew, bQuote
112833 ** rename-token list.
112835 ** 2. Dereferences each pointer in the rename-token list.
112838 ** address-sanitizer or similar. If any of these pointers no longer
112839 ** point to valid objects, an exception is raised by the memory-checking
112853 assert( pParse==pParse->db->pParse );
112854 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
112855 if( pParse->nErr==0 ){
112858 for(p=pParse->pRename; p; p=p->pNext){
112859 if( p->p ){
112860 assert( p->p!=pPtr );
112861 i += *(u8*)(p->p);
112876 ** in pParse->pRename.
112888 assert( pPtr || pParse->db->mallocFailed );
112890 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
112891 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
112893 pNew->p = pPtr;
112894 pNew->t = *pToken;
112895 pNew->pNext = pParse->pRename;
112896 pParse->pRename = pNew;
112911 for(p=pParse->pRename; p; p=p->pNext){
112912 if( p->p==pFrom ){
112913 p->p = pTo;
112923 Parse *pParse = pWalker->pParse;
112926 sqlite3RenameTokenRemap(pParse, 0, (const void*)&pExpr->y.pTab);
112936 With *pWith = pSelect->pWith;
112938 Parse *pParse = pWalker->pParse;
112941 assert( pWith->nCte>0 );
112942 if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){
112943 /* Push a copy of the With object onto the with-stack. We use a copy
112945 ** and SF_Resolved) below. And the parser code that uses the with-stack
112948 pCopy = sqlite3WithDup(pParse->db, pWith);
112951 for(i=0; i<pWith->nCte; i++){
112952 Select *p = pWith->a[i].pSelect;
112957 if( sNC.pParse->db->mallocFailed ) return;
112959 sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols);
112961 if( pCopy && pParse->pWith==pCopy ){
112962 pParse->pWith = pCopy->pOuter;
112976 for(ii=0; ii<pIdList->nId; ii++){
112977 sqlite3RenameTokenRemap(pParse, 0, (const void*)pIdList->a[ii].zName);
112985 Parse *pParse = pWalker->pParse;
112987 if( pParse->nErr ) return WRC_Abort;
112988 testcase( p->selFlags & SF_View );
112989 testcase( p->selFlags & SF_CopyCte );
112990 if( p->selFlags & (SF_View|SF_CopyCte) ){
112993 if( ALWAYS(p->pEList) ){
112994 ExprList *pList = p->pEList;
112995 for(i=0; i<pList->nExpr; i++){
112996 if( pList->a[i].zEName && pList->a[i].fg.eEName==ENAME_NAME ){
112997 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
113001 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
113002 SrcList *pSrc = p->pSrc;
113003 for(i=0; i<pSrc->nSrc; i++){
113004 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
113005 if( pSrc->a[i].fg.isUsing==0 ){
113006 sqlite3WalkExpr(pWalker, pSrc->a[i].u3.pOn);
113008 unmapColumnIdlistNames(pParse, pSrc->a[i].u3.pUsing);
113021 u8 eMode = pParse->eParseMode;
113027 pParse->eParseMode = PARSE_MODE_UNMAP;
113029 pParse->eParseMode = eMode;
113033 ** Remove all nodes that are part of expression-list pEList from the
113044 for(i=0; i<pEList->nExpr; i++){
113045 if( ALWAYS(pEList->a[i].fg.eEName==ENAME_NAME) ){
113046 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
113059 pNext = p->pNext;
113082 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
113083 if( (*pp)->p==pPtr ){
113086 *pp = pToken->pNext;
113087 pToken->pNext = pCtx->pList;
113088 pCtx->pList = pToken;
113089 pCtx->nList++;
113100 ** descend into sub-select statements.
113103 if( p->selFlags & (SF_View|SF_CopyCte) ){
113104 testcase( p->selFlags & SF_View );
113105 testcase( p->selFlags & SF_CopyCte );
113119 ** constructed in RenameCtx object at pWalker->u.pRename.
113122 RenameCtx *p = pWalker->u.pRename;
113123 if( pExpr->op==TK_TRIGGER
113124 && pExpr->iColumn==p->iCol
113125 && pWalker->pParse->pTriggerTab==p->pTab
113127 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
113128 }else if( pExpr->op==TK_COLUMN
113129 && pExpr->iColumn==p->iCol
113131 && p->pTab==pExpr->y.pTab
113133 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
113148 RenameToken *pBest = pCtx->pList;
113152 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
113153 if( pToken->t.z>pBest->t.z ) pBest = pToken;
113155 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
113156 *pp = pBest->pNext;
113163 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
113165 ** sub-routine is currently stored in pParse->zErrMsg. This function
113179 zErr = sqlite3MPrintf(pParse->db, "error in %s %s%s%s: %s",
113181 pParse->zErrMsg
113183 sqlite3_result_error(pCtx, zErr, -1);
113184 sqlite3DbFree(pParse->db, zErr);
113188 ** For each name in the the expression-list pEList (i.e. each
113189 ** pEList->a[i].zName) that matches the string in zOld, extract the
113190 ** corresponding rename-token from Parse object pParse and add it
113201 for(i=0; i<pEList->nExpr; i++){
113202 const char *zName = pEList->a[i].zEName;
113203 if( ALWAYS(pEList->a[i].fg.eEName==ENAME_NAME)
113214 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
113215 ** that matches the string in zOld, extract the corresponding rename-token
113226 for(i=0; i<pIdList->nId; i++){
113227 const char *zName = pIdList->a[i].zName;
113256 db->init.iDb = bTemp ? 1 : sqlite3FindDbName(db, zDb);
113257 p->eParseMode = PARSE_MODE_RENAME;
113258 p->db = db;
113259 p->nQueryLoop = 1;
113261 if( db->mallocFailed ) rc = SQLITE_NOMEM;
113263 && NEVER(p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0)
113274 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
113275 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
113280 db->init.iDb = 0;
113320 nQuot = sqlite3Strlen30(zQuot)-1;
113324 zOut = sqlite3DbMallocZero(db, nSql + pRename->nList*nQuot + 1);
113333 /* At this point pRename->pList contains a list of RenameToken objects
113335 ** with the new column name, or with single-quoted versions of themselves.
113340 while( pRename->pList ){
113347 if( bQuote==0 && sqlite3IsIdChar(*pBest->t.z) ){
113353 if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
113356 /* Dequote the double-quoted token. Then requote it again, this time
113359 ** add another space after the new, single-quoted version of the
113362 memcpy(zBuf1, pBest->t.z, pBest->t.n);
113363 zBuf1[pBest->t.n] = 0;
113366 pBest->t.z[pBest->t.n]=='\'' ? " " : ""
113372 iOff = pBest->t.z - zSql;
113373 if( pBest->t.n!=nReplace ){
113374 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
113375 nOut - (iOff + pBest->t.n)
113377 nOut += nReplace - pBest->t.n;
113384 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
113395 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
113401 sqlite3 *db = pParse->db;
113402 Trigger *pNew = pParse->pNewTrigger;
113409 assert( pNew->pTabSchema );
113410 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
113411 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
113413 pParse->eTriggerOp = pNew->op;
113416 if( ALWAYS(pParse->pTriggerTab) ){
113417 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab);
113421 if( rc==SQLITE_OK && pNew->pWhen ){
113422 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
113425 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
113426 if( pStep->pSelect ){
113427 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
113428 if( pParse->nErr ) rc = pParse->rc;
113430 if( rc==SQLITE_OK && pStep->zTarget ){
113434 pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0
113437 pStep->pExprList = 0;
113442 rc = pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
113443 assert( pStep->pExprList==0 || pStep->pExprList==pSel->pEList );
113444 assert( pSrc==pSel->pSrc );
113445 if( pStep->pExprList ) pSel->pEList = 0;
113446 pSel->pSrc = 0;
113449 if( pStep->pFrom ){
113451 for(i=0; i<pStep->pFrom->nSrc && rc==SQLITE_OK; i++){
113452 SrcItem *p = &pStep->pFrom->a[i];
113453 if( p->pSelect ){
113454 sqlite3SelectPrep(pParse, p->pSelect, 0);
113459 if( db->mallocFailed ){
113463 if( rc==SQLITE_OK && pStep->pWhere ){
113464 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
113467 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
113469 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
113470 if( pStep->pUpsert && rc==SQLITE_OK ){
113471 Upsert *pUpsert = pStep->pUpsert;
113472 pUpsert->pUpsertSrc = pSrc;
113475 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
113477 ExprList *pUpsertSet = pUpsert->pUpsertSet;
113481 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
113484 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
113506 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
113509 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
113510 sqlite3WalkSelect(pWalker, pStep->pSelect);
113511 sqlite3WalkExpr(pWalker, pStep->pWhere);
113512 sqlite3WalkExprList(pWalker, pStep->pExprList);
113513 if( pStep->pUpsert ){
113514 Upsert *pUpsert = pStep->pUpsert;
113515 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
113516 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
113517 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
113518 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
113520 if( pStep->pFrom ){
113522 for(i=0; i<pStep->pFrom->nSrc; i++){
113523 sqlite3WalkSelect(pWalker, pStep->pFrom->a[i].pSelect);
113534 sqlite3 *db = pParse->db;
113536 if( pParse->pVdbe ){
113537 sqlite3VdbeFinalize(pParse->pVdbe);
113539 sqlite3DeleteTable(db, pParse->pNewTable);
113540 while( (pIdx = pParse->pNewIndex)!=0 ){
113541 pParse->pNewIndex = pIdx->pNext;
113544 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
113545 sqlite3DbFree(db, pParse->zErrMsg);
113546 renameTokenFree(db, pParse->pRename);
113562 ** 7. bQuote: Non-zero if the new column name should be quoted.
113566 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
113596 sqlite3_xauth xAuth = db->xAuth;
113606 if( pTab==0 || iCol>=pTab->nCol ){
113610 zOld = pTab->aCol[iCol].zCnName;
113612 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
113615 db->xAuth = 0;
113630 Select *pSelect = sParse.pNewTable->u.view.pSelect;
113631 pSelect->selFlags &= ~SF_View;
113634 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
113641 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
113645 if( iCol<sParse.pNewTable->nCol ){
113647 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zCnName
113651 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
113653 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
113654 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
113655 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
113657 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
113658 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
113661 for(i=0; i<sParse.pNewTable->nCol; i++){
113663 &sParse.pNewTable->aCol[i]);
113670 for(pFKey=sParse.pNewTable->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
113671 for(i=0; i<pFKey->nCol; i++){
113672 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
113673 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
113675 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
113676 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
113678 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
113684 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
113685 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
113692 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
113693 if( pStep->zTarget ){
113694 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
113696 if( pStep->pUpsert ){
113697 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
113700 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
113701 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
113709 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
113733 db->xAuth = xAuth;
113742 RenameCtx *p = pWalker->u.pRename;
113743 if( pExpr->op==TK_COLUMN
113745 && p->pTab==pExpr->y.pTab
113747 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
113757 RenameCtx *p = pWalker->u.pRename;
113758 SrcList *pSrc = pSelect->pSrc;
113759 if( pSelect->selFlags & (SF_View|SF_CopyCte) ){
113760 testcase( pSelect->selFlags & SF_View );
113761 testcase( pSelect->selFlags & SF_CopyCte );
113765 assert( pWalker->pParse->db->mallocFailed );
113768 for(i=0; i<pSrc->nSrc; i++){
113769 SrcItem *pItem = &pSrc->a[i];
113770 if( pItem->pTab==p->pTab ){
113771 renameTokenFind(pWalker->pParse, p, pItem->zName);
113797 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
113820 sqlite3_xauth xAuth = db->xAuth;
113821 db->xAuth = 0;
113837 int isLegacy = (db->flags & SQLITE_LegacyAlter);
113843 Select *pSelect = pTab->u.view.pSelect;
113848 assert( pSelect->selFlags & SF_View );
113849 pSelect->selFlags &= ~SF_View;
113850 sqlite3SelectPrep(&sParse, pTab->u.view.pSelect, &sNC);
113854 sqlite3WalkSelect(&sWalker, pTab->u.view.pSelect);
113860 if( (isLegacy==0 || (db->flags & SQLITE_ForeignKeys))
113865 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
113866 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
113867 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
113876 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
113879 sqlite3WalkExprList(&sWalker, pTab->pCheck);
113881 renameTokenFind(&sParse, &sCtx, pTab->zName);
113887 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
113889 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
113897 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
113898 && sCtx.pTab->pSchema==pTrigger->pTabSchema
113900 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
113907 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
113908 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
113909 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
113911 if( pStep->pFrom ){
113913 for(i=0; i<pStep->pFrom->nSrc; i++){
113914 SrcItem *pItem = &pStep->pFrom->a[i];
113915 if( 0==sqlite3_stricmp(pItem->zName, zOld) ){
113916 renameTokenFind(&sParse, &sCtx, pItem->zName);
113944 db->xAuth = xAuth;
113952 if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
113953 renameTokenFind(pWalker->pParse, pWalker->u.pRename, (const void*)pExpr);
113961 ** double-quotes use single quotes instead.
113995 sqlite3_xauth xAuth = db->xAuth;
113996 db->xAuth = 0;
114021 Select *pSelect = sParse.pNewTable->u.view.pSelect;
114022 pSelect->selFlags &= ~SF_View;
114025 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
114031 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
114033 for(i=0; i<sParse.pNewTable->nCol; i++){
114036 &sParse.pNewTable->aCol[i]));
114041 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
114042 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
114068 db->xAuth = xAuth;
114107 int isLegacy = (db->flags & SQLITE_LegacyAlter);
114112 sqlite3_xauth xAuth = db->xAuth;
114113 db->xAuth = 0;
114121 int flags = db->flags;
114122 if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
114124 db->flags |= (flags & (SQLITE_DqsDML|SQLITE_DqsDDL));
114130 sqlite3SelectPrep(&sParse, sParse.pNewTable->u.view.pSelect, &sNC);
114139 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
114157 db->xAuth = xAuth;
114166 ** argv[0]: An integer - the index of the schema containing the table
114168 ** argv[2]: An integer - the index of the column to remove.
114182 const char *zDb = db->aDb[iSchema].zDbSName;
114191 sqlite3_xauth xAuth = db->xAuth;
114192 db->xAuth = 0;
114199 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
114205 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zCnName);
114206 if( iCol<pTab->nCol-1 ){
114208 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zCnName);
114209 zEnd = (const char*)pEnd->t.z;
114212 zEnd = (const char*)&zSql[pTab->u.tab.addColOffset];
114213 while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
114216 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
114217 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
114223 db->xAuth = xAuth;
114239 sqlite3 *db = pParse->db; /* Database handle */
114244 int iCol; /* Index of column zCol in pTab->aCol[] */
114247 assert( pParse->pNewTable==0 );
114249 if( NEVER(db->mallocFailed) ) goto exit_drop_column;
114250 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
114261 assert( db->mallocFailed );
114272 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
114274 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
114281 if( pTab->nCol<=1 ){
114287 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
114289 zDb = db->aDb[iDb].zDbSName;
114292 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, zCol) ){
114302 , zDb, iDb, iCol, pTab->zName
114310 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
114316 int nField = 0; /* Number of non-virtual columns after drop */
114319 iCur = pParse->nTab++;
114322 reg = ++pParse->nMem;
114325 pParse->nMem += pTab->nCol;
114328 pParse->nMem += pPk->nColumn;
114329 for(i=0; i<pPk->nKeyCol; i++){
114332 nField = pPk->nKeyCol;
114334 regRec = ++pParse->nMem;
114335 for(i=0; i<pTab->nCol; i++){
114336 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
114341 if( iPos<pPk->nKeyCol ) continue;
114342 regOut = reg+1+iPos-(iPos>iColPos);
114346 if( i==pTab->iPKey ){
114356 pParse->nMem++;
114362 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
114378 ** Register built-in functions used to help implement ALTER TABLE
114395 ** 2005-07-08
114397 ** The author disclaims copyright to this source code. In place of
114445 ** columns. The N-th integer (for N>1) is the average number of rows in
114446 ** the index which have the same value for the first N-1 columns. For
114447 ** a K-column index, there will be K+1 integers in the stat column. If
114471 ** inclusive are samples of the left-most key value in the index taken at
114478 ** For i between 0 and S-1. Conceptually, the index space is divided into
114505 ** of entries in the index whose left-most column exactly matches
114506 ** the left-most column of the sample. The second integer in nEq
114512 ** left-most column is less than the left-most column of the sample.
114513 ** The K-th integer in the nLt entry is the number of index entries
114528 ** looks at the left-most column of the index. The sqlite_stat3.sample
114529 ** column contains the actual value of the left-most column instead
114550 ** appropriate compile-time options are provided.
114579 sqlite3 *db = pParse->db;
114593 pDb = &db->aDb[iDb];
114602 if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
114605 ** side-effect of the CREATE TABLE statement is to leave the rootpage
114606 ** of the new table in register pParse->regRoot. This is important
114609 "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
114611 aRoot[i] = (u32)pParse->regRoot;
114618 aRoot[i] = pStat->tnum;
114623 pDb->zDbSName, zTab, zWhereType, zWhere
114626 }else if( db->xPreUpdateCallback ){
114627 sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
114653 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
114678 int nLimit; /* Analysis row-scan limit */
114681 u8 nSkipAhead; /* Number of times of skip-ahead */
114686 u32 iPrn; /* Pseudo-random number used for sampling */
114701 if( p->nRowid ){
114702 sqlite3DbFree(db, p->u.aRowid);
114703 p->nRowid = 0;
114713 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
114714 p->u.aRowid = sqlite3DbMallocRawNN(db, n);
114715 if( p->u.aRowid ){
114716 p->nRowid = n;
114717 memcpy(p->u.aRowid, pData, n);
114719 p->nRowid = 0;
114729 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
114730 p->nRowid = 0;
114731 p->u.iRowid = iRowid;
114741 pTo->isPSample = pFrom->isPSample;
114742 pTo->iCol = pFrom->iCol;
114743 pTo->iHash = pFrom->iHash;
114744 memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
114745 memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
114746 memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
114747 if( pFrom->nRowid ){
114748 sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
114750 sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
114761 if( p->mxSample ){
114763 for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
114764 for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
114765 sampleClear(p->db, &p->current);
114768 sqlite3DbFree(p->db, p);
114777 ** L: A limit on the number of rows to scan, or 0 for no-limit
114835 p->db = db;
114836 p->nEst = sqlite3_value_int64(argv[2]);
114837 p->nRow = 0;
114838 p->nLimit = sqlite3_value_int64(argv[3]);
114839 p->nCol = nCol;
114840 p->nKeyCol = nKeyCol;
114841 p->nSkipAhead = 0;
114842 p->current.anDLt = (tRowcnt*)&p[1];
114843 p->current.anEq = &p->current.anDLt[nColUp];
114846 p->mxSample = p->nLimit==0 ? mxSample : 0;
114849 int i; /* Used to iterate through p->aSample[] */
114851 p->iGet = -1;
114852 p->nPSample = (tRowcnt)(p->nEst/(mxSample/3+1) + 1);
114853 p->current.anLt = &p->current.anEq[nColUp];
114854 p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
114857 p->a = (struct StatSample*)&p->current.anLt[nColUp];
114858 p->aBest = &p->a[mxSample];
114859 pSpace = (u8*)(&p->a[mxSample+nCol]);
114861 p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
114862 p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
114863 p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
114865 assert( (pSpace - (u8*)p)==n );
114868 p->aBest[i].iCol = i;
114893 ** pNew and pOld are both candidate non-periodic samples selected for
114894 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
114901 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
114908 int nCol = pAccum->nCol;
114910 assert( pNew->iCol==pOld->iCol );
114911 for(i=pNew->iCol+1; i<nCol; i++){
114912 if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
114913 if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
114915 if( pNew->iHash>pOld->iHash ) return 1;
114925 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
114932 tRowcnt nEqNew = pNew->anEq[pNew->iCol];
114933 tRowcnt nEqOld = pOld->anEq[pOld->iCol];
114935 assert( pOld->isPSample==0 && pNew->isPSample==0 );
114936 assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
114940 if( pNew->iCol<pOld->iCol ) return 1;
114941 return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
114947 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
114948 ** remove the least desirable sample from p->a[] to make room.
114960 if( nEqZero>p->nMaxEqZero ){
114961 p->nMaxEqZero = nEqZero;
114963 if( pNew->isPSample==0 ){
114965 assert( pNew->anEq[pNew->iCol]>0 );
114972 for(i=p->nSample-1; i>=0; i--){
114973 StatSample *pOld = &p->a[i];
114974 if( pOld->anEq[pNew->iCol]==0 ){
114975 if( pOld->isPSample ) return;
114976 assert( pOld->iCol>pNew->iCol );
114984 pUpgrade->iCol = pNew->iCol;
114985 pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
114991 if( p->nSample>=p->mxSample ){
114992 StatSample *pMin = &p->a[p->iMin];
114993 tRowcnt *anEq = pMin->anEq;
114994 tRowcnt *anLt = pMin->anLt;
114995 tRowcnt *anDLt = pMin->anDLt;
114996 sampleClear(p->db, pMin);
114997 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
114998 pSample = &p->a[p->nSample-1];
114999 pSample->nRowid = 0;
115000 pSample->anEq = anEq;
115001 pSample->anDLt = anDLt;
115002 pSample->anLt = anLt;
115003 p->nSample = p->mxSample-1;
115006 /* The "rows less-than" for the rowid column must be greater than that
115007 ** for the last sample in the p->a[] array. Otherwise, the samples would
115009 assert( p->nSample==0
115010 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
115013 pSample = &p->a[p->nSample];
115015 p->nSample++;
115018 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
115021 if( p->nSample>=p->mxSample ){
115022 int iMin = -1;
115023 for(i=0; i<p->mxSample; i++){
115024 if( p->a[i].isPSample ) continue;
115025 if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
115030 p->iMin = iMin;
115038 ** p->current contains a sample that reflects the previous row of the
115047 for(i=(p->nCol-2); i>=iChng; i--){
115048 StatSample *pBest = &p->aBest[i];
115049 pBest->anEq[i] = p->current.anEq[i];
115050 if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
115056 ** p->nMaxEqZero or greater set to zero. */
115057 for(i=p->nSample-1; i>=0; i--){
115059 for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
115063 if( iChng<p->nMaxEqZero ){
115064 for(i=p->nSample-1; i>=0; i--){
115066 for(j=iChng; j<p->nCol; j++){
115067 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
115070 p->nMaxEqZero = iChng;
115080 ** C Index of left-most column to differ from previous row
115090 ** if it wants the byte-code to do special processing.
115107 assert( p->nCol>0 );
115108 assert( iChng<p->nCol );
115110 if( p->nRow==0 ){
115112 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
115116 if( p->mxSample ) samplePushPrevious(p, iChng);
115122 p->current.anEq[i]++;
115124 for(i=iChng; i<p->nCol; i++){
115125 p->current.anDLt[i]++;
115127 if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i];
115129 p->current.anEq[i] = 1;
115133 p->nRow++;
115135 if( p->mxSample ){
115138 sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
115140 sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
115143 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
115145 nLt = p->current.anLt[p->nCol-1];
115147 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
115148 p->current.isPSample = 1;
115149 p->current.iCol = 0;
115150 sampleInsert(p, &p->current, p->nCol-1);
115151 p->current.isPSample = 0;
115155 for(i=0; i<(p->nCol-1); i++){
115156 p->current.iCol = i;
115157 if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
115158 sampleCopy(p, &p->aBest[i], &p->current);
115163 if( p->nLimit && p->nRow>(tRowcnt)p->nLimit*(p->nSkipAhead+1) ){
115164 p->nSkipAhead++;
115165 sqlite3_result_int(context, p->current.anDLt[0]>0);
115203 ** a one-parameter function, stat_get(P), that always returns the
115220 assert( eCall==STAT_GET_STAT1 || p->mxSample );
115245 ** I = (K+D-1)/D
115255 sqlite3StrAccumInit(&sStat, 0, 0, 0, (p->nKeyCol+1)*100);
115257 p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow);
115258 for(i=0; i<p->nKeyCol; i++){
115259 u64 nDistinct = p->current.anDLt[i] + 1;
115260 u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
115261 if( iVal==2 && p->nRow*10 <= nDistinct*11 ) iVal = 1;
115263 assert( p->current.anEq[i] );
115269 if( p->iGet<0 ){
115271 p->iGet = 0;
115273 if( p->iGet<p->nSample ){
115274 StatSample *pS = p->a + p->iGet;
115275 if( pS->nRowid==0 ){
115276 sqlite3_result_int64(context, pS->u.iRowid);
115278 sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
115287 assert( p->iGet<p->nSample );
115289 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
115290 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
115292 aCnt = p->a[p->iGet].anDLt;
115293 p->iGet++;
115297 sqlite3StrAccumInit(&sStat, 0, 0, 0, p->nCol*100);
115298 for(i=0; i<p->nCol; i++){
115301 if( sStat.nChar ) sStat.nChar--;
115323 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat+1);
115336 ** of the k-th column of the pIdx index.
115344 assert( k>=0 && k<pIdx->nColumn );
115345 i = pIdx->aiColumn[k];
115347 VdbeComment((v,"%s.rowid",pIdx->zName));
115349 assert( pIdx->bHasExpr );
115350 VdbeComment((v,"%s.expr(%d)",pIdx->zName, k));
115352 VdbeComment((v,"%s.%s", pIdx->zName, pIdx->pTable->aCol[i].zCnName));
115371 sqlite3 *db = pParse->db; /* Database handle */
115377 int jZeroRows = -1; /* Jump from here if number of rows is zero */
115394 pParse->nMem = MAX(pParse->nMem, iMem);
115403 if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
115408 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
115412 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
115413 db->aDb[iDb].zDbSName ) ){
115419 if( db->xPreUpdateCallback ){
115422 pStat1->zName = (char*)&pStat1[1];
115423 memcpy(pStat1->zName, "sqlite_stat1", 13);
115424 pStat1->nCol = 3;
115425 pStat1->iPKey = -1;
115426 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNAMIC);
115430 /* Establish a read-lock on the table at the shared-cache level.
115431 ** Open a read-only cursor on the table. Also allocate a cursor number
115434 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
115437 pParse->nTab = MAX(pParse->nTab, iTab);
115439 sqlite3VdbeLoadString(v, regTabname, pTab->zName);
115441 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
115449 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
115451 nCol = pIdx->nKeyCol;
115452 zIdxName = pTab->zName;
115453 nColTest = nCol - 1;
115455 nCol = pIdx->nColumn;
115456 zIdxName = pIdx->zName;
115457 nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
115462 VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
115465 ** Pseudo-code for loop that calls stat_push():
115500 pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
115502 /* Open a read-only cursor on the index being analyzed. */
115503 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
115504 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
115506 VdbeComment((v, "%s", pIdx->zName));
115517 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regRowid);
115531 sqlite3VdbeAddOp2(v, OP_Integer, db->nAnalysisLimit, regTemp2);
115564 if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
115565 /* For a single-column UNIQUE index, once we have found a non-NULL
115572 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
115592 sqlite3VdbeJumpHere(v, addrNextRow-1);
115615 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
115617 regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
115618 for(j=0; j<pPk->nKeyCol; j++){
115619 k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
115620 assert( k>=0 && k<pIdx->nColumn );
115624 sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
115625 sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
115633 if( db->nAnalysisLimit ){
115655 sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
115661 if( OptimizationEnabled(db, SQLITE_Stat4) && db->nAnalysisLimit==0 ){
115672 pParse->nMem = MAX(pParse->nMem, regCol+nCol);
115690 sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
115704 VdbeComment((v, "%s", pTab->zName));
115714 sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
115736 sqlite3 *db = pParse->db;
115737 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
115744 iStatCur = pParse->nTab;
115745 pParse->nTab += 3;
115747 iMem = pParse->nMem+1;
115748 iTab = pParse->nTab;
115750 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
115767 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
115768 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
115770 iStatCur = pParse->nTab;
115771 pParse->nTab += 3;
115773 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
115775 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
115777 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
115785 ** ANALYZE -- 1
115786 ** ANALYZE <database> -- 2
115787 ** ANALYZE ?<database>.?<tablename> -- 3
115794 sqlite3 *db = pParse->db;
115805 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
115813 for(i=0; i<db->nDb; i++){
115817 }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
115824 zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
115828 analyzeTable(pParse, pIdx->pTable, pIdx);
115836 if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
115852 ** The first argument points to a nul-terminated string containing a
115876 v = v*10 + c - '0';
115895 pIndex->bUnordered = 0;
115896 pIndex->noSkipScan = 0;
115899 pIndex->bUnordered = 1;
115900 }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
115903 pIndex->szIdxRow = sqlite3LogEst(sz);
115905 pIndex->noSkipScan = 1;
115908 else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
115909 pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
115924 ** argv[2] = results of analysis - on integer for each column
115941 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
115950 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
115956 int nCol = pIndex->nKeyCol+1;
115961 if( pIndex->aiRowEst==0 ){
115962 pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
115963 if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
115965 aiRowEst = pIndex->aiRowEst;
115967 pIndex->bUnordered = 0;
115968 decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
115969 pIndex->hasStat1 = 1;
115970 if( pIndex->pPartIdxWhere==0 ){
115971 pTable->nRowLogEst = pIndex->aiRowLogEst[0];
115972 pTable->tabFlags |= TF_HasStat1;
115976 fakeIdx.szIdxRow = pTable->szTabRow;
115980 decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
115981 pTable->szTabRow = fakeIdx.szIdxRow;
115982 pTable->tabFlags |= TF_HasStat1;
115994 if( pIdx->aSample ){
115996 for(j=0; j<pIdx->nSample; j++){
115997 IndexSample *p = &pIdx->aSample[j];
115998 sqlite3DbFree(db, p->p);
116000 sqlite3DbFree(db, pIdx->aSample);
116002 if( db && db->pnBytesFreed==0 ){
116003 pIdx->nSample = 0;
116004 pIdx->aSample = 0;
116014 ** Populate the pIdx->aAvgEq[] array based on the samples currently
116015 ** stored in pIdx->aSample[].
116019 IndexSample *aSample = pIdx->aSample;
116020 IndexSample *pFinal = &aSample[pIdx->nSample-1];
116023 if( pIdx->nSampleCol>1 ){
116028 nCol = pIdx->nSampleCol-1;
116029 pIdx->aAvgEq[nCol] = 1;
116032 int nSample = pIdx->nSample;
116040 if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
116041 nRow = pFinal->anLt[iCol];
116042 nDist100 = (i64)100 * pFinal->anDLt[iCol];
116043 nSample--;
116045 nRow = pIdx->aiRowEst[0];
116046 nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
116048 pIdx->nRowEst0 = nRow;
116055 if( i==(pIdx->nSample-1)
116064 avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
116067 pIdx->aAvgEq[iCol] = avgEq;
116111 IndexSample *pSample; /* A slot in pIdx->aSample[] */
116113 assert( db->lookaside.bDisable );
116118 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
116136 assert( pIdx==0 || pIdx->nSample==0 );
116138 assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
116139 if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
116140 nIdxCol = pIdx->nKeyCol;
116142 nIdxCol = pIdx->nColumn;
116144 pIdx->nSampleCol = nIdxCol;
116149 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
116150 if( pIdx->aSample==0 ){
116154 pSpace = (tRowcnt*)&pIdx->aSample[nSample];
116155 pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
116156 pIdx->pTable->tabFlags |= TF_HasStat4;
116158 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
116159 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
116160 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
116162 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
116171 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
116186 nCol = pIdx->nSampleCol;
116191 pSample = &pIdx->aSample[pIdx->nSample];
116192 decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
116193 decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
116194 decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
116202 pSample->n = sqlite3_column_bytes(pStmt, 4);
116203 pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
116204 if( pSample->p==0 ){
116208 if( pSample->n ){
116209 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
116211 pIdx->nSample++;
116226 assert( db->lookaside.bDisable );
116256 ** If an OOM error occurs, this function always sets db->mallocFailed.
116265 Schema *pSchema = db->aDb[iDb].pSchema;
116268 assert( iDb>=0 && iDb<db->nDb );
116269 assert( db->aDb[iDb].pBt!=0 );
116273 for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
116275 pTab->tabFlags &= ~TF_HasStat1;
116277 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
116279 pIdx->hasStat1 = 0;
116282 pIdx->aSample = 0;
116288 sInfo.zDatabase = db->aDb[iDb].zDbSName;
116304 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
116306 if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
116316 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
116318 sqlite3_free(pIdx->aiRowEst);
116319 pIdx->aiRowEst = 0;
116337 ** The author disclaims copyright to this source code. In place of
116372 if( pExpr->op!=TK_ID ){
116375 pExpr->op = TK_STRING;
116387 sqlite3StrICmp(db->aDb[iDb].zDbSName, zName)==0
116393 ** An SQL user-function registered to do the work of an ATTACH statement. The
116403 ** If the db->init.reopenMemdb flags is set, then instead of attaching a
116404 ** new database, close the database on db->init.iDb and reopen it as an
116432 # define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb)
116439 ** from sqlite3_deserialize() to close database db->init.iDb and
116443 pNew = &db->aDb[db->init.iDb];
116444 if( pNew->pBt ) sqlite3BtreeClose(pNew->pBt);
116445 pNew->pBt = 0;
116446 pNew->pSchema = 0;
116447 rc = sqlite3BtreeOpen(pVfs, "x\0", db, &pNew->pBt, 0, SQLITE_OPEN_MAIN_DB);
116457 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
116458 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
116459 db->aLimit[SQLITE_LIMIT_ATTACHED]
116463 for(i=0; i<db->nDb; i++){
116471 /* Allocate the new entry in the db->aDb[] array and initialize the schema
116474 if( db->aDb==db->aDbStatic ){
116475 aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
116477 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
116479 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
116482 db->aDb = aNew;
116483 pNew = &db->aDb[db->nDb];
116490 flags = db->openFlags;
116491 rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
116494 sqlite3_result_error(context, zErr, -1);
116500 rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
116501 db->nDb++;
116502 pNew->zDbSName = sqlite3DbStrDup(db, zName);
116504 db->noSharedCache = 0;
116510 pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
116511 if( !pNew->pSchema ){
116513 }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
116518 sqlite3BtreeEnter(pNew->pBt);
116519 pPager = sqlite3BtreePager(pNew->pBt);
116520 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
116521 sqlite3BtreeSecureDelete(pNew->pBt,
116522 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
116524 sqlite3BtreeSetPagerFlags(pNew->pBt,
116525 PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
116527 sqlite3BtreeLeave(pNew->pBt);
116529 pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
116530 if( rc==SQLITE_OK && pNew->zDbSName==0 ){
116552 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
116560 if( nKey || sqlite3BtreeGetRequestedReserve(db->aDb[0].pBt)>0 ){
116561 rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
116572 ** remove the entry from the db->aDb[] array. i.e. put everything back the
116577 db->init.iDb = 0;
116578 db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
116589 if( newAuth<db->auth.authLevel ){
116596 int iDb = db->nDb - 1;
116598 if( db->aDb[iDb].pBt ){
116599 sqlite3BtreeClose(db->aDb[iDb].pBt);
116600 db->aDb[iDb].pBt = 0;
116601 db->aDb[iDb].pSchema = 0;
116604 db->nDb = iDb;
116621 sqlite3_result_error(context, zErrDyn, -1);
116628 ** An SQL user-function registered to do the work of an DETACH statement. The
116650 for(i=0; i<db->nDb; i++){
116651 pDb = &db->aDb[i];
116652 if( pDb->pBt==0 ) continue;
116656 if( i>=db->nDb ){
116664 if( sqlite3BtreeTxnState(pDb->pBt)!=SQLITE_TXN_NONE
116665 || sqlite3BtreeIsInBackup(pDb->pBt)
116673 assert( db->aDb[1].pSchema );
116674 pEntry = sqliteHashFirst(&db->aDb[1].pSchema->trigHash);
116677 if( pTrig->pTabSchema==pDb->pSchema ){
116678 pTrig->pTabSchema = pTrig->pSchema;
116683 sqlite3BtreeClose(pDb->pBt);
116684 pDb->pBt = 0;
116685 pDb->pSchema = 0;
116690 sqlite3_result_error(context, zErr, -1);
116709 sqlite3* db = pParse->db;
116712 if( pParse->nErr ) goto attach_end;
116727 if( pAuthArg->op==TK_STRING ){
116729 zAuthArg = pAuthArg->u.zToken;
116747 assert( v || db->mallocFailed );
116749 sqlite3VdbeAddFunctionCall(pParse, 0, regArgs+3-pFunc->nArg, regArgs+3,
116750 pFunc->nArg, pFunc, 0);
116809 DbFixer *pFix = p->u.pFix;
116810 if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL);
116811 if( pExpr->op==TK_VARIABLE ){
116812 if( pFix->pParse->db->init.busy ){
116813 pExpr->op = TK_NULL;
116815 sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
116826 DbFixer *pFix = p->u.pFix;
116829 sqlite3 *db = pFix->pParse->db;
116830 int iDb = sqlite3FindDbName(db, pFix->zDb);
116831 SrcList *pList = pSelect->pSrc;
116834 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
116835 if( pFix->bTemp==0 ){
116836 if( pItem->zDatabase ){
116837 if( iDb!=sqlite3FindDbName(db, pItem->zDatabase) ){
116838 sqlite3ErrorMsg(pFix->pParse,
116840 pFix->zType, pFix->pName, pItem->zDatabase);
116843 sqlite3DbFree(db, pItem->zDatabase);
116844 pItem->zDatabase = 0;
116845 pItem->fg.notCte = 1;
116847 pItem->pSchema = pFix->pSchema;
116848 pItem->fg.fromDDL = 1;
116851 if( pList->a[i].fg.isUsing==0
116852 && sqlite3WalkExpr(&pFix->w, pList->a[i].u3.pOn)
116858 if( pSelect->pWith ){
116859 for(i=0; i<pSelect->pWith->nCte; i++){
116860 if( sqlite3WalkSelect(p, pSelect->pWith->a[i].pSelect) ){
116879 sqlite3 *db = pParse->db;
116880 assert( db->nDb>iDb );
116881 pFix->pParse = pParse;
116882 pFix->zDb = db->aDb[iDb].zDbSName;
116883 pFix->pSchema = db->aDb[iDb].pSchema;
116884 pFix->zType = zType;
116885 pFix->pName = pName;
116886 pFix->bTemp = (iDb==1);
116887 pFix->w.pParse = pParse;
116888 pFix->w.xExprCallback = fixExprCb;
116889 pFix->w.xSelectCallback = fixSelectCb;
116890 pFix->w.xSelectCallback2 = sqlite3WalkWinDefnDummyCallback;
116891 pFix->w.walkerDepth = 0;
116892 pFix->w.eCode = 0;
116893 pFix->w.u.pFix = pFix;
116907 ** pParse->zErrMsg and these routines return non-zero. If everything
116912 SrcList *pList /* The Source list to check and modify */
116919 res = sqlite3WalkSelect(&pFix->w, &s);
116928 return sqlite3WalkSelect(&pFix->w, pSelect);
116934 return sqlite3WalkExpr(&pFix->w, pExpr);
116944 if( sqlite3WalkSelect(&pFix->w, pStep->pSelect)
116945 || sqlite3WalkExpr(&pFix->w, pStep->pWhere)
116946 || sqlite3WalkExprList(&pFix->w, pStep->pExprList)
116947 || sqlite3FixSrcList(pFix, pStep->pFrom)
116954 for(pUp=pStep->pUpsert; pUp; pUp=pUp->pNextUpsert){
116955 if( sqlite3WalkExprList(&pFix->w, pUp->pUpsertTarget)
116956 || sqlite3WalkExpr(&pFix->w, pUp->pUpsertTargetWhere)
116957 || sqlite3WalkExprList(&pFix->w, pUp->pUpsertSet)
116958 || sqlite3WalkExpr(&pFix->w, pUp->pUpsertWhere)
116965 pStep = pStep->pNext;
116977 ** The author disclaims copyright to this source code. In place of
116988 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
117035 ** means that the SQL statement will never-run - the sqlite3_exec() call
117051 sqlite3_mutex_enter(db->mutex);
117052 db->xAuth = (sqlite3_xauth)xAuth;
117053 db->pAuthArg = pArg;
117054 if( db->xAuth ) sqlite3ExpirePreparedStatements(db, 1);
117055 sqlite3_mutex_leave(db->mutex);
117060 ** Write an error message into pParse->zErrMsg that explains that the
117061 ** user-supplied authorization function returned an illegal value.
117065 pParse->rc = SQLITE_ERROR;
117083 sqlite3 *db = pParse->db; /* Database handle */
117084 char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
117087 if( db->init.busy ) return SQLITE_OK;
117088 rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
117090 ,db->auth.zAuthUser
117095 if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
117097 pParse->rc = SQLITE_AUTH;
117121 int iSrc; /* Index in pTabList->a[] of table being read */
117125 assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
117127 assert( pParse->db->xAuth!=0 );
117128 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
117135 if( pExpr->op==TK_TRIGGER ){
117136 pTab = pParse->pTriggerTab;
117139 for(iSrc=0; iSrc<pTabList->nSrc; iSrc++){
117140 if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
117141 pTab = pTabList->a[iSrc].pTab;
117146 iCol = pExpr->iColumn;
117150 assert( iCol<pTab->nCol );
117151 zCol = pTab->aCol[iCol].zCnName;
117152 }else if( pTab->iPKey>=0 ){
117153 assert( pTab->iPKey<pTab->nCol );
117154 zCol = pTab->aCol[pTab->iPKey].zCnName;
117158 assert( iDb>=0 && iDb<pParse->db->nDb );
117159 if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
117160 pExpr->op = TK_NULL;
117177 sqlite3 *db = pParse->db;
117183 assert( !IN_RENAME_OBJECT || db->xAuth==0 );
117184 if( db->xAuth==0 || db->init.busy || IN_SPECIAL_PARSE ){
117188 /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
117189 ** callback are either NULL pointers or zero-terminated strings that
117197 testcase( pParse->zAuthContext==0 );
117199 rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
117201 ,db->auth.zAuthUser
117206 pParse->rc = SQLITE_AUTH;
117217 ** popped. Or if pParse==0, this routine is a no-op.
117225 pContext->pParse = pParse;
117226 pContext->zAuthContext = pParse->zAuthContext;
117227 pParse->zAuthContext = zContext;
117235 if( pContext->pParse ){
117236 pContext->pParse->zAuthContext = pContext->zAuthContext;
117237 pContext->pParse = 0;
117248 ** The author disclaims copyright to this source code. In place of
117284 ** Record the fact that we want to lock a table at run-time.
117307 for(i=0; i<pToplevel->nTableLock; i++){
117308 p = &pToplevel->aTableLock[i];
117309 if( p->iDb==iDb && p->iTab==iTab ){
117310 p->isWriteLock = (p->isWriteLock || isWriteLock);
117315 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
117316 pToplevel->aTableLock =
117317 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
117318 if( pToplevel->aTableLock ){
117319 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
117320 p->iDb = iDb;
117321 p->iTab = iTab;
117322 p->isWriteLock = isWriteLock;
117323 p->zLockName = zName;
117325 pToplevel->nTableLock = 0;
117326 sqlite3OomFault(pToplevel->db);
117337 if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
117347 Vdbe *pVdbe = pParse->pVdbe;
117350 for(i=0; i<pParse->nTableLock; i++){
117351 TableLock *p = &pParse->aTableLock[i];
117352 int p1 = p->iDb;
117353 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
117354 p->zLockName, P4_STATIC);
117362 ** Return TRUE if the given yDbMask object is empty - if it contains no
117389 assert( pParse->pToplevel==0 );
117390 db = pParse->db;
117391 assert( db->pParse==pParse );
117392 if( pParse->nested ) return;
117393 if( pParse->nErr ){
117394 if( db->mallocFailed ) pParse->rc = SQLITE_NOMEM;
117397 assert( db->mallocFailed==0 );
117402 v = pParse->pVdbe;
117404 if( db->init.busy ){
117405 pParse->rc = SQLITE_DONE;
117409 if( v==0 ) pParse->rc = SQLITE_ERROR;
117411 assert( !pParse->isMultiWrite
117412 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
117414 if( pParse->bReturning ){
117415 Returning *pReturning = pParse->u1.pReturning;
117419 if( pReturning->nRetCol ){
117422 sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur);
117424 reg = pReturning->iRetReg;
117425 for(i=0; i<pReturning->nRetCol; i++){
117426 sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i);
117429 sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);
117437 if( pParse->nTableLock>0 && db->init.busy==0 ){
117439 if( db->auth.authLevel<UAUTH_User ){
117441 pParse->rc = SQLITE_AUTH_USER;
117453 assert( pParse->nErr>0 || sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
117455 assert( db->nDb>0 );
117459 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
117461 pSchema = db->aDb[iDb].pSchema;
117465 DbMaskTest(pParse->writeMask,iDb), /* P2 */
117466 pSchema->schema_cookie, /* P3 */
117467 pSchema->iGeneration /* P4 */
117469 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
117471 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
117472 }while( ++iDb<db->nDb );
117474 for(i=0; i<pParse->nVtabLock; i++){
117475 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
117478 pParse->nVtabLock = 0;
117482 ** obtain the required table-locks. This is a no-op unless the
117483 ** shared-cache feature is enabled.
117498 if( pParse->pConstExpr ){
117499 ExprList *pEL = pParse->pConstExpr;
117500 pParse->okConstFactor = 0;
117501 for(i=0; i<pEL->nExpr; i++){
117502 int iReg = pEL->a[i].u.iConstExprReg;
117503 sqlite3ExprCode(pParse, pEL->a[i].pExpr, iReg);
117507 if( pParse->bReturning ){
117508 Returning *pRet = pParse->u1.pReturning;
117509 if( pRet->nRetCol ){
117510 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
117520 assert( v!=0 || pParse->nErr );
117521 assert( db->mallocFailed==0 || pParse->nErr );
117522 if( pParse->nErr==0 ){
117525 assert( pParse->pAinc==0 || pParse->nTab>0 );
117527 pParse->rc = SQLITE_DONE;
117529 pParse->rc = SQLITE_ERROR;
117542 ** * Built-in SQL functions always take precedence over application-defined
117544 ** built-in function.
117549 sqlite3 *db = pParse->db;
117550 u32 savedDbFlags = db->mDbFlags;
117553 if( pParse->nErr ) return;
117554 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
117562 if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
117563 pParse->nErr++;
117566 pParse->nested++;
117569 db->mDbFlags |= DBFLAG_PreferBuiltin;
117571 db->mDbFlags = savedDbFlags;
117574 pParse->nested--;
117588 ** Locate the in-memory structure that describes a particular database
117608 if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
117613 for(i=0; i<db->nDb; i++){
117614 if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
117616 if( i>=db->nDb ){
117625 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
117632 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
117637 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
117644 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
117647 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
117650 for(i=2; i<db->nDb; i++){
117652 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
117657 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);
117659 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
117668 ** Locate the in-memory structure that describes a particular database
117671 ** error message in pParse->zErrMsg.
117674 ** routine leaves an error message in pParse->zErrMsg where
117684 sqlite3 *db = pParse->db;
117688 if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
117700 if( (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)==0 && db->init.busy==0 ){
117701 Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
117706 testcase( pMod->pEpoTab==0 );
117707 return pMod->pEpoTab;
117712 pParse->checkSchema = 1;
117713 }else if( IsVirtual(p) && (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)!=0 ){
117725 assert( HasRowid(p) || p->iPKey<0 );
117736 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
117737 ** non-NULL if it is part of a view or trigger program definition. See
117746 assert( p->pSchema==0 || p->zDatabase==0 );
117747 if( p->pSchema ){
117748 int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
117749 zDb = pParse->db->aDb[iDb].zDbSName;
117751 zDb = p->zDatabase;
117753 return sqlite3LocateTable(pParse, flags, p->zName, zDb);
117773 ** Locate the in-memory structure that describes
117789 for(i=OMIT_TEMPDB; i<db->nDb; i++){
117791 Schema *pSchema = db->aDb[j].pSchema;
117795 p = sqlite3HashFind(&pSchema->idxHash, zName);
117808 sqlite3ExprDelete(db, p->pPartIdxWhere);
117809 sqlite3ExprListDelete(db, p->aColExpr);
117810 sqlite3DbFree(db, p->zColAff);
117811 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
117813 sqlite3_free(p->aiRowEst);
117829 pHash = &db->aDb[iDb].pSchema->idxHash;
117832 if( pIndex->pTable->pIndex==pIndex ){
117833 pIndex->pTable->pIndex = pIndex->pNext;
117838 p = pIndex->pTable->pIndex;
117839 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
117840 if( ALWAYS(p && p->pNext==pIndex) ){
117841 p->pNext = pIndex->pNext;
117846 db->mDbFlags |= DBFLAG_SchemaChange;
117850 ** Look through the list of open database files in db->aDb[] and if
117852 ** db->aDb[] structure to a smaller size, if possible.
117859 for(i=j=2; i<db->nDb; i++){
117860 struct Db *pDb = &db->aDb[i];
117861 if( pDb->pBt==0 ){
117862 sqlite3DbFree(db, pDb->zDbSName);
117863 pDb->zDbSName = 0;
117867 db->aDb[j] = db->aDb[i];
117871 db->nDb = j;
117872 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
117873 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
117874 sqlite3DbFree(db, db->aDb);
117875 db->aDb = db->aDbStatic;
117881 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
117886 assert( iDb<db->nDb );
117892 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
117895 if( db->nSchemaLock==0 ){
117896 for(i=0; i<db->nDb; i++){
117898 sqlite3SchemaClear(db->aDb[i].pSchema);
117911 for(i=0; i<db->nDb; i++){
117912 Db *pDb = &db->aDb[i];
117913 if( pDb->pSchema ){
117914 if( db->nSchemaLock==0 ){
117915 sqlite3SchemaClear(pDb->pSchema);
117921 db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
117924 if( db->nSchemaLock==0 ){
117933 db->mDbFlags &= ~DBFLAG_SchemaChange;
117949 pList = pTab->u.tab.pDfltList;
117950 if( pCol->iDflt==0
117952 || NEVER(pList->nExpr<pCol->iDflt)
117954 pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;
117955 pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);
117957 sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);
117958 pList->a[pCol->iDflt-1].pExpr = pExpr;
117968 if( pCol->iDflt==0 ) return 0;
117970 if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
117971 if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
117972 return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
117987 n = sqlite3Strlen30(pCol->zCnName) + 1;
117988 if( pCol->colFlags & COLFLAG_HASTYPE ){
117989 n += sqlite3Strlen30(pCol->zCnName+n) + 1;
117992 zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);
117994 pCol->zCnName = zNew;
117995 memcpy(pCol->zCnName + n, zColl, nColl);
117996 pCol->colFlags |= COLFLAG_HASCOLL;
118005 if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;
118006 z = pCol->zCnName;
118008 if( pCol->colFlags & COLFLAG_HASTYPE ){
118023 if( (pCol = pTable->aCol)!=0 ){
118024 for(i=0; i<pTable->nCol; i++, pCol++){
118025 assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );
118026 sqlite3DbFree(db, pCol->zCnName);
118028 sqlite3DbNNFreeNN(db, pTable->aCol);
118030 sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);
118032 if( db->pnBytesFreed==0 ){
118033 pTable->aCol = 0;
118034 pTable->nCol = 0;
118036 pTable->u.tab.pDfltList = 0;
118054 ** db parameter can be used with db->pnBytesFreed to measure the memory
118070 if( !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
118076 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
118077 pNext = pIndex->pNext;
118078 assert( pIndex->pSchema==pTable->pSchema
118079 || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
118080 if( db->pnBytesFreed==0 && !IsVirtual(pTable) ){
118081 char *zName = pIndex->zName;
118083 &pIndex->pSchema->idxHash, zName, 0
118085 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
118101 sqlite3SelectDelete(db, pTable->u.view.pSelect);
118107 sqlite3DbFree(db, pTable->zName);
118108 sqlite3DbFree(db, pTable->zColAff);
118109 sqlite3ExprListDelete(db, pTable->pCheck);
118119 if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;
118133 assert( iDb>=0 && iDb<db->nDb );
118136 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
118137 pDb = &db->aDb[iDb];
118138 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
118140 u8 tableType = p->eTabType;
118143 db->mDbFlags |= DBFLAG_SchemaChange;
118146 db->isDropTable = 1;
118147 db->mDropTableName = sqlite3_malloc(strlen(zTabName) + 1);
118148 if( db->mDropTableName!=NULL ){
118149 memcpy(db->mDropTableName, zTabName, strlen(zTabName) + 1);
118151 db->mDropSchemaName = sqlite3_malloc(strlen(db->aDb[iDb].zDbSName) + 1);
118152 if( db->mDropSchemaName!=NULL ){
118153 memcpy(db->mDropSchemaName, db->aDb[iDb].zDbSName, strlen(db->aDb[iDb].zDbSName) + 1);
118175 zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);
118191 if( p->nTab==0 ){
118192 p->nTab = 1;
118197 ** Parameter zName points to a nul-terminated buffer containing the name
118199 ** function returns the index of the named database in db->aDb[], or
118200 ** -1 if the named db cannot be found.
118203 int i = -1; /* Database number */
118206 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
118207 if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
118219 ** index of the named database in db->aDb[], or -1 if the named db
118254 sqlite3 *db = pParse->db;
118257 if( pName2->n>0 ){
118258 if( db->init.busy ) {
118260 return -1;
118266 return -1;
118269 assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE
118270 || (db->mDbFlags & DBFLAG_Vacuum)!=0);
118271 iDb = db->init.iDb;
118281 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
118282 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
118284 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
118286 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
118288 return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
118292 ** This routine is used to check if the UTF-8 string zName is a legal
118308 sqlite3 *db = pParse->db;
118310 || db->init.imposterTable
118316 if( db->init.busy ){
118317 if( sqlite3_stricmp(zType, db->init.azInit[0])
118318 || sqlite3_stricmp(zName, db->init.azInit[1])
118319 || sqlite3_stricmp(zTblName, db->init.azInit[2])
118325 if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
118342 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
118349 ** find the (first) offset of that column in index pIdx. Or return -1
118354 for(i=0; i<pIdx->nColumn; i++){
118355 if( iCol==pIdx->aiColumn[i] ) return i;
118357 return -1;
118370 ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
118373 if( pTab->tabFlags & TF_HasVirtual ){
118376 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
118388 ** the N-th virtual column (zero-based) then the storage number is
118389 ** the number of non-virtual columns in the table plus N.
118405 ** -- 0 1 2 3 4 5 6 7 8
118416 ** this routine is a no-op macro. If the pTab does not have any virtual
118417 ** columns, then this routine is no-op that always return iCol. If iCol
118423 assert( iCol<pTab->nCol );
118424 if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
118426 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
118428 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
118430 return pTab->nNVCol + i - n;
118444 ** is a read-only no-op.
118447 int iReg = ++pParse->nMem;
118465 ** The new table record is initialized and put in pParse->pNewTable.
118482 sqlite3 *db = pParse->db;
118487 if( db->init.busy && db->init.newTnum==1 ){
118489 iDb = db->init.iDb;
118496 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
118508 pParse->sNameToken = *pName;
118513 if( db->init.iDb==1 ) isTemp = 1;
118524 char *zDb = db->aDb[iDb].zDbSName;
118543 char *zDb = db->aDb[iDb].zDbSName;
118553 assert( !db->init.busy || CORRUPT_DB );
118567 assert( db->mallocFailed );
118568 pParse->rc = SQLITE_NOMEM_BKPT;
118569 pParse->nErr++;
118572 pTable->zName = zName;
118573 pTable->iPKey = -1;
118574 pTable->pSchema = db->aDb[iDb].pSchema;
118575 pTable->nTabRef = 1;
118577 pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
118579 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
118581 assert( pParse->pNewTable==0 );
118582 pParse->pNewTable = pTable;
118592 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
118609 reg1 = pParse->regRowid = ++pParse->nMem;
118610 reg2 = pParse->regRoot = ++pParse->nMem;
118611 reg3 = ++pParse->nMem;
118615 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
118621 /* This just creates a place-holder record in the sqlite_schema table.
118625 ** The rowid for the new entry is left in register pParse->regRowid.
118626 ** The root page number of the new table is left in reg pParse->regRoot.
118636 assert( !pParse->bReturning );
118637 pParse->u1.addrCrTab =
118648 /* Normal (non-error) return. */
118653 pParse->checkSchema = 1;
118663 if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){
118664 pCol->colFlags |= COLFLAG_HIDDEN;
118665 if( pTab ) pTab->tabFlags |= TF_HasHidden;
118666 }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
118667 pTab->tabFlags |= TF_OOOHidden;
118675 ** with any application-generated triggers.
118684 pHash = &(db->aDb[1].pSchema->trigHash);
118686 sqlite3ExprListDelete(db, pRet->pReturnEL);
118709 sqlite3 *db = pParse->db;
118710 if( pParse->pNewTrigger ){
118713 assert( pParse->bReturning==0 );
118715 pParse->bReturning = 1;
118721 pParse->u1.pReturning = pRet;
118722 pRet->pParse = pParse;
118723 pRet->pReturnEL = pList;
118726 testcase( pParse->earlyCleanup );
118727 if( db->mallocFailed ) return;
118728 pRet->retTrig.zName = RETURNING_TRIGGER_NAME;
118729 pRet->retTrig.op = TK_RETURNING;
118730 pRet->retTrig.tr_tm = TRIGGER_AFTER;
118731 pRet->retTrig.bReturning = 1;
118732 pRet->retTrig.pSchema = db->aDb[1].pSchema;
118733 pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
118734 pRet->retTrig.step_list = &pRet->retTStep;
118735 pRet->retTStep.op = TK_RETURNING;
118736 pRet->retTStep.pTrig = &pRet->retTrig;
118737 pRet->retTStep.pExprList = pList;
118738 pHash = &(db->aDb[1].pSchema->trigHash);
118739 assert( sqlite3HashFind(pHash, RETURNING_TRIGGER_NAME)==0 || pParse->nErr );
118740 if( sqlite3HashInsert(pHash, RETURNING_TRIGGER_NAME, &pRet->retTrig)
118741 ==&pRet->retTrig ){
118760 sqlite3 *db = pParse->db;
118767 if( (p = pParse->pNewTable)==0 ) return;
118768 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
118769 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
118779 && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
118781 sType.n -= 6;
118782 while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
118784 && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
118786 sType.n -= 9;
118787 while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
118816 for(i=0; i<p->nCol; i++){
118817 if( p->aCol[i].hName==hName && sqlite3StrICmp(z, p->aCol[i].zCnName)==0 ){
118823 aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
118828 p->aCol = aNew;
118829 pCol = &p->aCol[p->nCol];
118830 memset(pCol, 0, sizeof(p->aCol[0]));
118831 pCol->zCnName = z;
118832 pCol->hName = hName;
118838 pCol->affinity = affinity;
118839 pCol->eCType = eType;
118840 pCol->szEst = szEst;
118844 pCol->colFlags |= COLFLAG_SORTERREF;
118853 pCol->affinity = sqlite3AffinityType(zType, pCol);
118854 pCol->colFlags |= COLFLAG_HASTYPE;
118856 p->nCol++;
118857 p->nNVCol++;
118858 pParse->constraintName.n = 0;
118870 p = pParse->pNewTable;
118871 if( p==0 || NEVER(p->nCol<1) ) return;
118872 pCol = &p->aCol[p->nCol-1];
118873 pCol->notNull = (u8)onError;
118874 p->tabFlags |= TF_HasNotNull;
118878 if( pCol->colFlags & COLFLAG_UNIQUE ){
118880 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
118881 assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
118882 if( pIdx->aiColumn[0]==p->nCol-1 ){
118883 pIdx->uniqNotNull = 1;
118893 ** This routine does a case-independent search of zType for the
118901 ** --------------------------------
118959 /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
118966 v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
118971 pCol->colFlags |= COLFLAG_SORTERREF;
118976 pCol->szEst = v;
118999 sqlite3 *db = pParse->db;
119000 p = pParse->pNewTable;
119002 int isInit = db->init.busy && db->init.iDb!=1;
119003 pCol = &(p->aCol[p->nCol-1]);
119006 pCol->zCnName);
119008 }else if( pCol->colFlags & COLFLAG_GENERATED ){
119009 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
119010 testcase( pCol->colFlags & COLFLAG_STORED );
119051 if( p->op==TK_STRING ){
119052 p->op = TK_ID;
119053 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
119054 p->pLeft->op = TK_ID;
119062 pCol->colFlags |= COLFLAG_PRIMKEY;
119064 if( pCol->colFlags & COLFLAG_GENERATED ){
119065 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
119066 testcase( pCol->colFlags & COLFLAG_STORED );
119085 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
119098 Table *pTab = pParse->pNewTable;
119100 int iCol = -1, i;
119103 if( pTab->tabFlags & TF_HasPrimaryKey ){
119105 "table \"%s\" has more than one primary key", pTab->zName);
119108 pTab->tabFlags |= TF_HasPrimaryKey;
119110 iCol = pTab->nCol - 1;
119111 pCol = &pTab->aCol[iCol];
119115 nTerm = pList->nExpr;
119117 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
119120 if( pCExpr->op==TK_ID ){
119123 zCName = pCExpr->u.zToken;
119124 for(iCol=0; iCol<pTab->nCol; iCol++){
119125 if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zCnName)==0 ){
119126 pCol = &pTab->aCol[iCol];
119136 && pCol->eCType==COLTYPE_INTEGER
119140 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
119141 sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
119143 pTab->iPKey = iCol;
119144 pTab->keyConf = (u8)onError;
119146 pTab->tabFlags |= autoInc*TF_Autoincrement;
119147 if( pList ) pParse->iPkSortOrder = pList->a[0].fg.sortFlags;
119161 sqlite3ExprListDelete(pParse->db, pList);
119175 Table *pTab = pParse->pNewTable;
119176 sqlite3 *db = pParse->db;
119178 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
119180 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
119181 if( pParse->constraintName.n ){
119182 sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
119186 while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
119188 t.n = (int)(zEnd - t.z);
119189 sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
119194 sqlite3ExprDelete(pParse->db, pCheckExpr);
119208 if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
119209 i = p->nCol-1;
119210 db = pParse->db;
119216 sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
119222 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
119223 assert( pIdx->nKeyCol==1 );
119224 if( pIdx->aiColumn[0]==i ){
119225 pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
119238 Table *pTab = pParse->pNewTable;
119244 pCol = &(pTab->aCol[pTab->nCol-1]);
119249 if( pCol->iDflt>0 ) goto generated_error;
119251 if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
119252 /* no-op */
119253 }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
119259 if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
119260 pCol->colFlags |= eType;
119263 pTab->tabFlags |= eType;
119264 if( pCol->colFlags & COLFLAG_PRIMKEY ){
119273 pCol->zCnName);
119275 sqlite3ExprDelete(pParse->db, pExpr);
119278 ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
119280 sqlite3ExprDelete(pParse->db, pExpr);
119294 ** This plan is not completely bullet-proof. It is possible for
119300 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
119301 ** the schema-version whenever the schema changes.
119304 sqlite3 *db = pParse->db;
119305 Vdbe *v = pParse->pVdbe;
119308 (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
119331 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
119335 ** If the string zSignedIdent consists entirely of alpha-numeric
119338 ** it is quoted using double-quotes.
119374 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
119375 n += identLength(pCol->zCnName) + 5;
119377 n += identLength(p->zName);
119387 n += 35 + 6*p->nCol;
119395 identPut(zStmt, &k, p->zName);
119397 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
119408 sqlite3_snprintf(n-k, &zStmt[k], zSep);
119411 identPut(zStmt, &k, pCol->zCnName);
119412 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
119413 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
119414 testcase( pCol->affinity==SQLITE_AFF_BLOB );
119415 testcase( pCol->affinity==SQLITE_AFF_TEXT );
119416 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
119417 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
119418 testcase( pCol->affinity==SQLITE_AFF_REAL );
119420 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
119422 assert( pCol->affinity==SQLITE_AFF_BLOB
119423 || pCol->affinity==sqlite3AffinityType(zType, 0) );
119428 sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
119439 if( pIdx->nColumn>=N ) return SQLITE_OK;
119440 assert( pIdx->isResized==0 );
119444 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
119445 pIdx->azColl = (const char**)zExtra;
119447 memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
119448 pIdx->aiRowLogEst = (LogEst*)zExtra;
119450 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
119451 pIdx->aiColumn = (i16*)zExtra;
119453 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
119454 pIdx->aSortOrder = (u8*)zExtra;
119455 pIdx->nColumn = N;
119456 pIdx->isResized = 1;
119467 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
119468 wTable += pTabCol->szEst;
119470 if( pTab->iPKey<0 ) wTable++;
119471 pTab->szTabRow = sqlite3LogEst(wTable*4);
119480 const Column *aCol = pIdx->pTable->aCol;
119481 for(i=0; i<pIdx->nColumn; i++){
119482 i16 x = pIdx->aiColumn[i];
119483 assert( x<pIdx->pTable->nCol );
119484 wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
119486 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
119494 while( nCol-- > 0 ){
119504 ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
119517 assert( nKey<=pIdx->nColumn );
119518 assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
119519 assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
119520 assert( pPk->pTable->tabFlags & TF_WithoutRowid );
119521 assert( pPk->pTable==pIdx->pTable );
119523 j = pPk->aiColumn[iCol];
119526 assert( pIdx->aiColumn[i]>=0 || j>=0 );
119527 if( pIdx->aiColumn[i]==j
119528 && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
119541 ** high-order bit of colNotIdxed is always 1. All unindexed columns
119544 ** 2019-10-24: For the purpose of this computation, virtual columns are
119552 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
119558 Table *pTab = pIdx->pTable;
119559 for(j=pIdx->nColumn-1; j>=0; j--){
119560 int x = pIdx->aiColumn[j];
119561 if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
119562 testcase( x==BMS-1 );
119563 testcase( x==BMS-2 );
119564 if( x<BMS-1 ) m |= MASKBIT(x);
119567 pIdx->colNotIdxed = ~m;
119568 assert( (pIdx->colNotIdxed>>63)==1 ); /* See note-20221022-a */
119601 sqlite3 *db = pParse->db;
119602 Vdbe *v = pParse->pVdbe;
119606 if( !db->init.imposterTable ){
119607 for(i=0; i<pTab->nCol; i++){
119608 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
119609 && (pTab->aCol[i].notNull==OE_None)
119611 pTab->aCol[i].notNull = OE_Abort;
119614 pTab->tabFlags |= TF_HasNotNull;
119620 assert( !pParse->bReturning );
119621 if( pParse->u1.addrCrTab ){
119623 sqlite3VdbeChangeP3(v, pParse->u1.addrCrTab, BTREE_BLOBKEY);
119629 if( pTab->iPKey>=0 ){
119632 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
119636 pTab->tabFlags &= ~TF_WithoutRowid;
119640 sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
119642 pList->a[0].fg.sortFlags = pParse->iPkSortOrder;
119643 assert( pParse->pNewTable==pTab );
119644 pTab->iPKey = -1;
119645 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
119647 if( pParse->nErr ){
119648 pTab->tabFlags &= ~TF_WithoutRowid;
119651 assert( db->mallocFailed==0 );
119653 assert( pPk->nKeyCol==1 );
119663 for(i=j=1; i<pPk->nKeyCol; i++){
119665 pPk->nColumn--;
119667 testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
119668 pPk->azColl[j] = pPk->azColl[i];
119669 pPk->aSortOrder[j] = pPk->aSortOrder[i];
119670 pPk->aiColumn[j++] = pPk->aiColumn[i];
119673 pPk->nKeyCol = j;
119676 pPk->isCovering = 1;
119677 if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
119678 nPk = pPk->nColumn = pPk->nKeyCol;
119684 if( v && pPk->tnum>0 ){
119685 assert( db->init.busy==0 );
119686 sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
119690 pPk->tnum = pTab->tnum;
119692 /* Update the in-memory representation of all UNIQUE indices by converting
119695 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
119699 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
119700 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
119706 pIdx->nColumn = pIdx->nKeyCol;
119709 if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
119710 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
119711 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
119712 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
119713 pIdx->aiColumn[j] = pPk->aiColumn[i];
119714 pIdx->azColl[j] = pPk->azColl[i];
119715 if( pPk->aSortOrder[i] ){
119717 pIdx->bAscKeyBug = 1;
119722 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
119723 assert( pIdx->nColumn>=j );
119729 for(i=0; i<pTab->nCol; i++){
119730 if( !hasColumn(pPk->aiColumn, nPk, i)
119731 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
119734 for(i=0, j=nPk; i<pTab->nCol; i++){
119735 if( !hasColumn(pPk->aiColumn, j, i)
119736 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
119738 assert( j<pPk->nColumn );
119739 pPk->aiColumn[j] = i;
119740 pPk->azColl[j] = sqlite3StrBINARY;
119744 assert( pPk->nColumn==j );
119745 assert( pTab->nNVCol<=j );
119760 nName = sqlite3Strlen30(pTab->zName);
119761 if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
119763 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
119765 if( pMod->pModule->iVersion<3 ) return 0;
119766 if( pMod->pModule->xShadowName==0 ) return 0;
119767 return pMod->pModule->xShadowName(zName+nName+1);
119779 int nName; /* Length of pTab->zName */
119784 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
119786 if( NEVER(pMod->pModule==0) ) return;
119787 if( pMod->pModule->iVersion<3 ) return;
119788 if( pMod->pModule->xShadowName==0 ) return;
119789 assert( pTab->zName!=0 );
119790 nName = sqlite3Strlen30(pTab->zName);
119791 for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
119793 assert( pOther->zName!=0 );
119795 if( pOther->tabFlags & TF_Shadow ) continue;
119796 if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
119797 && pOther->zName[nName]=='_'
119798 && pMod->pModule->xShadowName(pOther->zName+nName+1)
119800 pOther->tabFlags |= TF_Shadow;
119851 #define markExprListImmutable(X) /* no-op */
119864 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
119883 sqlite3 *db = pParse->db; /* The database connection */
119890 p = pParse->pNewTable;
119893 if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
119894 p->tabFlags |= TF_Shadow;
119897 /* If the db->init.busy is 1 it means we are reading the SQL off the
119900 ** for the table from the db->init.newTnum field. (The page number
119904 ** table itself. So mark it read-only.
119906 if( db->init.busy ){
119907 if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
119911 p->tnum = db->init.newTnum;
119912 if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
119926 p->tabFlags |= TF_Strict;
119927 for(ii=0; ii<p->nCol; ii++){
119928 Column *pCol = &p->aCol[ii];
119929 if( pCol->eCType==COLTYPE_CUSTOM ){
119930 if( pCol->colFlags & COLFLAG_HASTYPE ){
119933 p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
119937 p->zName, pCol->zCnName);
119940 }else if( pCol->eCType==COLTYPE_ANY ){
119941 pCol->affinity = SQLITE_AFF_BLOB;
119943 if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
119944 && p->iPKey!=ii
119945 && pCol->notNull == OE_None
119947 pCol->notNull = OE_Abort;
119948 p->tabFlags |= TF_HasNotNull;
119953 assert( (p->tabFlags & TF_HasPrimaryKey)==0
119954 || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
119955 assert( (p->tabFlags & TF_HasPrimaryKey)!=0
119956 || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
119960 if( (p->tabFlags & TF_Autoincrement) ){
119965 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
119966 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
119969 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
119972 iDb = sqlite3SchemaToIndex(db, p->pSchema);
119977 if( p->pCheck ){
119978 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
119979 if( pParse->nErr ){
119982 sqlite3ExprListDelete(db, p->pCheck);
119983 p->pCheck = 0;
119985 markExprListImmutable(p->pCheck);
119990 if( p->tabFlags & TF_HasGenerated ){
119992 testcase( p->tabFlags & TF_HasVirtual );
119993 testcase( p->tabFlags & TF_HasStored );
119994 for(ii=0; ii<p->nCol; ii++){
119995 u32 colFlags = p->aCol[ii].colFlags;
119997 Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
120007 sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
120015 sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
120023 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
120033 if( !db->init.busy ){
120061 ** statement to populate the new table. The root-page number for the
120062 ** new table is in register pParse->regRoot.
120068 ** A shared-cache write-lock is not required to write to the new table,
120069 ** as a schema-lock must have already been obtained to create it. Since
120070 ** a schema-lock excludes all other database users, the write-lock would
120075 int regYield; /* Register holding co-routine entry-point */
120076 int addrTop; /* Top of the co-routine */
120083 pParse->rc = SQLITE_ERROR;
120084 pParse->nErr++;
120087 regYield = ++pParse->nMem;
120088 regRec = ++pParse->nMem;
120089 regRowid = ++pParse->nMem;
120090 assert(pParse->nTab==1);
120092 sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
120094 pParse->nTab = 2;
120097 if( pParse->nErr ) return;
120100 assert( p->aCol==0 );
120101 p->nCol = p->nNVCol = pSelTab->nCol;
120102 p->aCol = pSelTab->aCol;
120103 pSelTab->nCol = 0;
120104 pSelTab->aCol = 0;
120108 if( pParse->nErr ) return;
120110 sqlite3VdbeJumpHere(v, addrTop - 1);
120126 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
120127 n = (int)(pEnd2->z - pParse->sNameToken.z);
120128 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
120130 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
120142 db->aDb[iDb].zDbSName,
120144 p->zName,
120145 p->zName,
120146 pParse->regRoot,
120148 pParse->regRowid
120157 if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
120158 Db *pDb = &db->aDb[iDb];
120160 if( pDb->pSchema->pSeqTab==0 ){
120163 pDb->zDbSName
120171 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
120174 /* Add the table to the in-memory representation of the database.
120176 if( db->init.busy ){
120178 Schema *pSchema = p->pSchema;
120180 assert( HasRowid(p) || p->iPKey<0 );
120181 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
120187 pParse->pNewTable = 0;
120188 db->mDbFlags |= DBFLAG_SchemaChange;
120193 assert( !pParse->nested );
120195 if( strcmp(p->zName, "sqlite_sequence")==0 ){
120197 p->pSchema->pSeqTab = p;
120205 if( pCons->z==0 ){
120208 p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
120234 sqlite3 *db = pParse->db;
120236 if( pParse->nVar>0 ){
120241 p = pParse->pNewTable;
120242 if( p==0 || pParse->nErr ) goto create_view_fail;
120247 ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
120250 p->tabFlags |= TF_NoVisibleRowid;
120254 iDb = sqlite3SchemaToIndex(db, p->pSchema);
120260 ** allocated rather than point to the input string - which means that
120263 pSelect->selFlags |= SF_View;
120265 p->u.view.pSelect = pSelect;
120268 p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
120270 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
120271 p->eTabType = TABTYP_VIEW;
120272 if( db->mallocFailed ) goto create_view_fail;
120277 sEnd = pParse->sLastToken;
120283 n = (int)(sEnd.z - pBegin->z);
120285 z = pBegin->z;
120286 while( sqlite3Isspace(z[n-1]) ){ n--; }
120287 sEnd.z = &z[n-1];
120307 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
120313 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
120325 db->nSchemaLock++;
120327 db->nSchemaLock--;
120337 assert( pTable->nCol<=0 );
120354 if( pTable->nCol<0 ){
120355 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
120358 assert( pTable->nCol>=0 );
120368 pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
120370 u8 eParseMode = pParse->eParseMode;
120371 int nTab = pParse->nTab;
120372 int nSelect = pParse->nSelect;
120373 pParse->eParseMode = PARSE_MODE_NORMAL;
120374 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
120375 pTable->nCol = -1;
120378 xAuth = db->xAuth;
120379 db->xAuth = 0;
120381 db->xAuth = xAuth;
120385 pParse->nTab = nTab;
120386 pParse->nSelect = nSelect;
120388 pTable->nCol = 0;
120390 }else if( pTable->pCheck ){
120393 ** arglist which is stored in pTable->pCheck. The pCheck field
120397 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
120398 &pTable->nCol, &pTable->aCol);
120399 if( pParse->nErr==0
120400 && pTable->nCol==pSel->pEList->nExpr
120402 assert( db->mallocFailed==0 );
120410 assert( pTable->aCol==0 );
120411 pTable->nCol = pSelTab->nCol;
120412 pTable->aCol = pSelTab->aCol;
120413 pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
120414 pSelTab->nCol = 0;
120415 pSelTab->aCol = 0;
120416 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
120418 pTable->nNVCol = pTable->nCol;
120422 pParse->eParseMode = eParseMode;
120426 pTable->pSchema->schemaFlags |= DB_UnresetViews;
120427 if( db->mallocFailed ){
120435 if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
120448 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
120463 ** root-page of a table or index in database iDb has changed from iFrom
120484 pDb = &db->aDb[iDb];
120485 pHash = &pDb->pSchema->tblHash;
120488 if( pTab->tnum==iFrom ){
120489 pTab->tnum = iTo;
120492 pHash = &pDb->pSchema->idxHash;
120495 if( pIdx->tnum==iFrom ){
120496 pIdx->tnum = iTo;
120503 ** Write code to erase the table with root-page iTable from database iDb.
120505 ** if a root-page of another table is moved by the btree-layer whilst
120506 ** erasing iTable (this can happen with an auto-vacuum database).
120516 ** is non-zero, then it is the root page number of a table moved to
120527 pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
120535 ** in case a root-page belonging to another table is moved by the btree layer
120536 ** is also added (this can happen with an auto-vacuum database).
120539 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
120541 ** table and index root-pages in order, starting with the numerically
120542 ** largest root-page number. This guarantees that none of the root-pages
120550 ** and root page 5 happened to be the largest root-page number in the
120553 ** a free-list page.
120555 Pgno iTab = pTab->tnum;
120565 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
120566 Pgno iIdx = pIdx->tnum;
120567 assert( pIdx->pSchema==pTab->pSchema );
120575 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
120576 assert( iDb>=0 && iDb<pParse->db->nDb );
120594 const char *zDbName = pParse->db->aDb[iDb].zDbSName;
120598 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
120612 sqlite3 *db = pParse->db;
120614 Db *pDb = &db->aDb[iDb];
120632 assert( pTrigger->pSchema==pTab->pSchema ||
120633 pTrigger->pSchema==db->aDb[1].pSchema );
120635 pTrigger = pTrigger->pNext;
120642 ** move as a result of the drop (can happen in auto-vacuum mode).
120644 if( pTab->tabFlags & TF_Autoincrement ){
120647 pDb->zDbSName, pTab->zName
120662 pDb->zDbSName, pTab->zName);
120671 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
120674 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
120680 ** Return TRUE if shadow tables should be read-only in the current
120685 if( (db->flags & SQLITE_Defensive)!=0
120686 && db->pVtabCtx==0
120687 && db->nVdbeExec==0
120700 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
120701 if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
120702 if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
120705 if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
120708 if( pTab->tabFlags & TF_Eponymous ){
120721 sqlite3 *db = pParse->db;
120724 if( db->mallocFailed ){
120727 assert( pParse->nErr==0 );
120728 assert( pName->nSrc==1 );
120730 if( noErr ) db->suppressErr++;
120732 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
120733 if( noErr ) db->suppressErr--;
120737 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
120742 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
120743 assert( iDb>=0 && iDb<db->nDb );
120755 const char *zDb = db->aDb[iDb].zDbSName;
120769 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
120778 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
120781 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
120787 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
120796 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
120800 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
120812 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
120833 ** under construction in the pParse->pNewTable field.
120845 sqlite3 *db = pParse->db;
120849 Table *p = pParse->pNewTable;
120858 int iCol = p->nCol-1;
120860 if( pToCol && pToCol->nExpr!=1 ){
120863 p->aCol[iCol].zCnName, pTo);
120867 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
120873 nCol = pFromCol->nExpr;
120875 nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
120877 for(i=0; i<pToCol->nExpr; i++){
120878 nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
120885 pFKey->pFrom = p;
120887 pFKey->pNextFrom = p->u.tab.pFKey;
120888 z = (char*)&pFKey->aCol[nCol];
120889 pFKey->zTo = z;
120893 memcpy(z, pTo->z, pTo->n);
120894 z[pTo->n] = 0;
120896 z += pTo->n+1;
120897 pFKey->nCol = nCol;
120899 pFKey->aCol[0].iFrom = p->nCol-1;
120903 for(j=0; j<p->nCol; j++){
120904 if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
120905 pFKey->aCol[i].iFrom = j;
120909 if( j>=p->nCol ){
120912 pFromCol->a[i].zEName);
120916 sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
120922 int n = sqlite3Strlen30(pToCol->a[i].zEName);
120923 pFKey->aCol[i].zCol = z;
120925 sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
120927 memcpy(z, pToCol->a[i].zEName, n);
120932 pFKey->isDeferred = 0;
120933 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
120934 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
120936 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
120937 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
120938 pFKey->zTo, (void *)pFKey
120945 assert( pNextTo->pPrevTo==0 );
120946 pFKey->pNextTo = pNextTo;
120947 pNextTo->pPrevTo = pFKey;
120953 p->u.tab.pFKey = pFKey;
120974 if( (pTab = pParse->pNewTable)==0 ) return;
120976 if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
120977 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
120978 pFKey->isDeferred = (u8)isDeferred;
120991 ** the root page number of the index is taken from pIndex->tnum.
120994 Table *pTab = pIndex->pTable; /* The table that is indexed */
120995 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
120996 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
121005 sqlite3 *db = pParse->db; /* The database connection */
121006 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
121009 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
121010 db->aDb[iDb].zDbSName ) ){
121015 /* Require a write-lock on the table to perform this operation */
121016 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
121023 tnum = pIndex->tnum;
121026 assert( pKey!=0 || pParse->nErr );
121029 iSorter = pParse->nTab++;
121030 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
121056 pIndex->nKeyCol); VdbeCoverage(v);
121071 if( !pIndex->bAscKeyBug ){
121096 ** of 8-byte aligned space after the Index object and return a
121116 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
121117 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
121118 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
121119 p->aSortOrder = (u8*)pExtra;
121120 p->nColumn = nCol;
121121 p->nKeyCol = nCol - 1;
121130 ** pParse and return non-zero. Otherwise, return zero.
121135 for(i=0; i<pList->nExpr; i++){
121136 if( pList->a[i].fg.bNulls ){
121137 u8 sf = pList->a[i].fg.sortFlags;
121152 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
121153 ** as the table to be indexed. pParse->pNewTable is a table that is
121157 ** is a primary key or unique-constraint on the most recent column added
121164 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
121180 sqlite3 *db = pParse->db;
121190 assert( db->pParse==pParse );
121191 if( pParse->nErr ){
121194 assert( db->mallocFailed==0 );
121210 /* Use the two-part index name to determine the database
121217 assert( pName && pName->z );
121224 if( !db->init.busy ){
121226 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
121238 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
121239 assert( db->mallocFailed==0 || pTab==0 );
121241 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
121243 "cannot create a TEMP index on non-TEMP table \"%s\"",
121244 pTab->zName);
121251 pTab = pParse->pNewTable;
121253 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
121255 pDb = &db->aDb[iDb];
121258 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
121259 && db->init.busy==0
121262 && sqlite3UserAuthTable(pTab->zName)==0
121265 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
121297 assert( pName->z!=0 );
121298 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
121302 if( !db->init.busy ){
121303 if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
121308 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
121312 assert( !db->init.busy );
121322 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
121323 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
121340 const char *zDb = pDb->zDbSName;
121346 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
121358 Column *pCol = &pTab->aCol[pTab->nCol-1];
121359 pCol->colFlags |= COLFLAG_UNIQUE;
121360 sqlite3TokenInit(&prevCol, pCol->zCnName);
121364 assert( pList->nExpr==1 );
121368 if( pParse->nErr ) goto exit_create_index;
121374 for(i=0; i<pList->nExpr; i++){
121375 Expr *pExpr = pList->a[i].pExpr;
121377 if( pExpr->op==TK_COLLATE ){
121379 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
121387 nExtraCol = pPk ? pPk->nKeyCol : 1;
121388 assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
121389 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
121391 if( db->mallocFailed ){
121394 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
121395 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
121396 pIndex->zName = zExtra;
121398 memcpy(pIndex->zName, zName, nName+1);
121399 pIndex->pTable = pTab;
121400 pIndex->onError = (u8)onError;
121401 pIndex->uniqNotNull = onError!=OE_None;
121402 pIndex->idxType = idxType;
121403 pIndex->pSchema = db->aDb[iDb].pSchema;
121404 pIndex->nKeyCol = pList->nExpr;
121407 pIndex->pPartIdxWhere = pPIWhere;
121414 if( pDb->pSchema->file_format>=4 ){
121415 sortOrderMask = -1; /* Honor DESC */
121423 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
121429 pListItem = pList->a;
121431 pIndex->aColExpr = pList;
121434 for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
121435 Expr *pCExpr; /* The i-th index expression */
121436 int requestedSortOrder; /* ASC or DESC on the i-th expression */
121439 sqlite3StringToId(pListItem->pExpr);
121440 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
121441 if( pParse->nErr ) goto exit_create_index;
121442 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
121443 if( pCExpr->op!=TK_COLUMN ){
121444 if( pTab==pParse->pNewTable ){
121449 if( pIndex->aColExpr==0 ){
121450 pIndex->aColExpr = pList;
121454 pIndex->aiColumn[i] = XN_EXPR;
121455 pIndex->uniqNotNull = 0;
121456 pIndex->bHasExpr = 1;
121458 j = pCExpr->iColumn;
121461 j = pTab->iPKey;
121463 if( pTab->aCol[j].notNull==0 ){
121464 pIndex->uniqNotNull = 0;
121466 if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
121467 pIndex->bHasVCol = 1;
121468 pIndex->bHasExpr = 1;
121471 pIndex->aiColumn[i] = (i16)j;
121474 if( pListItem->pExpr->op==TK_COLLATE ){
121476 assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
121477 zColl = pListItem->pExpr->u.zToken;
121483 nExtra -= nColl;
121485 zColl = sqlite3ColumnColl(&pTab->aCol[j]);
121488 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
121491 pIndex->azColl[i] = zColl;
121492 requestedSortOrder = pListItem->fg.sortFlags & sortOrderMask;
121493 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
121501 for(j=0; j<pPk->nKeyCol; j++){
121502 int x = pPk->aiColumn[j];
121504 if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
121505 pIndex->nColumn--;
121507 testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
121508 pIndex->aiColumn[i] = x;
121509 pIndex->azColl[i] = pPk->azColl[j];
121510 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
121514 assert( i==pIndex->nColumn );
121516 pIndex->aiColumn[i] = XN_ROWID;
121517 pIndex->azColl[i] = sqlite3StrBINARY;
121520 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
121525 || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
121527 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
121528 pIndex->isCovering = 1;
121529 for(j=0; j<pTab->nCol; j++){
121530 if( j==pTab->iPKey ) continue;
121532 pIndex->isCovering = 0;
121537 if( pTab==pParse->pNewTable ){
121560 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
121563 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
121566 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
121567 for(k=0; k<pIdx->nKeyCol; k++){
121570 assert( pIdx->aiColumn[k]>=0 );
121571 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
121572 z1 = pIdx->azColl[k];
121573 z2 = pIndex->azColl[k];
121576 if( k==pIdx->nKeyCol ){
121577 if( pIdx->onError!=pIndex->onError ){
121585 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
121589 if( pIdx->onError==OE_Default ){
121590 pIdx->onError = pIndex->onError;
121593 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
121595 pIndex->pNext = pParse->pNewIndex;
121596 pParse->pNewIndex = pIndex;
121607 ** in-memory database structures.
121609 assert( pParse->nErr==0 );
121610 if( db->init.busy ){
121613 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
121615 pIndex->tnum = db->init.newTnum;
121618 pParse->rc = SQLITE_CORRUPT_BKPT;
121622 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
121623 pIndex->zName, pIndex);
121629 db->mDbFlags |= DBFLAG_SchemaChange;
121648 int iMem = ++pParse->nMem;
121661 pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
121669 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
121670 if( pName->z[n-1]==';' ) n--;
121673 onError==OE_None ? "" : " UNIQUE", n, pName->z);
121684 db->aDb[iDb].zDbSName,
121685 pIndex->zName,
121686 pTab->zName,
121693 ** to invalidate all pre-compiled statements.
121699 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
121703 sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
121706 if( db->init.busy || pTblName==0 ){
121707 pIndex->pNext = pTab->pIndex;
121708 pTab->pIndex = pIndex;
121712 assert( pParse->pNewIndex==0 );
121713 pParse->pNewIndex = pIndex;
121727 for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
121729 if( pThis->onError!=OE_Replace ) continue;
121730 while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
121732 pThis->pNext = pNext->pNext;
121733 pNext->pNext = pThis;
121734 ppFrom = &pNext->pNext;
121742 for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
121743 assert( pThis->onError!=OE_Replace
121744 || pThis->pNext==0
121745 || pThis->pNext->onError==OE_Replace );
121756 ** Fill the Index.aiRowEst[] array with default information - information
121766 ** aiRowEst[N]<=aiRowEst[N-1]
121776 LogEst *a = pIdx->aiRowLogEst;
121778 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
121782 assert( !pIdx->hasStat1 );
121788 ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1
121794 x = pIdx->pTable->nRowLogEst;
121797 pIdx->pTable->nRowLogEst = x = 99;
121799 if( pIdx->pPartIdxWhere!=0 ){ x -= 10; assert( 10==sqlite3LogEst(2) ); }
121805 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
121810 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
121820 sqlite3 *db = pParse->db;
121823 if( db->mallocFailed ){
121826 assert( pParse->nErr==0 ); /* Never called with prior non-OOM errors */
121827 assert( pName->nSrc==1 );
121831 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
121834 sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
121836 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
121839 pParse->checkSchema = 1;
121842 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
121847 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
121851 Table *pTab = pIndex->pTable;
121852 const char *zDb = db->aDb[iDb].zDbSName;
121858 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
121870 db->aDb[iDb].zDbSName, pIndex->zName
121872 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
121874 destroyRootPage(pParse, pIndex->tnum, iDb);
121875 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
121888 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
121896 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
121908 if( (n & (n-1))==0 ){
121912 *pIdx = -1;
121930 sqlite3 *db = pParse->db;
121938 sizeof(IdList) + pList->nId*sizeof(pList->a));
121945 i = pList->nId++;
121946 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
121947 if( IN_RENAME_OBJECT && pList->a[i].zName ){
121948 sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
121960 assert( pList->eU4!=EU4_EXPR ); /* EU4_EXPR mode is not currently used */
121961 for(i=0; i<pList->nId; i++){
121962 sqlite3DbFree(db, pList->a[i].zName);
121968 ** Return the index in pList of the identifier named zId. Return -1
121974 for(i=0; i<pList->nId; i++){
121975 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
121977 return -1;
121986 ** appropriate for small and memory-limited applications.
122015 int nExtra, /* Number of new slots to add to pSrc->a[] */
122016 int iStart /* Index in pSrc->a[] of first new slot */
122024 assert( iStart<=pSrc->nSrc );
122027 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
122029 sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
122030 sqlite3 *db = pParse->db;
122032 if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
122039 sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
122041 assert( db->mallocFailed );
122045 pSrc->nAlloc = nAlloc;
122050 for(i=pSrc->nSrc-1; i>=iStart; i--){
122051 pSrc->a[i+nExtra] = pSrc->a[i];
122053 pSrc->nSrc += nExtra;
122056 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
122058 pSrc->a[i].iCursor = -1;
122111 assert( pParse->db!=0 );
122112 db = pParse->db;
122114 pList = sqlite3DbMallocRawNN(pParse->db, sizeof(SrcList) );
122116 pList->nAlloc = 1;
122117 pList->nSrc = 1;
122118 memset(&pList->a[0], 0, sizeof(pList->a[0]));
122119 pList->a[0].iCursor = -1;
122121 SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
122129 pItem = &pList->a[pList->nSrc-1];
122130 if( pDatabase && pDatabase->z==0 ){
122134 pItem->zName = sqlite3NameFromToken(db, pDatabase);
122135 pItem->zDatabase = sqlite3NameFromToken(db, pTable);
122137 pItem->zName = sqlite3NameFromToken(db, pTable);
122138 pItem->zDatabase = 0;
122149 assert( pList || pParse->db->mallocFailed );
122151 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
122152 if( pItem->iCursor>=0 ) continue;
122153 pItem->iCursor = pParse->nTab++;
122154 if( pItem->pSelect ){
122155 sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
122169 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
122170 if( pItem->zDatabase ) sqlite3DbNNFreeNN(db, pItem->zDatabase);
122171 if( pItem->zName ) sqlite3DbNNFreeNN(db, pItem->zName);
122172 if( pItem->zAlias ) sqlite3DbNNFreeNN(db, pItem->zAlias);
122173 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
122174 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
122175 sqlite3DeleteTable(db, pItem->pTab);
122176 if( pItem->pSelect ) sqlite3SelectDelete(db, pItem->pSelect);
122177 if( pItem->fg.isUsing ){
122178 sqlite3IdListDelete(db, pItem->u3.pUsing);
122179 }else if( pItem->u3.pOn ){
122180 sqlite3ExprDelete(db, pItem->u3.pOn);
122192 ** pDatabase is NULL if the database name qualifier is missing - the
122207 Token *pAlias, /* The right-hand side of the AS subexpression */
122212 sqlite3 *db = pParse->db;
122213 if( !p && pOnUsing!=0 && (pOnUsing->pOn || pOnUsing->pUsing) ){
122215 (pOnUsing->pOn ? "ON" : "USING")
122223 assert( p->nSrc>0 );
122224 pItem = &p->a[p->nSrc-1];
122226 assert( pItem->zName==0 || pDatabase!=0 );
122227 if( IN_RENAME_OBJECT && pItem->zName ){
122228 Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
122229 sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
122232 if( pAlias->n ){
122233 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
122236 pItem->pSelect = pSubquery;
122237 if( pSubquery->selFlags & SF_NestedFrom ){
122238 pItem->fg.isNestedFrom = 1;
122241 assert( pOnUsing==0 || pOnUsing->pOn==0 || pOnUsing->pUsing==0 );
122242 assert( pItem->fg.isUsing==0 );
122244 pItem->u3.pOn = 0;
122245 }else if( pOnUsing->pUsing ){
122246 pItem->fg.isUsing = 1;
122247 pItem->u3.pUsing = pOnUsing->pUsing;
122249 pItem->u3.pOn = pOnUsing->pOn;
122262 ** element of the source-list passed as the second argument.
122266 if( p && pIndexedBy->n>0 ){
122268 assert( p->nSrc>0 );
122269 pItem = &p->a[p->nSrc-1];
122270 assert( pItem->fg.notIndexed==0 );
122271 assert( pItem->fg.isIndexedBy==0 );
122272 assert( pItem->fg.isTabFunc==0 );
122273 if( pIndexedBy->n==1 && !pIndexedBy->z ){
122276 pItem->fg.notIndexed = 1;
122278 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
122279 pItem->fg.isIndexedBy = 1;
122280 assert( pItem->fg.isCte==0 ); /* No collision on union u2 */
122291 assert( p1 && p1->nSrc==1 );
122293 SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
122295 sqlite3SrcListDelete(pParse->db, p2);
122298 memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));
122299 sqlite3DbFree(pParse->db, p2);
122300 p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);
122308 ** table-valued-function.
122312 SrcItem *pItem = &p->a[p->nSrc-1];
122313 assert( pItem->fg.notIndexed==0 );
122314 assert( pItem->fg.isIndexedBy==0 );
122315 assert( pItem->fg.isTabFunc==0 );
122316 pItem->u1.pFuncArg = pList;
122317 pItem->fg.isTabFunc = 1;
122319 sqlite3ExprListDelete(pParse->db, pList);
122335 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
122340 ** * All tables to the left of the right-most RIGHT JOIN are tagged with
122347 if( p && p->nSrc>1 ){
122348 int i = p->nSrc-1;
122351 allFlags |= p->a[i].fg.jointype = p->a[i-1].fg.jointype;
122352 }while( (--i)>0 );
122353 p->a[0].fg.jointype = 0;
122358 for(i=p->nSrc-1; ALWAYS(i>0) && (p->a[i].fg.jointype&JT_RIGHT)==0; i--){}
122359 i--;
122362 p->a[i].fg.jointype |= JT_LTORJ;
122363 }while( (--i)>=0 );
122377 db = pParse->db;
122385 for(i=0; i<db->nDb; i++){
122387 Btree *pBt = db->aDb[i].pBt;
122412 assert( pParse->db!=0 );
122430 char *zName = sqlite3NameFromToken(pParse->db, pName);
122438 sqlite3DbFree(pParse->db, zName);
122450 sqlite3 *db = pParse->db;
122451 if( db->aDb[1].pBt==0 && !pParse->explain ){
122461 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
122465 pParse->rc = rc;
122468 db->aDb[1].pBt = pBt;
122469 assert( db->aDb[1].pSchema );
122470 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
122481 ** will occur at the end of the top-level VDBE and will be generated
122485 assert( iDb>=0 && iDb<pToplevel->db->nDb );
122486 assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
122488 assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
122489 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
122490 DbMaskSet(pToplevel->cookieMask, iDb);
122506 sqlite3 *db = pParse->db;
122508 for(i=0; i<db->nDb; i++){
122509 Db *pDb = &db->aDb[i];
122510 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
122532 DbMaskSet(pToplevel->writeMask, iDb);
122533 pToplevel->isMultiWrite |= setStatement;
122545 pToplevel->isMultiWrite = 1;
122566 pToplevel->mayAbort = 1;
122583 assert( pParse->pVdbe!=0 );
122585 assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
122604 Table *pTab = pIdx->pTable;
122606 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
122607 pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
122608 if( pIdx->aColExpr ){
122609 sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
122611 for(j=0; j<pIdx->nKeyCol; j++){
122613 assert( pIdx->aiColumn[j]>=0 );
122614 zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
122616 sqlite3_str_appendall(&errMsg, pTab->zName);
122630 ** Code an OP_Halt due to non-unique rowid.
122635 Table *pTab /* The table with the non-unique rowid */
122639 if( pTab->iPKey>=0 ){
122640 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
122641 pTab->aCol[pTab->iPKey].zCnName);
122644 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
122659 for(i=0; i<pIndex->nColumn; i++){
122660 const char *z = pIndex->azColl[i];
122661 assert( z!=0 || pIndex->aiColumn[i]<0 );
122662 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
122679 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
122681 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
122683 sqlite3RefillIndex(pParse, pIndex, -1);
122699 sqlite3 *db = pParse->db; /* The database connection */
122704 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
122706 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
122717 ** REINDEX -- 1
122718 ** REINDEX <collation> -- 2
122719 ** REINDEX ?<database>.?<tablename> -- 3
122720 ** REINDEX ?<database>.?<indexname> -- 4
122735 sqlite3 *db = pParse->db; /* The database connection */
122747 }else if( NEVER(pName2==0) || pName2->z==0 ){
122749 assert( pName1->z );
122750 zColl = sqlite3NameFromToken(pParse->db, pName1);
122764 zDb = db->aDb[iDb].zDbSName;
122775 sqlite3RefillIndex(pParse, pIndex, -1);
122790 int nCol = pIdx->nColumn;
122791 int nKey = pIdx->nKeyCol;
122793 if( pParse->nErr ) return 0;
122794 if( pIdx->uniqNotNull ){
122795 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
122797 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
122802 const char *zColl = pIdx->azColl[i];
122803 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
122805 pKey->aSortFlags[i] = pIdx->aSortOrder[i];
122806 assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
122808 if( pParse->nErr ){
122809 assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
122810 if( pIdx->bNoQuery==0 ){
122815 ** the missing index using the collation-needed callback. For
122818 pIdx->bNoQuery = 1;
122819 pParse->rc = SQLITE_ERROR_RETRY;
122834 Token *pName, /* Name of the common-table */
122840 sqlite3 *db = pParse->db;
122843 assert( pNew!=0 || db->mallocFailed );
122845 if( db->mallocFailed ){
122849 pNew->pSelect = pQuery;
122850 pNew->pCols = pArglist;
122851 pNew->zName = sqlite3NameFromToken(pParse->db, pName);
122852 pNew->eM10d = eM10d;
122863 sqlite3ExprListDelete(db, pCte->pCols);
122864 sqlite3SelectDelete(db, pCte->pSelect);
122865 sqlite3DbFree(db, pCte->zName);
122888 sqlite3 *db = pParse->db;
122898 zName = pCte->zName;
122901 for(i=0; i<pWith->nCte; i++){
122902 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
122909 sqlite3_int64 nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
122914 assert( (pNew!=0 && zName!=0) || db->mallocFailed );
122916 if( db->mallocFailed ){
122920 pNew->a[pNew->nCte++] = *pCte;
122933 for(i=0; i<pWith->nCte; i++){
122934 cteClear(db, &pWith->a[i]);
122946 ** The author disclaims copyright to this source code. In place of
122966 assert( !db->xCollNeeded || !db->xCollNeeded16 );
122967 if( db->xCollNeeded ){
122970 db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
122974 if( db->xCollNeeded16 ){
122977 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
122980 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
122991 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
122996 char *z = pColl->zName;
123001 if( pColl2->xCmp!=0 ){
123003 pColl->xDel = 0; /* Do not copy the destructor */
123022 if( pColl && pColl->xCmp==0 ){
123023 const char *zName = pColl->zName;
123024 sqlite3 *db = pParse->db;
123043 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
123055 pColl = sqlite3HashFind(&db->aCollSeq, zName);
123069 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
123087 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
123112 if( pColl ) pColl += enc-1;
123114 pColl = db->pDfltColl;
123125 db->enc = enc;
123126 /* EVIDENCE-OF: R-08308-17224 The default collating function for all
123129 db->pDfltColl = sqlite3FindCollSeq(db, enc, sqlite3StrBINARY, 0);
123153 sqlite3 *db = pParse->db;
123159 if( !p || !p->xCmp ){
123166 if( p && !p->xCmp && synthCollSeq(db, p) ){
123169 assert( !p || p->xCmp );
123172 pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
123198 sqlite3 *db = pParse->db;
123200 u8 initbusy = db->init.busy;
123204 if( !initbusy && (!pColl || !pColl->xCmp) ){
123217 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
123218 ** is also -1. In other words, we are searching for a function that
123221 ** If nArg is -2 that means that we are searching for any function
123231 ** 4: UTF8/16 conversion required - argument count matches exactly
123232 ** 5: UTF16 byte order conversion required - argument count matches exactly
123235 ** If nArg==(-2) then any function with a non-null xSFunc is
123237 ** a non-match.
123242 int nArg, /* Desired number of arguments. (-1)==any */
123246 assert( p->nArg>=-1 );
123249 if( p->nArg!=nArg ){
123250 if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
123251 if( p->nArg>=0 ) return 0;
123256 if( p->nArg==nArg ){
123263 if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
123265 }else if( (enc & p->funcFlags & 2)!=0 ){
123281 for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
123282 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
123283 if( sqlite3StrICmp(p->zName, zFunc)==0 ){
123306 assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
123307 aDef[i].pNext = pOther->pNext;
123308 pOther->pNext = &aDef[i];
123321 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
123329 ** If nArg is -2, then the first valid function found is returned. A
123330 ** function is valid if xSFunc is non-zero. The nArg==(-2)
123332 ** of arguments. If nArg is -2, then createFlag must be 0.
123340 const char *zName, /* Name of the function. zero-terminated */
123341 int nArg, /* Number of arguments. -1 means any number */
123351 assert( nArg>=(-2) );
123352 assert( nArg>=(-1) || createFlag==0 );
123355 /* First search for a match amongst the application-defined functions.
123357 p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
123364 p = p->pNext;
123367 /* If no match is found, search the built-in functions.
123369 ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
123370 ** functions even if a prior app-defined function was found. And give
123371 ** priority to built-in functions.
123376 ** new function. But the FuncDefs for built-in functions are read-only.
123377 ** So we must not search for built-ins when creating a new function.
123379 if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
123389 p = p->pNext;
123401 pBest->zName = (const char*)&pBest[1];
123402 pBest->nArg = (u16)nArg;
123403 pBest->funcFlags = enc;
123405 for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
123406 pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
123412 pBest->pNext = pOther;
123416 if( pBest && (pBest->xSFunc || createFlag) ){
123438 temp1 = pSchema->tblHash;
123439 temp2 = pSchema->trigHash;
123440 sqlite3HashInit(&pSchema->trigHash);
123441 sqlite3HashClear(&pSchema->idxHash);
123446 sqlite3HashInit(&pSchema->tblHash);
123452 sqlite3HashClear(&pSchema->fkeyHash);
123453 pSchema->pSeqTab = 0;
123454 if( pSchema->schemaFlags & DB_SchemaLoaded ){
123455 pSchema->iGeneration++;
123457 pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
123473 }else if ( 0==p->file_format ){
123474 sqlite3HashInit(&p->tblHash);
123475 sqlite3HashInit(&p->idxHash);
123476 sqlite3HashInit(&p->trigHash);
123477 sqlite3HashInit(&p->fkeyHash);
123478 p->enc = SQLITE_UTF8;
123488 ** The author disclaims copyright to this source code. In place of
123511 ** pSrc->a[0].pTab Pointer to the Table object
123512 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
123516 SrcItem *pItem = pSrc->a;
123518 assert( pItem && pSrc->nSrc>=1 );
123520 sqlite3DeleteTable(pParse->db, pItem->pTab);
123521 pItem->pTab = pTab;
123523 pTab->nTabRef++;
123524 if( pItem->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pItem) ){
123531 /* Generate byte-code that will report the number of rows modified
123541 /* Return true if table pTab is read-only.
123543 ** A table is read-only if any of the following are true:
123558 ** is for a top-level SQL statement.
123561 if( sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ){
123568 ** * Only allow DELETE, INSERT, or UPDATE of non-SQLITE_VTAB_INNOCUOUS
123571 if( pParse->pToplevel!=0
123572 && pTab->u.vtab.p->eVtabRisk >
123573 ((pParse->db->flags & SQLITE_TrustedSchema)!=0)
123576 pTab->zName);
123585 if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
123586 db = pParse->db;
123587 if( (pTab->tabFlags & TF_Readonly)!=0 ){
123588 return sqlite3WritableSchema(db)==0 && pParse->nested==0;
123590 assert( pTab->tabFlags & TF_Shadow );
123597 ** If pTab is not writable -> generate an error message and return 1.
123598 ** If pTab is writable but other errors have occurred -> return 1.
123599 ** If pTab is writable and no prior errors -> return 0;
123603 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
123608 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
123633 sqlite3 *db = pParse->db;
123634 int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
123638 assert( pFrom->nSrc==1 );
123639 pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
123640 pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
123641 assert( pFrom->a[0].fg.isUsing==0 );
123642 assert( pFrom->a[0].u3.pOn==0 );
123663 SrcList *pSrc, /* the FROM clause -- which tables to scan */
123669 sqlite3 *db = pParse->db;
123681 sqlite3ExprDelete(pParse->db, pWhere);
123682 sqlite3ExprListDelete(pParse->db, pOrderBy);
123702 pTab = pSrc->a[0].pTab;
123710 if( pPk->nKeyCol==1 ){
123711 const char *zName = pTab->aCol[pPk->aiColumn[0]].zCnName;
123716 for(i=0; i<pPk->nKeyCol; i++){
123717 Expr *p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zCnName);
123722 pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
123729 pSrc->a[0].pTab = 0;
123731 pSrc->a[0].pTab = pTab;
123732 if( pSrc->a[0].fg.isIndexedBy ){
123733 assert( pSrc->a[0].fg.isCte==0 );
123734 pSrc->a[0].u2.pIBIndex = 0;
123735 pSrc->a[0].fg.isIndexedBy = 0;
123736 sqlite3DbFree(db, pSrc->a[0].u1.zIndexedBy);
123737 }else if( pSrc->a[0].fg.isCte ){
123738 pSrc->a[0].u2.pCteUse->nUse++;
123774 int iDataCur = 0; /* VDBE cursor for the canonical data source */
123805 db = pParse->db;
123806 assert( db->pParse==pParse );
123807 if( pParse->nErr ){
123810 assert( db->mallocFailed==0 );
123811 assert( pTabList->nSrc==1 );
123840 sqlite3TreeViewDelete(pParse->pWith, pTabList, pWhere,
123864 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
123865 assert( iDb<db->nDb );
123866 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
123867 db->aDb[iDb].zDbSName);
123876 assert( pTabList->nSrc==1 );
123877 iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
123878 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
123879 pParse->nTab++;
123885 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
123894 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
123923 if( (db->flags & SQLITE_CountRows)!=0
123924 && !pParse->nested
123925 && !pParse->pTriggerTab
123926 && !pParse->bReturning
123928 memCnt = ++pParse->nMem;
123939 ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
123949 && db->xPreUpdateCallback==0
123953 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
123955 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
123956 pTab->zName, P4_STATIC);
123958 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
123959 assert( pIdx->pSchema==pTab->pSchema );
123961 sqlite3VdbeAddOp3(v, OP_Clear, pIdx->tnum, iDb, memCnt ? memCnt : -1);
123963 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
123976 iRowSet = ++pParse->nMem;
123983 nPk = pPk->nKeyCol;
123984 iPk = pParse->nMem+1;
123985 pParse->nMem += nPk;
123986 iEphCur = pParse->nTab++;
123995 ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
123996 ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
123997 ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
124017 assert( pPk->aiColumn[i]>=0 );
124019 pPk->aiColumn[i], iPk+i);
124023 iKey = ++pParse->nMem;
124024 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
124028 /* For ONEPASS, no need to store the rowid/primary-key. There is only
124039 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
124040 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
124046 iKey = ++pParse->nMem;
124049 sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
124079 /* Set up a loop over the rowids/primary-keys that were found in the
124080 ** where-clause loop above.
124084 if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
124113 pParse->isMultiWrite = 0;
124121 int count = (pParse->nested==0); /* True to count changes */
124126 /* End of the loop over all rowids/primary-keys. */
124137 } /* End non-truncate path */
124143 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
124189 ** cursor number iIdxCur+i for the i-th index.
124225 u8 count, /* If non-zero, increment the row change counter */
124230 Vdbe *v = pParse->pVdbe; /* Vdbe */
124264 iOld = pParse->nMem+1;
124265 pParse->nMem += (1 + pTab->nCol);
124267 /* Populate the OLD.* pseudo-table register array. These values will be
124270 for(iCol=0; iCol<pTab->nCol; iCol++){
124298 iIdxNoSeek = -1;
124311 ** If variable 'count' is non-zero, then this OP_Delete instruction should
124312 ** invoke the update-hook. The pre-update-hook, on the other hand should
124314 ** the update-hook is not invoked for rows removed by REPLACE, but the
124315 ** pre-update-hook is.
124321 if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
124363 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
124364 ** index is the 0-th index.)
124378 int r1 = -1; /* Register holding an index key */
124385 v = pParse->pVdbe;
124387 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
124392 VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
124396 pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
124444 Vdbe *v = pParse->pVdbe;
124450 if( pIdx->pPartIdxWhere ){
124452 pParse->iSelfTab = iDataCur + 1;
124453 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
124455 pParse->iSelfTab = 0;
124456 pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02;
124462 nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
124464 if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
124467 && pPrior->aiColumn[j]==pIdx->aiColumn[j]
124468 && pPrior->aiColumn[j]!=XN_EXPR
124474 if( pIdx->aiColumn[j]>=0 ){
124492 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
124498 sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
124507 ** The author disclaims copyright to this source code. In place of
124515 ** This file contains the C-language implementations for many of the SQL
124532 assert( context->pVdbe!=0 );
124533 pOp = &context->pVdbe->aOp[context->iOp-1];
124534 assert( pOp->opcode==OP_CollSeq );
124535 assert( pOp->p4type==P4_COLLSEQ );
124536 return pOp->p4.pColl;
124544 assert( context->isError<=0 );
124545 context->isError = -1;
124546 context->skipFlag = 1;
124550 ** Implementation of the non-aggregate min() and max() functions
124563 mask = sqlite3_user_data(context)==0 ? 0 : -1;
124566 assert( mask==-1 || mask==0 );
124588 int i = sqlite3_value_type(argv[0]) - 1;
124596 /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
124600 sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
124645 sqlite3_result_int(context, (int)(z-z0));
124658 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
124669 /* IMP: R-31676-45509 If X is the integer -9223372036854775808
124671 ** equivalent positive 64-bit two complement value. */
124672 sqlite3_result_error(context, "integer overflow", -1);
124675 iVal = -iVal;
124681 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
124688 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
124692 if( rVal<0 ) rVal = -rVal;
124759 nHaystack--;
124790 x.nArg = argc-1;
124793 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
124806 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
124807 ** of x. If x is text, then we actually count UTF-8 characters.
124851 ** as substr(X,1,N) - it returns the first N characters of X. This
124852 ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
124853 ** from 2009-02-02 for compatibility of applications that exploited the
124860 p2 = -p2;
124864 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
124874 p1--;
124876 p2--;
124879 p1 -= p2;
124889 p1--;
124891 for(z2=z; *z2 && p2; p2--){
124894 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
124898 p2 = len-p1;
124922 /* If Y==0 and X will fit in a 64-bit int,
124926 if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
124929 r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
124954 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
124955 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
124956 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
125018 #define noopFunc versionFunc /* Substitute function - never called */
125033 ** (or -9223372036854775808) since when you do abs() of that
125038 ** therefore be no less than -9223372036854775807.
125040 r = -(r & LARGEST_INT64);
125080 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
125089 ** IMP: R-32760-32347 The changes() SQL function is a wrapper
125114 /* IMP: R-11217-42568 This function is a wrapper around the
125120 ** A structure defining how to do GLOB-style comparisons.
125143 /* The correct SQL-92 behavior is for the LIKE operator to ignore
125158 ** Compare two UTF-8 strings for equality where the first string is
125178 ** range of characters can be specified using '-'. Example:
125179 ** "[a-z]" matches any single lower-case letter. To match a '-', make
125202 u32 matchOne = pInfo->matchOne; /* "?" or "_" */
125203 u32 matchAll = pInfo->matchAll; /* "*" or "%" */
125204 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
125221 if( pInfo->matchSet==0 ){
125227 assert( matchOther<0x80 ); /* '[' is a single-byte character */
125229 int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
125242 ** For a case-insensitive search, set variable cx to be the same as
125275 if( pInfo->matchSet==0 ){
125295 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
125326 ** non-zero if there is no match.
125339 ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
125340 ** a miss - like strcmp().
125364 ** the build-in LIKE operator. The first argument to the function is the
125402 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
125403 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
125404 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
125405 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
125409 /* The escape character string must consist of a single UTF-8 character.
125414 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
125416 "ESCAPE expression must be a single character", -1);
125420 if( escape==pInfo->matchAll || escape==pInfo->matchOne ){
125423 if( escape==pInfo->matchAll ) pInfo->matchAll = 0;
125424 if( escape==pInfo->matchOne ) pInfo->matchOne = 0;
125427 escape = pInfo->matchSet;
125467 /* IMP: R-48699-48617 This function is an SQL wrapper around the
125468 ** sqlite3_libversion() C-interface. */
125469 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
125474 ** that identifies the particular version of the source code used to build
125483 /* IMP: R-24470-31136 This function is an SQL wrapper around the
125485 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
125491 ** its side-effects.
125517 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
125541 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
125545 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
125549 /* Array for converting from half-bytes (nybbles) into ASCII hex
125564 assert( pStr!=0 && pStr->nChar==0 );
125574 sqlite3AtoF(zVal, &r2, pStr->nChar, SQLITE_UTF8);
125591 if( pStr->accError==0 ){
125592 char *zText = pStr->zText;
125602 pStr->nChar = nBlob*2 + 3;
125624 ** Strings are surrounded by single-quotes with escapes on interior quotes
125634 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
125645 ** The unicode() function. Return the integer unicode code-point value
125697 sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
125730 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
125743 rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
125782 || sqlite3_context_db_handle(context)->mallocFailed );
125802 loopLimit = nStr - nPattern;
125809 nOut += nRep - nPattern;
125810 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
125811 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
125812 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
125818 if( (cntExpand&(cntExpand-1))==0 ){
125823 zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1));
125833 i += nPattern-1;
125836 assert( j+nStr-i+1<=nOut );
125837 memcpy(&zOut[j], &zStr[i], nStr-i);
125838 j += nStr - i;
125893 aLen[nChar] = (unsigned)(z - azChar[nChar]);
125908 nIn -= len;
125916 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
125919 nIn -= len;
125934 ** when the SQLITE_ENABLE_UNKNOWN_FUNCTION compile-time option is used.
125935 ** When the "sqlite3" command-line shell is built using this functionality,
125937 ** involving application-defined functions to be examined in a generic
125945 /* no-op */
125950 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
125951 ** is only available if the SQLITE_SOUNDEX compile-time option is used
125958 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
126003 /* IMP: R-64894-50321 The string "?000" is returned if the argument
126012 ** A function that loads a shared-library extension then returns NULL.
126023 if( (db->flags & SQLITE_LoadExtFunc)==0 ){
126024 sqlite3_result_error(context, "not authorized", -1);
126034 sqlite3_result_error(context, zErrMsg, -1);
126051 u8 approx; /* True if non-integer value was input to the sum */
126072 p->cnt++;
126075 p->rSum += v;
126076 if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
126077 p->approx = p->overflow = 1;
126080 p->rSum += sqlite3_value_double(argv[0]);
126081 p->approx = 1;
126093 /* p is always non-NULL because sumStep() will have been called first
126096 assert( p->cnt>0 );
126097 p->cnt--;
126098 assert( type==SQLITE_INTEGER || p->approx );
126099 if( type==SQLITE_INTEGER && p->approx==0 ){
126101 p->rSum -= v;
126102 p->iSum -= v;
126104 p->rSum -= sqlite3_value_double(argv[0]);
126114 if( p && p->cnt>0 ){
126115 if( p->overflow ){
126116 sqlite3_result_error(context,"integer overflow",-1);
126117 }else if( p->approx ){
126118 sqlite3_result_double(context, p->rSum);
126120 sqlite3_result_int64(context, p->iSum);
126127 if( p && p->cnt>0 ){
126128 sqlite3_result_double(context, p->rSum/(double)p->cnt);
126135 sqlite3_result_double(context, p ? p->rSum : (double)0);
126157 p->n++;
126164 ** expressed as a 32-bit integer. */
126165 assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
126166 || p->n==sqlite3_aggregate_count(context) );
126172 sqlite3_result_int64(context, p ? p->n : 0);
126178 /* p is always non-NULL since countStep() will have been called first */
126180 p->n--;
126182 p->bInverse = 1;
126206 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
126207 }else if( pBest->flags ){
126214 ** sqlite3_user_data() function returns (void *)-1. For min() it
126227 pBest->db = sqlite3_context_db_handle(context);
126235 if( pRes->flags ){
126266 /* If pnSepLengths!=0, refs an array of inter-string separator lengths,
126268 ** (Hence, its slots in use number nAccum-1 between method calls.)
126289 int firstTerm = pGCC->str.mxAlloc==0;
126290 pGCC->str.mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
126293 sqlite3_str_appendchar(&pGCC->str, 1, ',');
126297 pGCC->nFirstSepLength = 1;
126304 sqlite3_str_append(&pGCC->str, zSep, nSep);
126310 if( nSep != pGCC->nFirstSepLength || pGCC->pnSepLengths != 0 ){
126311 int *pnsl = pGCC->pnSepLengths;
126314 pnsl = (int*)sqlite3_malloc64((pGCC->nAccum+1) * sizeof(int));
126316 int i = 0, nA = pGCC->nAccum-1;
126317 while( i<nA ) pnsl[i++] = pGCC->nFirstSepLength;
126320 pnsl = (int*)sqlite3_realloc64(pnsl, pGCC->nAccum * sizeof(int));
126323 if( ALWAYS(pGCC->nAccum>0) ){
126324 pnsl[pGCC->nAccum-1] = nSep;
126326 pGCC->pnSepLengths = pnsl;
126328 sqlite3StrAccumSetError(&pGCC->str, SQLITE_NOMEM);
126335 pGCC->nFirstSepLength = sqlite3_value_bytes(argv[1]);
126337 pGCC->nAccum += 1;
126341 if( zVal ) sqlite3_str_append(&pGCC->str, zVal, nVal);
126356 /* pGCC is always non-NULL since groupConcatStep() will have always
126364 pGCC->nAccum -= 1;
126365 if( pGCC->pnSepLengths!=0 ){
126366 assert(pGCC->nAccum >= 0);
126367 if( pGCC->nAccum>0 ){
126368 nVS += *pGCC->pnSepLengths;
126369 memmove(pGCC->pnSepLengths, pGCC->pnSepLengths+1,
126370 (pGCC->nAccum-1)*sizeof(int));
126373 /* If removing single accumulated string, harmlessly over-do. */
126374 nVS += pGCC->nFirstSepLength;
126376 if( nVS>=(int)pGCC->str.nChar ){
126377 pGCC->str.nChar = 0;
126379 pGCC->str.nChar -= nVS;
126380 memmove(pGCC->str.zText, &pGCC->str.zText[nVS], pGCC->str.nChar);
126382 if( pGCC->str.nChar==0 ){
126383 pGCC->str.mxAlloc = 0;
126384 sqlite3_free(pGCC->pnSepLengths);
126385 pGCC->pnSepLengths = 0;
126396 sqlite3ResultStrAccum(context, &pGCC->str);
126398 sqlite3_free(pGCC->pnSepLengths);
126407 StrAccum *pAccum = &pGCC->str;
126408 if( pAccum->accError==SQLITE_TOOBIG ){
126410 }else if( pAccum->accError==SQLITE_NOMEM ){
126414 sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT);
126423 ** This routine does per-connection function registration. Most
126424 ** of the built-in functions above are part of the global function set.
126446 ** Re-register the built-in LIKE functions. The caseSensitive
126462 sqlite3FindFunction(db, "like", 2, SQLITE_UTF8, 0)->funcFlags |= flags;
126463 sqlite3FindFunction(db, "like", 3, SQLITE_UTF8, 0)->funcFlags |= flags;
126471 ** LIKE-style function then return FALSE.
126487 assert( pExpr->op==TK_FUNCTION );
126489 if( !pExpr->x.pList ){
126492 nExpr = pExpr->x.pList->nExpr;
126494 pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
126498 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
126506 memcpy(aWc, pDef->pUserData, 3);
126514 Expr *pEscape = pExpr->x.pList->a[2].pExpr;
126516 if( pEscape->op!=TK_STRING ) return 0;
126518 zEscape = pEscape->u.zToken;
126525 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
126541 /* Extra math functions that require linking with -lm
126587 ** ln(X) - natural logarithm
126588 ** log(X) - log X base 10
126589 ** log10(X) - log X base 10
126590 ** log(B,X) - log X base B
126646 ** Implementation of 1-argument SQL math functions:
126648 ** exp(X) - Compute e to the X-th power
126668 ** Implementation of 2-argument SQL math functions:
126670 ** power(X,Y) - Compute X to the Y-th power
126693 ** Implementation of 0-argument pi() function.
126721 sqlite3_result_int(context, x<0.0 ? -1 : x>0.0 ? +1 : 0);
126726 ** to the global function hash table. This occurs at start-time (as
126737 ** FuncDef.pHash elements at start-time. The elements of this array
126738 ** are read-only after initialization is complete.
126777 FUNCTION(min, -1, 0, 1, minmaxFunc ),
126781 FUNCTION(max, -1, 1, 1, minmaxFunc ),
126789 FUNCTION(printf, -1, 0, 0, printfFunc ),
126790 FUNCTION(format, -1, 0, 0, printfFunc ),
126792 FUNCTION(char, -1, 0, 0, charFunc ),
126840 FUNCTION(unknown, -1, 0, 0, unknownFunc ),
126881 INLINE_FUNC(coalesce, -1, INLINEFUNC_coalesce, 0 ),
126892 #if 0 /* Enable to print out how the built-in functions are hashed */
126897 printf("FUNC-HASH %02d:", i);
126898 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
126899 int n = sqlite3Strlen30(p->zName);
126900 int h = p->zName[0] + n;
126901 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
126902 printf(" %s(%d)", p->zName, h);
126914 ** The author disclaims copyright to this source code. In place of
126932 ** --------------------------
127014 ** ---------------
127016 ** Before coding an UPDATE or DELETE row operation, the code-generator
127021 ** accessed). No information is required by the code-generator before
127025 ** sqlite3FkRequired() - Test to see if FK processing is required.
127026 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
127030 ** --------------------------------------
127032 ** sqlite3FkCheck() - Check for foreign key violations.
127033 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
127034 ** sqlite3FkDelete() - Delete an FKey structure.
127039 ** -----------------------
127069 ** constraint to the parent table column stored in the left-most column
127071 ** child table column that corresponds to the second left-most column of
127090 ** then non-zero is returned, and a "foreign key mismatch" error loaded
127091 ** into pParse. If an OOM error occurs, non-zero is returned and the
127092 ** pParse->db->mallocFailed flag is set.
127103 int nCol = pFKey->nCol; /* Number of columns in parent key */
127104 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
127111 /* If this is a non-composite (single column) foreign key, check if it
127117 ** Non-composite foreign keys do not require the aiCol array.
127127 if( pParent->iPKey>=0 ){
127129 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zCnName, zKey) ){
127135 aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
127140 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
127141 if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
127153 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
127158 /* If zKey is non-NULL, then this foreign key was declared to
127164 i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
127173 zDfltColl = sqlite3ColumnColl(&pParent->aCol[iCol]);
127175 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
127177 zIdxCol = pParent->aCol[iCol].zCnName;
127179 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
127180 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
127192 if( !pParse->disableTriggers ){
127194 "foreign key mismatch - \"%w\" referencing \"%w\"",
127195 pFKey->pFrom->zName, pFKey->zTo);
127197 sqlite3DbFree(pParse->db, aiCol);
127209 ** affected - once to "delete" the old row, and then again to "insert" the
127219 ** --------------------------------------------------------------------------
127244 int iCur = pParse->nTab - 1; /* Cursor number to use */
127248 (!pFKey->isDeferred
127249 && !(pParse->db->flags & SQLITE_DeferFKs)
127250 && !pParse->pToplevel
127251 && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
127261 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
127264 for(i=0; i<pFKey->nCol; i++){
127265 int iReg = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + regData + 1;
127282 sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[0])+1+regData, regTemp);
127287 ** to increment the constraint-counter (i.e. this is an INSERT operation),
127289 ** increment the constraint-counter. */
127290 if( pTab==pFKey->pFrom && nIncr==1 ){
127298 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
127302 int nCol = pFKey->nCol;
127305 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
127309 sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,
127314 ** to increment the constraint-counter (i.e. this is an INSERT operation),
127316 ** increment the constraint-counter.
127318 ** If any of the parent-key values are NULL, then the row cannot match
127320 ** of the parent-key values are NULL (at this point it is known that
127323 if( pTab==pFKey->pFrom && nIncr==1 ){
127326 int iChild = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i])
127329 iParent += sqlite3TableColumnToStorage(pIdx->pTable,
127330 pIdx->aiColumn[i]);
127331 assert( pIdx->aiColumn[i]>=0 );
127332 assert( aiCol[i]!=pTab->iPKey );
127333 if( pIdx->aiColumn[i]==pTab->iPKey ){
127344 sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
127351 if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
127352 && !pParse->pToplevel
127353 && !pParse->isMultiWrite
127363 if( nIncr>0 && pFKey->isDeferred==0 ){
127366 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
127391 sqlite3 *db = pParse->db;
127395 if( iCol>=0 && iCol!=pTab->iPKey ){
127396 pCol = &pTab->aCol[iCol];
127397 pExpr->iTable = regBase + sqlite3TableColumnToStorage(pTab,iCol) + 1;
127398 pExpr->affExpr = pCol->affinity;
127400 if( zColl==0 ) zColl = db->pDfltColl->zName;
127403 pExpr->iTable = regBase;
127404 pExpr->affExpr = SQLITE_AFF_INTEGER;
127423 pExpr->y.pTab = pTab;
127424 pExpr->iTable = iCursor;
127425 pExpr->iColumn = iCol;
127434 ** code for an SQL UPDATE operation, this function may be called twice -
127437 ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
127446 ** --------------------------------------------------------------------------
127468 sqlite3 *db = pParse->db; /* Database handle */
127476 assert( pIdx==0 || pIdx->pTable==pTab );
127477 assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
127478 assert( pIdx!=0 || pFKey->nCol==1 );
127482 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
127488 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
127494 for(i=0; i<pFKey->nCol; i++){
127501 iCol = pIdx ? pIdx->aiColumn[i] : -1;
127503 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
127505 zCol = pFKey->pFrom->aCol[iCol].zCnName;
127525 if( pTab==pFKey->pFrom && nIncr>0 ){
127530 pLeft = exprTableRegister(pParse, pTab, regData, -1);
127531 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
127536 for(i=0; i<pIdx->nKeyCol; i++){
127537 i16 iCol = pIdx->aiColumn[i];
127540 pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zCnName);
127558 if( pParse->nErr==0 ){
127560 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
127588 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
127594 ** and all of its sub-components.
127596 ** The Trigger structure or any of its sub-components may be allocated from
127601 TriggerStep *pStep = p->step_list;
127602 sqlite3ExprDelete(dbMem, pStep->pWhere);
127603 sqlite3ExprListDelete(dbMem, pStep->pExprList);
127604 sqlite3SelectDelete(dbMem, pStep->pSelect);
127605 sqlite3ExprDelete(dbMem, p->pWhen);
127617 Hash *pHash = &db->aDb[iDb].pSchema->tblHash;
127622 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
127623 fkTriggerDelete(db, pFKey->apTrigger[0]); pFKey->apTrigger[0] = 0;
127624 fkTriggerDelete(db, pFKey->apTrigger[1]); pFKey->apTrigger[1] = 0;
127647 sqlite3 *db = pParse->db;
127648 if( (db->flags&SQLITE_ForeignKeys) && IsOrdinaryTable(pTab) ){
127661 for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
127662 if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
127669 pParse->disableTriggers = 1;
127671 pParse->disableTriggers = 0;
127682 if( (db->flags & SQLITE_DeferFKs)==0 ){
127703 ** is set to -1). If the rowid column is modified by the UPDATE statement
127704 ** the bChngRowid argument is non-zero.
127716 for(i=0; i<p->nCol; i++){
127717 int iChildKey = p->aCol[i].iFrom;
127719 if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
127730 ** is set to -1). If the rowid column is modified by the UPDATE statement
127731 ** the bChngRowid argument is non-zero.
127743 for(i=0; i<p->nCol; i++){
127744 char *zKey = p->aCol[i].zCol;
127746 for(iKey=0; iKey<pTab->nCol; iKey++){
127747 if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
127748 Column *pCol = &pTab->aCol[iKey];
127750 if( 0==sqlite3StrICmp(pCol->zCnName, zKey) ) return 1;
127751 }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
127767 if( pTop->pTriggerPrg ){
127768 Trigger *p = pTop->pTriggerPrg->pTrigger;
127769 if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
127770 || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
127784 ** first register in an array of (pTab->nCol+1) registers containing the
127790 ** first register of an array of (pTab->nCol+1) registers containing the new
127806 sqlite3 *db = pParse->db; /* Database handle */
127810 int isIgnoreErrors = pParse->disableTriggers;
127812 /* Exactly one of regOld and regNew should be non-zero. */
127815 /* If foreign-keys are disabled, this function is a no-op. */
127816 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
127819 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
127820 zDb = db->aDb[iDb].zDbSName;
127824 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
127834 && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
127844 if( pParse->disableTriggers ){
127845 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
127847 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
127851 if( !isIgnoreErrors || db->mallocFailed ) return;
127858 ** FK counter for each row of the current table with non-NULL keys.
127861 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
127862 for(i=0; i<pFKey->nCol; i++){
127864 iFromCol = pFKey->aCol[i].iFrom;
127865 iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1;
127868 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
127872 assert( pFKey->nCol==1 || (aiFree && pIdx) );
127877 iCol = pFKey->aCol[0].iFrom;
127880 for(i=0; i<pFKey->nCol; i++){
127881 if( aiCol[i]==pTab->iPKey ){
127882 aiCol[i] = -1;
127884 assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
127889 if( db->xAuth ){
127891 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zCnName;
127892 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
127898 /* Take a shared-cache advisory read-lock on the parent table. Allocate
127901 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
127902 pParse->nTab++;
127908 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
127927 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
127936 if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
127937 && !pParse->pToplevel && !pParse->isMultiWrite
127946 if( !isIgnoreErrors || db->mallocFailed ) return;
127949 assert( aiCol || pFKey->nCol==1 );
127955 SrcItem *pItem = pSrc->a;
127956 pItem->pTab = pFKey->pFrom;
127957 pItem->zName = pFKey->pFrom->zName;
127958 pItem->pTab->nTabRef++;
127959 pItem->iCursor = pParse->nTab++;
127962 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
127965 int eAction = pFKey->aAction[aChange!=0];
127970 ** So do not set the "may-abort" flag in this case.
127973 ** may-abort flag will eventually be set on this statement anyway
127984 if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
127988 pItem->zName = 0;
128006 if( pParse->db->flags&SQLITE_ForeignKeys && IsOrdinaryTable(pTab) ){
128009 for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
128010 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
128012 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
128016 for(i=0; i<pIdx->nKeyCol; i++){
128017 assert( pIdx->aiColumn[i]>=0 );
128018 mask |= COLUMN_MASK(pIdx->aiColumn[i]);
128033 ** entry in the aChange[] array is set to -1. If the column is modified,
128038 ** non-zero. If there is no foreign key related processing, this function
128054 int *aChange, /* Non-NULL for UPDATE operations */
128059 if( pParse->db->flags&SQLITE_ForeignKeys && IsOrdinaryTable(pTab) ){
128064 bHaveFK = (sqlite3FkReferences(pTab) || pTab->u.tab.pFKey);
128071 for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
128073 if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) eRet = 2;
128079 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
128081 if( p->aAction[1]!=OE_None ) return 2;
128092 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
128100 ** require no special handling by the triggers sub-system, code for them is
128123 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
128125 sqlite3 *db = pParse->db; /* Database handle */
128130 action = pFKey->aAction[iAction];
128131 if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
128134 pTrigger = pFKey->apTrigger[iAction];
128140 int *aiCol = 0; /* child table cols -> parent key cols */
128149 assert( aiCol || pFKey->nCol==1 );
128151 for(i=0; i<pFKey->nCol; i++){
128159 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
128161 assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
128162 assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
128164 pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zCnName);
128165 sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zCnName);
128203 Column *pCol = pFKey->pFrom->aCol + iFromCol;
128205 if( pCol->colFlags & COLFLAG_GENERATED ){
128206 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
128207 testcase( pCol->colFlags & COLFLAG_STORED );
128210 pDflt = sqlite3ColumnExpr(pFKey->pFrom, pCol);
128226 zFrom = pFKey->pFrom->zName;
128230 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
128237 tDb.z = db->aDb[iDb].zDbSName;
128242 pRaise->affExpr = OE_Abort;
128259 nFrom + 1 /* Space for pStep->zTarget */
128262 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
128263 pStep->zTarget = (char *)&pStep[1];
128264 memcpy((char *)pStep->zTarget, zFrom, nFrom);
128266 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
128267 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
128268 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
128271 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
128275 /* Re-enable the lookaside buffer, if it was disabled earlier. */
128282 if( db->mallocFailed==1 ){
128291 pStep->op = TK_SELECT;
128295 pStep->op = TK_DELETE;
128300 pStep->op = TK_UPDATE;
128302 pStep->pTrig = pTrigger;
128303 pTrigger->pSchema = pTab->pSchema;
128304 pTrigger->pTabSchema = pTab->pSchema;
128305 pFKey->apTrigger[iAction] = pTrigger;
128306 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
128319 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
128324 /* If foreign-key support is enabled, iterate through all FKs that
128327 ** trigger sub-program. */
128328 if( pParse->db->flags&SQLITE_ForeignKeys ){
128330 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
128350 FKey *pNext; /* Copy of pFKey->pNextFrom */
128354 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pNext){
128355 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
128358 if( db->pnBytesFreed==0 ){
128359 if( pFKey->pPrevTo ){
128360 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
128362 void *p = (void *)pFKey->pNextTo;
128363 const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
128364 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
128366 if( pFKey->pNextTo ){
128367 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
128371 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
128374 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
128378 fkTriggerDelete(db, pFKey->apTrigger[0]);
128379 fkTriggerDelete(db, pFKey->apTrigger[1]);
128382 pNext = pFKey->pNextFrom;
128393 ** The author disclaims copyright to this source code. In place of
128424 assert( pParse->pVdbe!=0 );
128425 v = pParse->pVdbe;
128427 sqlite3TableLock(pParse, iDb, pTab->tnum,
128428 (opcode==OP_OpenWrite)?1:0, pTab->zName);
128430 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
128431 VdbeComment((v, "%s", pTab->zName));
128435 assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
128436 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
128438 VdbeComment((v, "%s", pTab->zName));
128448 ** ------------------------------
128463 if( !pIdx->zColAff ){
128473 Table *pTab = pIdx->pTable;
128474 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
128475 if( !pIdx->zColAff ){
128479 for(n=0; n<pIdx->nColumn; n++){
128480 i16 x = pIdx->aiColumn[n];
128483 aff = pTab->aCol[x].affinity;
128488 assert( pIdx->bHasExpr );
128489 assert( pIdx->aColExpr!=0 );
128490 aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
128494 pIdx->zColAff[n] = aff;
128496 pIdx->zColAff[n] = 0;
128499 return pIdx->zColAff;
128509 zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
128512 for(i=j=0; i<pTab->nCol; i++){
128513 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
128514 zColAff[j++] = pTab->aCol[i].affinity;
128518 zColAff[j--] = 0;
128528 ** For ordinary (legacy, non-strict) tables:
128529 ** -----------------------------------------
128535 ** which were then optimized out) then this routine becomes a no-op.
128545 ** --------- ---------------
128553 ** ------------------
128567 if( pTab->tabFlags & TF_Strict ){
128576 assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
128577 pPrev->opcode = OP_TypeCheck;
128578 sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);
128581 sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
128586 zColAff = pTab->zColAff;
128593 pTab->zColAff = zColAff;
128601 assert( sqlite3VdbeGetLastOp(v)->opcode==OP_MakeRecord
128602 || sqlite3VdbeDb(v)->mallocFailed );
128603 sqlite3VdbeChangeP4(v, -1, zColAff, i);
128609 ** Return non-zero if the table pTab in database iDb or any of its indices
128619 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
128625 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
128627 Pgno tnum = pOp->p2;
128628 if( tnum==pTab->tnum ){
128631 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
128632 if( tnum==pIndex->tnum ){
128638 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
128639 assert( pOp->p4.pVtab!=0 );
128640 assert( pOp->p4type==P4_VTAB );
128652 if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
128653 assert( pExpr->iColumn < pWalker->u.pTab->nCol );
128654 pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
128678 assert( pTab->tabFlags & TF_HasGenerated );
128679 testcase( pTab->tabFlags & TF_HasVirtual );
128680 testcase( pTab->tabFlags & TF_HasStored );
128685 sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
128686 if( (pTab->tabFlags & TF_HasStored)!=0 ){
128687 pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
128688 if( pOp->opcode==OP_Affinity ){
128690 ** columns. '@' is the no-op affinity and those columns have not
128693 char *zP4 = pOp->p4.z;
128695 assert( pOp->p4type==P4_DYNAMIC );
128697 if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
128700 if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
128705 }else if( pOp->opcode==OP_TypeCheck ){
128709 pOp->p3 = 1;
128714 ** this is a two-pass algorithm. On the first pass, mark all generated
128717 for(i=0; i<pTab->nCol; i++){
128718 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
128719 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
128720 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
128721 pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
128730 /* On the second pass, compute the value of each NOT-AVAILABLE column.
128735 pParse->iSelfTab = -iRegStore;
128739 for(i=0; i<pTab->nCol; i++){
128740 Column *pCol = pTab->aCol + i;
128741 if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
128743 pCol->colFlags |= COLFLAG_BUSY;
128746 pCol->colFlags &= ~COLFLAG_BUSY;
128752 assert( pCol->colFlags & COLFLAG_GENERATED );
128755 pCol->colFlags &= ~COLFLAG_NOTAVAIL;
128760 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
128762 pParse->iSelfTab = 0;
128797 assert( pParse->db->aDb[iDb].pSchema!=0 );
128798 if( (pTab->tabFlags & TF_Autoincrement)!=0
128799 && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
128803 Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
128807 ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
128811 || pSeqTab->nCol!=2
128813 pParse->nErr++;
128814 pParse->rc = SQLITE_CORRUPT_SEQUENCE;
128818 pInfo = pToplevel->pAinc;
128819 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
128821 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
128823 testcase( pParse->earlyCleanup );
128824 if( pParse->db->mallocFailed ) return 0;
128825 pInfo->pNext = pToplevel->pAinc;
128826 pToplevel->pAinc = pInfo;
128827 pInfo->pTab = pTab;
128828 pInfo->iDb = iDb;
128829 pToplevel->nMem++; /* Register to hold name of table */
128830 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
128831 pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
128833 memId = pInfo->regCtr;
128844 sqlite3 *db = pParse->db; /* The database connection */
128847 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
128849 /* This routine is never called during trigger-generation. It is
128850 ** only called from the top-level */
128851 assert( pParse->pTriggerTab==0 );
128855 for(p = pParse->pAinc; p; p = p->pNext){
128872 pDb = &db->aDb[p->iDb];
128873 memId = p->regCtr;
128874 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
128875 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
128876 sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
128882 aOp[3].p1 = memId-1;
128891 if( pParse->nTab==0 ) pParse->nTab = 1;
128905 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
128918 Vdbe *v = pParse->pVdbe;
128919 sqlite3 *db = pParse->db;
128922 for(p = pParse->pAinc; p; p = p->pNext){
128932 Db *pDb = &db->aDb[p->iDb];
128934 int memId = p->regCtr;
128937 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
128940 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
128945 aOp[2].p1 = memId-1;
128954 if( pParse->pAinc ) autoIncrementEnd(pParse);
128959 ** above are all no-ops
128970 Select *pSelect, /* A SELECT statement to use as the data source */
128983 ** then a list of all (non-hidden) columns for the table is substituted.
128988 ** first two forms shown above. A VALUES clause is really just short-hand
128994 ** insert with data coming from a single-row VALUES clause, the code executes
128995 ** once straight down through. Pseudo-code follows (we call this
129007 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
129031 ** X <- A
129039 ** end-coroutine X
129052 ** X <- A
129060 ** end co-routine R
129075 Select *pSelect, /* A SELECT statement to use as the data source */
129089 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
129118 db = pParse->db;
129119 assert( db->pParse==pParse );
129120 if( pParse->nErr ){
129123 assert( db->mallocFailed==0 );
129130 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
129131 pList = pSelect->pEList;
129132 pSelect->pEList = 0;
129139 assert( pTabList->nSrc==1 );
129144 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
129145 assert( iDb<db->nDb );
129146 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
129147 db->aDb[iDb].zDbSName) ){
129172 sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
129178 ** ViewGetColumnNames() is a no-op if pTab is not a view.
129184 /* Cannot insert into a read-only table.
129194 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
129226 regRowid = regIns = pParse->nMem+1;
129227 pParse->nMem += pTab->nCol + 1;
129230 pParse->nMem++;
129243 ** PRIMARY KEY in the original table is pTab->iPKey.) After this
129244 ** loop, if ipkColumn==(-1), that means that integer primary key
129253 bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
129255 assert( pColumn->eU4!=EU4_EXPR );
129256 pColumn->eU4 = EU4_IDX;
129257 for(i=0; i<pColumn->nId; i++){
129258 pColumn->a[i].u4.idx = -1;
129260 for(i=0; i<pColumn->nId; i++){
129261 for(j=0; j<pTab->nCol; j++){
129262 if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zCnName)==0 ){
129263 pColumn->a[i].u4.idx = j;
129265 if( j==pTab->iPKey ){
129269 if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
129272 pTab->aCol[j].zCnName);
129279 if( j>=pTab->nCol ){
129280 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
129285 pTabList->a, pColumn->a[i].zName);
129286 pParse->checkSchema = 1;
129294 ** is coming from a SELECT statement, then generate a co-routine that
129296 ** co-routine is the common header to the 3rd and 4th templates.
129299 /* Data is coming from a SELECT or from a multi-row VALUES clause.
129300 ** Generate a co-routine to run the SELECT. */
129301 int regYield; /* Register holding co-routine entry-point */
129302 int addrTop; /* Top of the co-routine */
129305 regYield = ++pParse->nMem;
129310 dest.nSdst = pTab->nCol;
129313 assert( db->pParse==pParse );
129314 if( rc || pParse->nErr ) goto insert_cleanup;
129315 assert( db->mallocFailed==0 );
129317 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
129318 assert( pSelect->pEList );
129319 nColumn = pSelect->pEList->nExpr;
129349 srcTab = pParse->nTab++;
129364 ** single-row VALUES clause
129369 srcTab = -1;
129372 nColumn = pList->nExpr;
129386 ipkColumn = pTab->iPKey;
129388 if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
129389 testcase( pTab->tabFlags & TF_HasVirtual );
129390 testcase( pTab->tabFlags & TF_HasStored );
129391 for(i=ipkColumn-1; i>=0; i--){
129392 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
129393 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
129394 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
129395 ipkColumn--;
129401 /* Make sure the number of columns in the source data matches the number
129407 if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
129408 for(i=0; i<pTab->nCol; i++){
129409 if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
129412 if( nColumn!=(pTab->nCol-nHidden) ){
129415 pTabList->a, pTab->nCol-nHidden, nColumn);
129419 if( pColumn!=0 && nColumn!=pColumn->nId ){
129420 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
129426 if( (db->flags & SQLITE_CountRows)!=0
129427 && !pParse->nested
129428 && !pParse->pTriggerTab
129429 && !pParse->bReturning
129431 regRowCount = ++pParse->nMem;
129438 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
129444 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
129446 aRegIdx[i] = ++pParse->nMem;
129447 pParse->nMem += pIdx->nColumn;
129449 aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
129456 pTab->zName);
129463 if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
129466 pTabList->a[0].iCursor = iDataCur;
129469 pNx->pUpsertSrc = pTabList;
129470 pNx->regData = regData;
129471 pNx->iDataCur = iDataCur;
129472 pNx->iIdxCur = iIdxCur;
129473 if( pNx->pUpsertTarget ){
129478 pNx = pNx->pNextUpsert;
129506 sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
129510 /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
129512 ** the value does not get overwritten by a NULL at tag-20191021-002. */
129526 for(i=0; i<pTab->nCol; i++, iRegStore++){
129530 if( i==pTab->iPKey ){
129531 /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
129534 ** NULL - we cannot optimize further by skipping the column completely */
129538 if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
129544 iRegStore--;
129548 ** triggers, the slots used for stored columns will be OP_Copy-ed
129559 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
129565 assert( pColumn->eU4==EU4_IDX );
129566 for(j=0; j<pColumn->nId && pColumn->a[j].u4.idx!=i; j++){}
129567 if( j>=pColumn->nId ){
129571 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
129579 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
129583 k = i - nHidden;
129593 Expr *pX = pList->a[k].pExpr;
129607 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
129613 ** not happened yet) so we substitute a rowid of -1
129616 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
129624 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
129627 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
129633 assert( pTab->nNVCol>0 );
129634 sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
129641 if( pTab->tabFlags & TF_HasGenerated ){
129642 testcase( pTab->tabFlags & TF_HasVirtual );
129643 testcase( pTab->tabFlags & TF_HasStored );
129659 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
129661 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
129674 /* Rowid already initialized at tag-20191021-001 */
129676 Expr *pIpk = pList->a[ipkColumn].pExpr;
129677 if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
129681 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
129712 if( pTab->tabFlags & TF_HasGenerated ){
129724 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
129735 if( db->flags & SQLITE_ForeignKeys ){
129753 }else if( pParse->bReturning ){
129755 ** constant value -1, in case one or more of the returned expressions
129757 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
129770 pTab, regData-2-pTab->nCol, onError, endOfLoop);
129773 /* The bottom of the main insertion loop, if the data source
129787 if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
129788 assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
129802 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
129838 ** Meanings of bits in of pWalker->eCode for
129845 * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
129850 if( pExpr->op==TK_COLUMN ){
129851 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
129852 if( pExpr->iColumn>=0 ){
129853 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
129854 pWalker->eCode |= CKCNSTRNT_COLUMN;
129857 pWalker->eCode |= CKCNSTRNT_ROWID;
129864 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
129873 ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
129874 ** The operation of this routine is the same - return true if an only if
129902 ** the indexes of a table in the order provided in the Table->pIndex list.
129903 ** However, sometimes (rarely - when there is an upsert) it wants to visit
129937 assert( pIter->i==0 );
129938 if( pIter->eType ){
129939 *pIx = pIter->u.ax.aIdx[0].ix;
129940 return pIter->u.ax.aIdx[0].p;
129943 return pIter->u.lx.pIdx;
129949 if( pIter->eType ){
129950 int i = ++pIter->i;
129951 if( i>=pIter->u.ax.nIdx ){
129955 *pIx = pIter->u.ax.aIdx[i].ix;
129956 return pIter->u.ax.aIdx[i].p;
129959 pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
129960 return pIter->u.lx.pIdx;
129970 ** pTab->nCol+1 registers in this range. The first register (the one
129997 ** at pTab->pIndex.
129999 ** (2019-05-07) The generated code also creates a new record for the
130001 ** register identified by aRegIdx[nIdx] - in other words in the first
130012 ** for the first index in the pTab->pIndex list. Cursors for other indices
130013 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
130021 ** --------------- ---------- ----------------------------------------
130051 ** Or if overrideError==OE_Default, then the pParse->onError parameter
130052 ** is used. Or if pParse->onError==OE_Default then the onError value
130063 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
130097 db = pParse->db;
130098 v = pParse->pVdbe;
130101 nCol = pTab->nCol;
130112 nPkField = pPk->nKeyCol;
130121 if( pTab->tabFlags & TF_HasNotNull ){
130128 Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
130129 int isGenerated; /* non-zero if column is generated */
130130 onError = pCol->notNull;
130132 if( i==pTab->iPKey ){
130135 isGenerated = pCol->colFlags & COLFLAG_GENERATED;
130151 || pCol->iDflt==0 /* REPLACE is ABORT if no DEFAULT value */
130153 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
130154 testcase( pCol->colFlags & COLFLAG_STORED );
130155 testcase( pCol->colFlags & COLFLAG_GENERATED );
130171 assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
130183 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
130184 pCol->zCnName);
130209 if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
130217 } /* end of 2-pass loop */
130218 } /* end if( has-not-null-constraints ) */
130223 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
130224 ExprList *pCheck = pTab->pCheck;
130225 pParse->iSelfTab = -(regNewData+1);
130227 for(i=0; i<pCheck->nExpr; i++){
130230 Expr *pExpr = pCheck->a[i].pExpr;
130245 if( !db->mallocFailed ){
130252 char *zName = pCheck->a[i].zEName;
130253 assert( zName!=0 || pParse->db->mallocFailed );
130254 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
130261 pParse->iSelfTab = 0;
130278 ** 2018-08-14: Ticket https://www.sqlite.org/src/info/908f001483982c43
130296 sIdxIter.u.lx.pIdx = pTab->pIndex;
130298 if( pUpsert->pUpsertTarget==0 ){
130299 /* There is just on ON CONFLICT clause and it has no constraint-target */
130300 assert( pUpsert->pNextUpsert==0 );
130301 if( pUpsert->isDoUpdate==0 ){
130302 /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
130310 }else if( pTab->pIndex!=0 ){
130318 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
130327 pUpsert->pToFree = sIdxIter.u.ax.aIdx;
130328 for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
130329 if( pTerm->pUpsertTarget==0 ) break;
130330 if( pTerm->pUpsertIdx==0 ) continue; /* Skip ON CONFLICT for the IPK */
130332 pIdx = pTab->pIndex;
130333 while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
130334 pIdx = pIdx->pNext;
130343 for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
130373 if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
130379 if( db->flags&SQLITE_RecTriggers ){
130389 regTrigCnt = ++pParse->nMem;
130404 onError = pTab->keyConf;
130415 if( pUpsertClause->isDoUpdate==0 ){
130436 && pTab->pIndex /* There exist other constraints */
130475 ** recursive-triggers flag is set, call GenerateRowDelete() to
130477 ** the triggers and remove both the table and index b-tree entries.
130479 ** Otherwise, if there are no triggers or the recursive-triggers
130481 ** GenerateRowIndexDelete(). This removes the index b-tree entries
130482 ** only. The table b-tree entry will be replaced by the new entry
130499 regNewData, 1, 0, OE_Replace, 1, -1);
130505 /* This OP_Delete opcode fires the pre-update-hook only. It does
130506 ** not modify the b-tree. It is more efficient to let the coming
130512 if( pTab->pIndex ){
130514 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
130537 sqlite3VdbeJumpHere(v, ipkTop-1);
130570 VdbeNoopComment((v, "prep index %s", pIdx->zName));
130575 if( pIdx->pPartIdxWhere ){
130577 pParse->iSelfTab = -(regNewData+1);
130578 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
130580 pParse->iSelfTab = 0;
130587 for(i=0; i<pIdx->nColumn; i++){
130588 int iField = pIdx->aiColumn[i];
130591 pParse->iSelfTab = -(regNewData+1);
130592 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
130593 pParse->iSelfTab = 0;
130594 VdbeComment((v, "%s column %d", pIdx->zName, i));
130595 }else if( iField==XN_ROWID || iField==pTab->iPKey ){
130603 VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
130606 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
130607 VdbeComment((v, "for %s", pIdx->zName));
130609 if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
130610 sqlite3SetMakeRecordP5(v, pIdx->pTable);
130613 sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
130625 onError = pIdx->onError;
130638 if( pUpsertClause->isDoUpdate==0 ){
130653 ** must be explicitly deleted in order to ensure any pre-update hook
130657 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
130660 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
130662 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
130663 (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
130674 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
130682 ** is different from old-rowid */
130691 ** store it in registers regR..regR+nPk-1 */
130693 for(i=0; i<pPk->nKeyCol; i++){
130694 assert( pPk->aiColumn[i]>=0 );
130695 x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
130697 VdbeComment((v, "%s.%s", pTab->zName,
130698 pTab->aCol[pPk->aiColumn[i]].zCnName));
130709 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
130713 for(i=0; i<pPk->nKeyCol; i++){
130714 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
130715 x = pPk->aiColumn[i];
130717 if( i==(pPk->nKeyCol-1) ){
130761 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
130762 assert( nConflictCk>0 || db->mallocFailed );
130790 if( pIdx->pPartIdxWhere ){
130793 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
130797 ** the constraint-ok jump destination to be the address of
130818 nConflictCk--;
130873 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
130887 ** to be the number of columns in table pTab that must not be NULL-trimmed.
130889 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
130895 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
130896 if( pTab->pSchema->file_format<2 ) return;
130898 for(i=pTab->nCol-1; i>0; i--){
130899 if( pTab->aCol[i].iDflt!=0 ) break;
130900 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
130909 ** PK index. This function adds code to invoke the pre-update hook,
130919 Vdbe *v = pParse->pVdbe;
130922 assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
130944 int iDataCur, /* Cursor of the canonical data source */
130962 v = pParse->pVdbe;
130965 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
130967 assert( pIdx->onError!=OE_Replace
130968 || pIdx->pNext==0
130969 || pIdx->pNext->onError==OE_Replace );
130971 if( pIdx->pPartIdxWhere ){
130985 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
130989 if( pParse->nested ){
131002 if( !pParse->nested ){
131018 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
131024 ** pTab->pIndex list.
131026 ** If pTab is a virtual table, then this routine is a no-op and the
131036 int *piDataCur, /* Write the database source cursor number here */
131048 /* This routine is a no-op for virtual tables. Leave the output
131051 *piDataCur = *piIdxCur = -999;
131054 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
131055 v = pParse->pVdbe;
131057 if( iBase<0 ) iBase = pParse->nTab;
131063 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
131066 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
131068 assert( pIdx->pSchema==pTab->pSchema );
131074 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
131077 VdbeComment((v, "%s", pIdx->zName));
131080 if( iBase>pParse->nTab ) pParse->nTab = iBase;
131089 ** purposes only - to make sure the transfer optimization really
131098 ** Check to see if index pSrc is compatible as a source of data
131111 assert( pDest->pTable!=pSrc->pTable );
131112 if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
131115 if( pDest->onError!=pSrc->onError ){
131118 for(i=0; i<pSrc->nKeyCol; i++){
131119 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
131122 if( pSrc->aiColumn[i]==XN_EXPR ){
131123 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
131124 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
131125 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
131129 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
131132 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
131136 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
131154 ** There are lots of rules for determining compatibility - see comments
131159 ** is empty - a factor that can only be determined at run-time. In that
131172 Select *pSelect, /* A SELECT statement to use as the data source */
131176 sqlite3 *db = pParse->db;
131179 Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
131180 SrcItem *pItem; /* An element of pSelect->pSrc */
131183 int iSrc, iDest; /* Cursors from source and destination */
131193 if( pParse->pWith || pSelect->pWith ){
131205 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
131208 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
131209 if( pSelect->pSrc->nSrc!=1 ){
131212 if( pSelect->pSrc->a[0].pSelect ){
131215 if( pSelect->pWhere ){
131218 if( pSelect->pOrderBy ){
131223 if( pSelect->pGroupBy ){
131226 if( pSelect->pLimit ){
131229 if( pSelect->pPrior ){
131232 if( pSelect->selFlags & SF_Distinct ){
131235 pEList = pSelect->pEList;
131237 if( pEList->nExpr!=1 ){
131240 assert( pEList->a[0].pExpr );
131241 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
131249 pItem = pSelect->pSrc->a;
131254 if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
131259 return 0; /* source and destination must both be WITHOUT ROWID or not */
131264 if( pDest->nCol!=pSrc->nCol ){
131267 if( pDest->iPKey!=pSrc->iPKey ){
131270 if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
131271 return 0; /* Cannot feed from a non-strict into a strict table */
131273 for(i=0; i<pDest->nCol; i++){
131274 Column *pDestCol = &pDest->aCol[i];
131275 Column *pSrcCol = &pSrc->aCol[i];
131277 if( (db->mDbFlags & DBFLAG_Vacuum)==0
131278 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
131300 if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
131301 (pSrcCol->colFlags & COLFLAG_GENERATED) ){
131302 return 0; /* Both columns have the same generated-column type */
131304 /* But the transfer is only allowed if both the source and destination
131308 if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
131311 sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
131312 testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
131313 testcase( pDestCol->colFlags & COLFLAG_STORED );
131318 if( pDestCol->affinity!=pSrcCol->affinity ){
131325 if( pDestCol->notNull && !pSrcCol->notNull ){
131329 if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
131332 assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
131334 assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
131337 || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
131338 pSrcExpr->u.zToken)!=0)
131344 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
131348 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
131354 if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
131359 return 0; /* Corrupt schema - two indexes on the same btree */
131363 if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
131376 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
131380 if( (db->flags & SQLITE_CountRows)!=0 ){
131391 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
131394 iSrc = pParse->nTab++;
131395 iDest = pParse->nTab++;
131402 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
131403 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
131432 if( pDest->iPKey>=0 ){
131434 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
131442 }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
131446 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
131449 if( db->mDbFlags & DBFLAG_Vacuum ){
131456 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
131465 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
131466 sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
131474 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
131475 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
131477 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
131479 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
131483 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
131485 VdbeComment((v, "%s", pSrcIdx->zName));
131486 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
131489 VdbeComment((v, "%s", pDestIdx->zName));
131491 if( db->mDbFlags & DBFLAG_Vacuum ){
131496 ** order. In this case, instead of seeking within the b-tree as part
131498 ** OP_IdxInsert to seek to the point within the b-tree where each key
131506 for(i=0; i<pSrcIdx->nColumn; i++){
131507 const char *zColl = pSrcIdx->azColl[i];
131510 if( i==pSrcIdx->nColumn ){
131515 }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
131520 if( (db->mDbFlags & DBFLAG_Vacuum)==0
131554 ** The author disclaims copyright to this source code. In place of
131596 sqlite3_mutex_enter(db->mutex);
131603 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
131609 /* this happens for a comment or white-space */
131622 && db->flags&SQLITE_NullCallback)) ){
131649 /* EVIDENCE-OF: R-38229-40159 If the callback function to
131650 ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
131688 assert( (rc&db->errMask)==rc );
131689 sqlite3_mutex_leave(db->mutex);
131698 ** The author disclaims copyright to this source code. In place of
131718 ** The author disclaims copyright to this source code. In place of
132094 ** This header file is also used by the loadext.c source file
132095 ** (part of the main SQLite library - not an extension) so that
132102 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
132104 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
132106 #define sqlite3_bind_blob sqlite3_api->bind_blob
132107 #define sqlite3_bind_double sqlite3_api->bind_double
132108 #define sqlite3_bind_int sqlite3_api->bind_int
132109 #define sqlite3_bind_int64 sqlite3_api->bind_int64
132110 #define sqlite3_bind_null sqlite3_api->bind_null
132111 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
132112 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
132113 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
132114 #define sqlite3_bind_text sqlite3_api->bind_text
132115 #define sqlite3_bind_text16 sqlite3_api->bind_text16
132116 #define sqlite3_bind_value sqlite3_api->bind_value
132117 #define sqlite3_busy_handler sqlite3_api->busy_handler
132118 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
132119 #define sqlite3_changes sqlite3_api->changes
132120 #define sqlite3_close sqlite3_api->close
132121 #define sqlite3_collation_needed sqlite3_api->collation_needed
132122 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
132123 #define sqlite3_column_blob sqlite3_api->column_blob
132124 #define sqlite3_column_bytes sqlite3_api->column_bytes
132125 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
132126 #define sqlite3_column_count sqlite3_api->column_count
132127 #define sqlite3_column_database_name sqlite3_api->column_database_name
132128 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
132129 #define sqlite3_column_decltype sqlite3_api->column_decltype
132130 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
132131 #define sqlite3_column_double sqlite3_api->column_double
132132 #define sqlite3_column_int sqlite3_api->column_int
132133 #define sqlite3_column_int64 sqlite3_api->column_int64
132134 #define sqlite3_column_name sqlite3_api->column_name
132135 #define sqlite3_column_name16 sqlite3_api->column_name16
132136 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
132137 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
132138 #define sqlite3_column_table_name sqlite3_api->column_table_name
132139 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
132140 #define sqlite3_column_text sqlite3_api->column_text
132141 #define sqlite3_column_text16 sqlite3_api->column_text16
132142 #define sqlite3_column_type sqlite3_api->column_type
132143 #define sqlite3_column_value sqlite3_api->column_value
132144 #define sqlite3_commit_hook sqlite3_api->commit_hook
132145 #define sqlite3_complete sqlite3_api->complete
132146 #define sqlite3_complete16 sqlite3_api->complete16
132147 #define sqlite3_create_collation sqlite3_api->create_collation
132148 #define sqlite3_create_collation16 sqlite3_api->create_collation16
132149 #define sqlite3_create_function sqlite3_api->create_function
132150 #define sqlite3_create_function16 sqlite3_api->create_function16
132151 #define sqlite3_create_module sqlite3_api->create_module
132152 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
132153 #define sqlite3_data_count sqlite3_api->data_count
132154 #define sqlite3_db_handle sqlite3_api->db_handle
132155 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
132156 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
132157 #define sqlite3_errcode sqlite3_api->errcode
132158 #define sqlite3_errmsg sqlite3_api->errmsg
132159 #define sqlite3_errmsg16 sqlite3_api->errmsg16
132160 #define sqlite3_exec sqlite3_api->exec
132162 #define sqlite3_expired sqlite3_api->expired
132164 #define sqlite3_finalize sqlite3_api->finalize
132165 #define sqlite3_free sqlite3_api->free
132166 #define sqlite3_free_table sqlite3_api->free_table
132167 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
132168 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
132169 #define sqlite3_get_table sqlite3_api->get_table
132171 #define sqlite3_global_recover sqlite3_api->global_recover
132173 #define sqlite3_interrupt sqlite3_api->interruptx
132174 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
132175 #define sqlite3_libversion sqlite3_api->libversion
132176 #define sqlite3_libversion_number sqlite3_api->libversion_number
132177 #define sqlite3_malloc sqlite3_api->malloc
132178 #define sqlite3_mprintf sqlite3_api->mprintf
132179 #define sqlite3_open sqlite3_api->open
132180 #define sqlite3_open16 sqlite3_api->open16
132181 #define sqlite3_prepare sqlite3_api->prepare
132182 #define sqlite3_prepare16 sqlite3_api->prepare16
132183 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
132184 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
132185 #define sqlite3_profile sqlite3_api->profile
132186 #define sqlite3_progress_handler sqlite3_api->progress_handler
132187 #define sqlite3_realloc sqlite3_api->realloc
132188 #define sqlite3_reset sqlite3_api->reset
132189 #define sqlite3_result_blob sqlite3_api->result_blob
132190 #define sqlite3_result_double sqlite3_api->result_double
132191 #define sqlite3_result_error sqlite3_api->result_error
132192 #define sqlite3_result_error16 sqlite3_api->result_error16
132193 #define sqlite3_result_int sqlite3_api->result_int
132194 #define sqlite3_result_int64 sqlite3_api->result_int64
132195 #define sqlite3_result_null sqlite3_api->result_null
132196 #define sqlite3_result_text sqlite3_api->result_text
132197 #define sqlite3_result_text16 sqlite3_api->result_text16
132198 #define sqlite3_result_text16be sqlite3_api->result_text16be
132199 #define sqlite3_result_text16le sqlite3_api->result_text16le
132200 #define sqlite3_result_value sqlite3_api->result_value
132201 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
132202 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
132203 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
132204 #define sqlite3_snprintf sqlite3_api->xsnprintf
132205 #define sqlite3_step sqlite3_api->step
132206 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
132207 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
132208 #define sqlite3_total_changes sqlite3_api->total_changes
132209 #define sqlite3_trace sqlite3_api->trace
132211 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
132213 #define sqlite3_update_hook sqlite3_api->update_hook
132214 #define sqlite3_user_data sqlite3_api->user_data
132215 #define sqlite3_value_blob sqlite3_api->value_blob
132216 #define sqlite3_value_bytes sqlite3_api->value_bytes
132217 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
132218 #define sqlite3_value_double sqlite3_api->value_double
132219 #define sqlite3_value_int sqlite3_api->value_int
132220 #define sqlite3_value_int64 sqlite3_api->value_int64
132221 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
132222 #define sqlite3_value_text sqlite3_api->value_text
132223 #define sqlite3_value_text16 sqlite3_api->value_text16
132224 #define sqlite3_value_text16be sqlite3_api->value_text16be
132225 #define sqlite3_value_text16le sqlite3_api->value_text16le
132226 #define sqlite3_value_type sqlite3_api->value_type
132227 #define sqlite3_vmprintf sqlite3_api->vmprintf
132228 #define sqlite3_vsnprintf sqlite3_api->xvsnprintf
132229 #define sqlite3_overload_function sqlite3_api->overload_function
132230 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
132231 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
132232 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
132233 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
132234 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
132235 #define sqlite3_blob_close sqlite3_api->blob_close
132236 #define sqlite3_blob_open sqlite3_api->blob_open
132237 #define sqlite3_blob_read sqlite3_api->blob_read
132238 #define sqlite3_blob_write sqlite3_api->blob_write
132239 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
132240 #define sqlite3_file_control sqlite3_api->file_control
132241 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
132242 #define sqlite3_memory_used sqlite3_api->memory_used
132243 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
132244 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
132245 #define sqlite3_mutex_free sqlite3_api->mutex_free
132246 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
132247 #define sqlite3_mutex_try sqlite3_api->mutex_try
132248 #define sqlite3_open_v2 sqlite3_api->open_v2
132249 #define sqlite3_release_memory sqlite3_api->release_memory
132250 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
132251 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
132252 #define sqlite3_sleep sqlite3_api->sleep
132253 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
132254 #define sqlite3_vfs_find sqlite3_api->vfs_find
132255 #define sqlite3_vfs_register sqlite3_api->vfs_register
132256 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
132257 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
132258 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
132259 #define sqlite3_result_error_code sqlite3_api->result_error_code
132260 #define sqlite3_test_control sqlite3_api->test_control
132261 #define sqlite3_randomness sqlite3_api->randomness
132262 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
132263 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
132264 #define sqlite3_limit sqlite3_api->limit
132265 #define sqlite3_next_stmt sqlite3_api->next_stmt
132266 #define sqlite3_sql sqlite3_api->sql
132267 #define sqlite3_status sqlite3_api->status
132268 #define sqlite3_backup_finish sqlite3_api->backup_finish
132269 #define sqlite3_backup_init sqlite3_api->backup_init
132270 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
132271 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
132272 #define sqlite3_backup_step sqlite3_api->backup_step
132273 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
132274 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
132275 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
132276 #define sqlite3_db_config sqlite3_api->db_config
132277 #define sqlite3_db_mutex sqlite3_api->db_mutex
132278 #define sqlite3_db_status sqlite3_api->db_status
132279 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
132280 #define sqlite3_log sqlite3_api->log
132281 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
132282 #define sqlite3_sourceid sqlite3_api->sourceid
132283 #define sqlite3_stmt_status sqlite3_api->stmt_status
132284 #define sqlite3_strnicmp sqlite3_api->strnicmp
132285 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
132286 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
132287 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
132288 #define sqlite3_wal_hook sqlite3_api->wal_hook
132289 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
132290 #define sqlite3_vtab_config sqlite3_api->vtab_config
132291 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
132293 #define sqlite3_close_v2 sqlite3_api->close_v2
132294 #define sqlite3_db_filename sqlite3_api->db_filename
132295 #define sqlite3_db_readonly sqlite3_api->db_readonly
132296 #define sqlite3_db_release_memory sqlite3_api->db_release_memory
132297 #define sqlite3_errstr sqlite3_api->errstr
132298 #define sqlite3_stmt_busy sqlite3_api->stmt_busy
132299 #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
132300 #define sqlite3_stricmp sqlite3_api->stricmp
132301 #define sqlite3_uri_boolean sqlite3_api->uri_boolean
132302 #define sqlite3_uri_int64 sqlite3_api->uri_int64
132303 #define sqlite3_uri_parameter sqlite3_api->uri_parameter
132304 #define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
132305 #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
132307 #define sqlite3_auto_extension sqlite3_api->auto_extension
132308 #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
132309 #define sqlite3_bind_text64 sqlite3_api->bind_text64
132310 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
132311 #define sqlite3_load_extension sqlite3_api->load_extension
132312 #define sqlite3_malloc64 sqlite3_api->malloc64
132313 #define sqlite3_msize sqlite3_api->msize
132314 #define sqlite3_realloc64 sqlite3_api->realloc64
132315 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
132316 #define sqlite3_result_blob64 sqlite3_api->result_blob64
132317 #define sqlite3_result_text64 sqlite3_api->result_text64
132318 #define sqlite3_strglob sqlite3_api->strglob
132320 #define sqlite3_value_dup sqlite3_api->value_dup
132321 #define sqlite3_value_free sqlite3_api->value_free
132322 #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
132323 #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
132325 #define sqlite3_value_subtype sqlite3_api->value_subtype
132326 #define sqlite3_result_subtype sqlite3_api->result_subtype
132328 #define sqlite3_status64 sqlite3_api->status64
132329 #define sqlite3_strlike sqlite3_api->strlike
132330 #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
132332 #define sqlite3_system_errno sqlite3_api->system_errno
132334 #define sqlite3_trace_v2 sqlite3_api->trace_v2
132335 #define sqlite3_expanded_sql sqlite3_api->expanded_sql
132337 #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
132339 #define sqlite3_prepare_v3 sqlite3_api->prepare_v3
132340 #define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
132341 #define sqlite3_bind_pointer sqlite3_api->bind_pointer
132342 #define sqlite3_result_pointer sqlite3_api->result_pointer
132343 #define sqlite3_value_pointer sqlite3_api->value_pointer
132345 #define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
132346 #define sqlite3_value_nochange sqlite3_api->value_nochange
132347 #define sqlite3_vtab_collation sqlite3_api->vtab_collation
132349 #define sqlite3_keyword_count sqlite3_api->keyword_count
132350 #define sqlite3_keyword_name sqlite3_api->keyword_name
132351 #define sqlite3_keyword_check sqlite3_api->keyword_check
132352 #define sqlite3_str_new sqlite3_api->str_new
132353 #define sqlite3_str_finish sqlite3_api->str_finish
132354 #define sqlite3_str_appendf sqlite3_api->str_appendf
132355 #define sqlite3_str_vappendf sqlite3_api->str_vappendf
132356 #define sqlite3_str_append sqlite3_api->str_append
132357 #define sqlite3_str_appendall sqlite3_api->str_appendall
132358 #define sqlite3_str_appendchar sqlite3_api->str_appendchar
132359 #define sqlite3_str_reset sqlite3_api->str_reset
132360 #define sqlite3_str_errcode sqlite3_api->str_errcode
132361 #define sqlite3_str_length sqlite3_api->str_length
132362 #define sqlite3_str_value sqlite3_api->str_value
132364 #define sqlite3_create_window_function sqlite3_api->create_window_function
132366 #define sqlite3_normalized_sql sqlite3_api->normalized_sql
132368 #define sqlite3_stmt_isexplain sqlite3_api->stmt_isexplain
132369 #define sqlite3_value_frombind sqlite3_api->value_frombind
132371 #define sqlite3_drop_modules sqlite3_api->drop_modules
132373 #define sqlite3_hard_heap_limit64 sqlite3_api->hard_heap_limit64
132374 #define sqlite3_uri_key sqlite3_api->uri_key
132375 #define sqlite3_filename_database sqlite3_api->filename_database
132376 #define sqlite3_filename_journal sqlite3_api->filename_journal
132377 #define sqlite3_filename_wal sqlite3_api->filename_wal
132379 #define sqlite3_create_filename sqlite3_api->create_filename
132380 #define sqlite3_free_filename sqlite3_api->free_filename
132381 #define sqlite3_database_file_object sqlite3_api->database_file_object
132383 #define sqlite3_txn_state sqlite3_api->txn_state
132385 #define sqlite3_changes64 sqlite3_api->changes64
132386 #define sqlite3_total_changes64 sqlite3_api->total_changes64
132388 #define sqlite3_autovacuum_pages sqlite3_api->autovacuum_pages
132390 #define sqlite3_error_offset sqlite3_api->error_offset
132391 #define sqlite3_vtab_rhs_value sqlite3_api->vtab_rhs_value
132392 #define sqlite3_vtab_distinct sqlite3_api->vtab_distinct
132393 #define sqlite3_vtab_in sqlite3_api->vtab_in
132394 #define sqlite3_vtab_in_first sqlite3_api->vtab_in_first
132395 #define sqlite3_vtab_in_next sqlite3_api->vtab_in_next
132398 #define sqlite3_deserialize sqlite3_api->deserialize
132399 #define sqlite3_serialize sqlite3_api->serialize
132401 #define sqlite3_db_name sqlite3_api->db_name
132403 #define sqlite3_value_encoding sqlite3_api->value_encoding
132405 #define sqlite3_set_droptable_handle sqlite3_api->set_droptable_handle
132418 # define SQLITE_EXTENSION_INIT1 /*no-op*/
132420 # define SQLITE_EXTENSION_INIT3 /*no-op*/
132962 sqlite3_vfs *pVfs = db->pVfs;
132994 if( (db->flags & SQLITE_LoadExtension)==0 ){
133003 /* tag-20210611-1. Some dlopen() implementations will segfault if given
133041 for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){}
133061 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
133080 /* Append the new shared library handle to the db->aExtension array. */
133081 aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
133085 if( db->nExtension>0 ){
133086 memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
133088 sqlite3DbFree(db, db->aExtension);
133089 db->aExtension = aHandle;
133091 db->aExtension[db->nExtension++] = handle;
133102 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
133114 sqlite3_mutex_enter(db->mutex);
133117 sqlite3_mutex_leave(db->mutex);
133127 assert( sqlite3_mutex_held(db->mutex) );
133128 for(i=0; i<db->nExtension; i++){
133129 sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
133131 sqlite3DbFree(db, db->aExtension);
133139 sqlite3_mutex_enter(db->mutex);
133141 db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
133143 db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
133145 sqlite3_mutex_leave(db->mutex);
133166 ** we have to locate the state vector at run-time. In the more common
133226 ** routine is a no-op.
133241 for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
133243 wsdAutoext.nExt--;
133322 ** The author disclaims copyright to this source code. In place of
133412 #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
133416 #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
133418 /* Names of columns for pragmas that return multi-column result
133419 ** or that return single-column results where the name of the
133486 /* Definitions of all built-in pragmas */
134117 ** Interpret the given string as an auto-vacuum mode value.
134135 ** backed temporary databases, 2 for the Red-Black tree in memory database
134136 ** and 0 to use the compile-time default.
134140 return z[0] - '0';
134157 sqlite3 *db = pParse->db;
134158 if( db->aDb[1].pBt!=0 ){
134159 if( !db->autoCommit
134160 || sqlite3BtreeTxnState(db->aDb[1].pBt)!=SQLITE_TXN_NONE
134166 sqlite3BtreeClose(db->aDb[1].pBt);
134167 db->aDb[1].pBt = 0;
134182 sqlite3 *db = pParse->db;
134183 if( db->temp_store==ts ) return SQLITE_OK;
134187 db->temp_store = (u8)ts;
134199 u8 n = pPragma->nPragCName;
134202 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
134205 for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
134239 if( db->autoCommit ){
134240 Db *pDb = db->aDb;
134241 int n = db->nDb;
134247 assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
134248 while( (n--) > 0 ){
134249 if( pDb->pBt ){
134250 sqlite3BtreeSetPagerFlags(pDb->pBt,
134251 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
134258 # define setAllPagerFlags(X) /* no-op */
134263 ** Return a human-readable name for a constraint resolution action.
134284 ** journal-mode name.
134311 upr = ArraySize(aPragmaName)-1;
134317 upr = mid - 1;
134332 int isBuiltin, /* True if this is a built-in function */
134343 for(; p; p=p->pNext){
134352 if( p->xSFunc==0 ) continue;
134353 if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0
134358 if( p->xValue!=0 ){
134360 }else if( p->xFinalize!=0 ){
134366 p->zName, isBuiltin,
134367 zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK],
134368 p->nArg,
134369 (p->funcFlags & mask) ^ SQLITE_INNOCUOUS
134378 ** Generate code to output a single-column result row with a value of the
134411 int minusFlag /* True if a '-' sign preceded <value> */
134413 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
134414 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
134420 sqlite3 *db = pParse->db; /* The database connection */
134433 pParse->nMem = 2;
134439 pDb = &db->aDb[iDb];
134451 zRight = sqlite3MPrintf(db, "-%T", pValue);
134457 zDb = pId2->n>0 ? pDb->zDbSName : 0;
134462 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
134464 ** handled the pragma and generate a no-op prepared statement.
134466 ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
134471 ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
134481 db->busyHandler.nBusy = 0;
134495 pParse->nErr++;
134496 pParse->rc = rc;
134512 /* IMP: R-43042-22504 No error messages are generated if an
134518 if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
134523 if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
134524 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
134530 switch( pPragma->ePragTyp ){
134565 pParse->nMem += 2;
134577 pDb->pSchema->cache_size = size;
134578 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
134595 Btree *pBt = pDb->pBt;
134601 /* Malloc may fail when setting the page-size, as there is an internal
134604 db->nextPagesize = sqlite3Atoi(zRight);
134605 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){
134621 Btree *pBt = pDb->pBt;
134622 int b = -1;
134631 if( pId2->n==0 && b>=0 ){
134633 for(ii=0; ii<db->nDb; ii++){
134634 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
134663 iReg = ++pParse->nMem;
134687 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
134690 ** the locking-mode of the main database).
134692 eMode = db->dfltLockMode;
134695 if( pId2->n==0 ){
134697 ** of the PRAGMA command. In this case the locking-mode must be
134705 assert(pDb==&db->aDb[0]);
134706 for(ii=2; ii<db->nDb; ii++){
134707 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
134710 db->dfltLockMode = (u8)eMode;
134712 pPager = sqlite3BtreePager(pDb->pBt);
134749 if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){
134750 /* Do not allow journal-mode "OFF" in defensive since the database
134755 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
134758 pId2->n = 1;
134760 for(ii=db->nDb-1; ii>=0; ii--){
134761 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
134777 Pager *pPager = sqlite3BtreePager(pDb->pBt);
134778 i64 iLimit = -2;
134781 if( iLimit<-1 ) iLimit = -1;
134794 ** Get or set the value of the database 'auto-vacuum' parameter.
134799 Btree *pBt = pDb->pBt;
134806 db->nextAutovac = (u8)eAuto;
134808 ** incr-vacuum flags. This is required in case this connection
134810 ** as an auto-vacuum capable db.
134817 ** that this really is an auto-vacuum capable database.
134836 aOp[4].p3 = eAuto - 1;
134859 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
134875 ** number of pages is adjusted so that the cache uses -N kibibytes
134881 returnSingleInt(v, pDb->pSchema->cache_size);
134884 pDb->pSchema->cache_size = size;
134885 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
134902 ** number of pages is adjusted so that the cache uses -N kibibytes
134916 (db->flags & SQLITE_CacheSpill)==0 ? 0 :
134917 sqlite3BtreeSetSpillSize(pDb->pBt,0));
134921 sqlite3BtreeSetSpillSize(pDb->pBt, size);
134924 db->flags |= SQLITE_CacheSpill;
134926 db->flags &= ~(u64)SQLITE_CacheSpill;
134955 if( pId2->n==0 ) db->szMmap = sz;
134956 for(ii=db->nDb-1; ii>=0; ii--){
134957 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
134958 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
134962 sz = -1;
134971 pParse->nErr++;
134972 pParse->rc = rc;
134985 ** Note that it is possible for the library compile-time options to
134990 returnSingleInt(v, db->temp_store);
135015 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
135023 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
135024 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
135062 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
135093 Pager *pPager = sqlite3BtreePager(pDb->pBt);
135100 Pager *pPager = sqlite3BtreePager(pDb->pBt);
135130 returnSingleInt(v, pDb->safety_level-1);
135132 if( !db->autoCommit ){
135138 pDb->safety_level = iLevel;
135139 pDb->bSyncSet = 1;
135151 returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
135153 u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */
135154 if( db->autoCommit==0 ){
135156 ** in auto-commit mode. */
135160 if( db->auth.authLevel==UAUTH_User ){
135161 /* Do not allow non-admin users to modify the schema arbitrarily */
135167 db->flags |= mask;
135169 db->flags &= ~mask;
135170 if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
135174 /* IMP: R-60817-01178 If the argument is "RESET" then schema
135181 /* Many of the flag-pragmas modify the code generated by the SQL
135204 ** pk: Non-zero for PK fields.
135215 pParse->nMem = 7;
135217 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
135220 if( pCol->colFlags & COLFLAG_NOINSERT ){
135221 if( pPragma->iArg==0 ){
135225 if( pCol->colFlags & COLFLAG_VIRTUAL ){
135227 }else if( pCol->colFlags & COLFLAG_STORED ){
135229 }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
135233 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
135238 for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
135241 assert( pColExpr==0 || pColExpr->op==TK_SPAN || isHidden>=2 );
135244 sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
135245 i-nHidden,
135246 pCol->zCnName,
135248 pCol->notNull ? 1 : 0,
135249 (isHidden>=2 || pColExpr==0) ? 0 : pColExpr->u.zToken,
135272 pParse->nMem = 6;
135274 for(ii=0; ii<db->nDb; ii++){
135278 if( zDb && sqlite3_stricmp(zDb, db->aDb[ii].zDbSName)!=0 ) continue;
135285 pHash = &db->aDb[ii].pSchema->tblHash;
135287 while( initNCol-- ){
135292 if( pTab->nCol==0 ){
135293 char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName);
135296 (void)sqlite3_prepare(db, zSql, -1, &pDummy, 0);
135300 if( db->mallocFailed ){
135301 sqlite3ErrorMsg(db->pParse, "out of memory");
135302 db->pParse->rc = SQLITE_NOMEM_BKPT;
135304 pHash = &db->aDb[ii].pSchema->tblHash;
135313 if( zRight && sqlite3_stricmp(zRight, pTab->zName)!=0 ) continue;
135318 }else if( pTab->tabFlags & TF_Shadow ){
135324 db->aDb[ii].zDbSName,
135325 sqlite3PreferredTableName(pTab->zName),
135327 pTab->nCol,
135328 (pTab->tabFlags & TF_WithoutRowid)!=0,
135329 (pTab->tabFlags & TF_Strict)!=0
135340 pParse->nMem = 5;
135342 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
135345 sqlite3PreferredTableName(pTab->zName),
135347 pTab->szTabRow,
135348 pTab->nRowLogEst,
135349 pTab->tabFlags);
135350 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
135352 pIdx->zName,
135353 pIdx->szIdxRow,
135354 pIdx->aiRowLogEst[0],
135355 pIdx->hasStat1);
135377 int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
135380 if( pPragma->iArg ){
135382 mx = pIdx->nColumn;
135383 pParse->nMem = 6;
135386 mx = pIdx->nKeyCol;
135387 pParse->nMem = 3;
135389 pTab = pIdx->pTable;
135391 assert( pParse->nMem<=pPragma->nPragCName );
135393 i16 cnum = pIdx->aiColumn[i];
135395 cnum<0 ? 0 : pTab->aCol[cnum].zCnName);
135396 if( pPragma->iArg ){
135398 pIdx->aSortOrder[i],
135399 pIdx->azColl[i],
135400 i<pIdx->nKeyCol);
135402 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
135414 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
135415 pParse->nMem = 5;
135417 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
135421 pIdx->zName,
135423 azOrigin[pIdx->idxType],
135424 pIdx->pPartIdxWhere!=0);
135432 pParse->nMem = 3;
135433 for(i=0; i<db->nDb; i++){
135434 if( db->aDb[i].pBt==0 ) continue;
135435 assert( db->aDb[i].zDbSName!=0 );
135438 db->aDb[i].zDbSName,
135439 sqlite3BtreeGetFilename(db->aDb[i].pBt));
135447 pParse->nMem = 2;
135448 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
135450 sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
135460 int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
135461 pParse->nMem = 6;
135463 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
135464 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
135468 for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
135470 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
135479 pParse->nMem = 1;
135480 for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
135482 sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
135505 pFK = pTab->u.tab.pFKey;
135507 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
135509 pParse->nMem = 8;
135513 for(j=0; j<pFK->nCol; j++){
135517 pFK->zTo,
135518 pTab->aCol[pFK->aCol[j].iFrom].zCnName,
135519 pFK->aCol[j].zCol,
135520 actionName(pFK->aAction[1]), /* ON UPDATE */
135521 actionName(pFK->aAction[0]), /* ON DELETE */
135525 pFK = pFK->pNextFrom;
135550 regResult = pParse->nMem+1;
135551 pParse->nMem += 4;
135552 regRow = ++pParse->nMem;
135553 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
135562 if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
135563 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
135564 zDb = db->aDb[iDb].zDbSName;
135566 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
135567 if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
135569 sqlite3VdbeLoadString(v, regResult, pTab->zName);
135571 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
135572 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
135575 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
135581 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
135589 assert( pParse->nErr>0 || pFK==0 );
135591 if( pParse->nTab<i ) pParse->nTab = i;
135594 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
135595 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
135600 assert( x==0 || db->mallocFailed );
135608 if( regRow+pFK->nCol>pParse->nMem ) pParse->nMem = regRow+pFK->nCol;
135609 for(j=0; j<pFK->nCol; j++){
135610 int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
135618 sqlite3VdbeAddOp4(v, OP_Affinity, regRow, pFK->nCol, 0,
135619 sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
135620 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regRow, pFK->nCol);
135626 assert( pFK->nCol==1 || db->mallocFailed );
135635 sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
135674 ** without the overhead of cross-checking indexes. Quick_check
135702 ** to -1 here, to indicate that the VDBE should verify the integrity
135705 assert( iDb==0 || pId2->z );
135706 if( pId2->z==0 ) iDb = -1;
135709 pParse->nMem = 6;
135720 iDb>=0 ? db->aDb[iDb].zDbSName : 0);
135723 sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
135726 for(i=0; i<db->nDb; i++){
135738 /* Do an integrity check of the B-Tree
135744 pTbls = &db->aDb[i].pSchema->tblHash;
135751 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
135764 if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
135765 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
135766 aRoot[++cnt] = pIdx->tnum;
135772 pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
135775 /* Do the b-tree integrity checks */
135780 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
135794 int r1 = -1;
135797 int mxCol; /* Maximum non-virtual column number */
135806 r2 = sqlite3GetTempRange(pParse, pPk->nKeyCol);
135807 sqlite3VdbeAddOp3(v, OP_Null, 1, r2, r2+pPk->nKeyCol-1);
135812 ** reg[8+i] counts the number of entries in the i-th index
135815 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
135818 assert( pParse->nMem>=8+j );
135823 /* Fetch the right-most column from the table. This will cause
135828 mxCol = pTab->nCol-1;
135830 && ((pTab->aCol[mxCol].colFlags & COLFLAG_VIRTUAL)!=0
135831 || pTab->iPKey==mxCol) ) mxCol--;
135842 a1 = sqlite3VdbeAddOp4Int(v, OP_IdxGT, iDataCur, 0,r2,pPk->nKeyCol);
135847 pTab->zName);
135852 for(j=0; j<pPk->nKeyCol; j++){
135860 ** (2) Datatype must be exact for non-ANY columns in STRICT tables
135861 ** (3) Datatype for TEXT columns in non-STRICT tables must be
135863 ** (4) Datatype for numeric columns in non-STRICT tables must not
135866 bStrict = (pTab->tabFlags & TF_Strict)!=0;
135867 for(j=0; j<pTab->nCol; j++){
135869 Column *pCol = pTab->aCol + j; /* The column to be checked */
135875 if( j==pTab->iPKey ) continue;
135877 doTypeCheck = pCol->eCType>COLTYPE_ANY;
135879 doTypeCheck = pCol->affinity>SQLITE_AFF_BLOB;
135881 if( pCol->notNull==0 && !doTypeCheck ) continue;
135885 if( pCol->colFlags & COLFLAG_VIRTUAL ){
135887 p1 = -1;
135890 if( pCol->iDflt ){
135893 pCol->affinity, &pDfltValue);
135911 if( pCol->notNull ){
135916 zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
135917 pCol->zCnName);
135927 /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
135937 assert( pCol->eCType>=1 && pCol->eCType<=sizeof(aStdTypeMask) );
135938 sqlite3VdbeChangeP5(v, aStdTypeMask[pCol->eCType-1]);
135940 zErr = sqlite3MPrintf(db, "non-%s value in %s.%s",
135941 sqlite3StdType[pCol->eCType-1],
135942 pTab->zName, pTab->aCol[j].zCnName);
135944 }else if( !bStrict && pCol->affinity==SQLITE_AFF_TEXT ){
135945 /* (3) Datatype for TEXT columns in non-STRICT tables must be
135951 pTab->zName, pTab->aCol[j].zCnName);
135953 }else if( !bStrict && pCol->affinity>=SQLITE_AFF_NUMERIC ){
135954 /* (4) Datatype for numeric columns in non-STRICT tables must not
135963 sqlite3VdbeAddOp4Int(v, OP_IsType, -1, labelOk, 3, p4);
135967 pTab->zName, pTab->aCol[j].zCnName);
135975 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
135976 ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
135977 if( db->mallocFailed==0 ){
135982 pParse->iSelfTab = iDataCur + 1;
135983 for(k=pCheck->nExpr-1; k>0; k--){
135984 sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
135986 sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
135989 pParse->iSelfTab = 0;
135991 pTab->zName);
136000 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
136010 pIdx->nColumn); VdbeCoverage(v);
136015 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
136026 for(kk=0; kk<pIdx->nKeyCol; kk++){
136027 int iCol = pIdx->aiColumn[kk];
136028 assert( iCol!=XN_ROWID && iCol<pTab->nCol );
136029 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
136037 pIdx->nKeyCol); VdbeCoverage(v);
136038 sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
136047 sqlite3VdbeJumpHere(v, loopTop-1);
136050 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
136055 sqlite3VdbeLoadString(v, 4, pIdx->zName);
136061 sqlite3ReleaseTempRange(pParse, r2, pPk->nKeyCol);
136081 aOp[0].p2 = 1-mxErr;
136087 sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
136096 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
136101 ** The second form of this pragma is a no-op if the main database file
136122 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
136123 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
136124 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
136127 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
136137 returnSingleText(v, encnames[ENC(pParse->db)].zName);
136144 if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
136145 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
136146 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
136147 u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
136153 if( !pEnc->zName ){
136178 ** the value of the schema-version and user-version, respectively. Both
136179 ** the schema-version and the user-version are 32-bit signed integers
136182 ** The schema-cookie is usually only manipulated internally by SQLite. It
136189 ** the schema-version is potentially dangerous and may lead to program
136192 ** The user-version is not used internally by SQLite. It may be used by
136196 int iCookie = pPragma->iArg; /* Which cookie to read or write */
136198 if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
136213 if( iCookie==BTREE_SCHEMA_VERSION && (db->flags & SQLITE_Defensive)!=0 ){
136215 ** mode. Change the OP_SetCookie opcode into a no-op. */
136242 ** Return the names of all compile-time options used in this build,
136248 pParse->nMem = 1;
136265 int iBt = (pId2->z?iDb:SQLITE_MAX_DB);
136276 pParse->nMem = 3;
136295 db->xWalCallback==sqlite3WalDefaultHook ?
136296 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
136304 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
136346 ** ever added that should be off by default, those off-by-default
136356 ** (2) The query planner used sqlite_stat1-style statistics for one or
136384 iTabCur = pParse->nTab++;
136385 for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
136388 pSchema = db->aDb[iDb].pSchema;
136389 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
136395 if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue;
136398 szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 );
136399 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
136400 if( !pIdx->hasStat1 ){
136412 db->aDb[iDb].zDbSName, pTab->zName);
136436 assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
136440 returnSingleInt(v, db->busyTimeout);
136448 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
136450 ** specified and is a non-negative integer.
136451 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
136453 ** sqlite3_soft_heap_limit64(-1) C-language function.
136460 returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
136471 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
136478 sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
136481 returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
136500 returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
136514 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK /* IMP: R-40975-20399 */
136517 db->nAnalysisLimit = (int)(N&0x7fffffff);
136519 returnSingleInt(v, db->nAnalysisLimit); /* IMP: R-57594-65522 */
136532 pParse->nMem = 2;
136533 for(i=0; i<db->nDb; i++){
136537 if( db->aDb[i].zDbSName==0 ) continue;
136538 pBt = db->aDb[i].pBt;
136541 }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
136545 sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
136553 ** ---------- ------
136566 if( pPragma->iArg==2 || pPragma->iArg==3 ){
136576 n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1;
136578 if( (pPragma->iArg & 1)==0 ){
136594 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
136603 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
136608 if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
136659 for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
136664 sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
136668 if( pPragma->mPragFlg & PragFlg_Result1 ){
136672 if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
136678 assert( strlen(zBuf) < sizeof(zBuf)-1 );
136686 pTab->pName = pPragma;
136687 pTab->db = db;
136688 pTab->iHidden = i;
136689 pTab->nHidden = j;
136721 pIdxInfo->estimatedCost = (double)1;
136722 if( pTab->nHidden==0 ){ return SQLITE_OK; }
136723 pConstraint = pIdxInfo->aConstraint;
136726 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
136727 if( pConstraint->usable==0 ) continue;
136728 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
136729 if( pConstraint->iColumn < pTab->iHidden ) continue;
136730 j = pConstraint->iColumn - pTab->iHidden;
136735 pIdxInfo->estimatedCost = (double)2147483647;
136736 pIdxInfo->estimatedRows = 2147483647;
136739 j = seen[0]-1;
136740 pIdxInfo->aConstraintUsage[j].argvIndex = 1;
136741 pIdxInfo->aConstraintUsage[j].omit = 1;
136743 pIdxInfo->estimatedCost = (double)20;
136744 pIdxInfo->estimatedRows = 20;
136745 j = seen[1]-1;
136746 pIdxInfo->aConstraintUsage[j].argvIndex = 2;
136747 pIdxInfo->aConstraintUsage[j].omit = 1;
136757 pCsr->base.pVtab = pVtab;
136758 *ppCursor = &pCsr->base;
136765 sqlite3_finalize(pCsr->pPragma);
136766 pCsr->pPragma = 0;
136767 for(i=0; i<ArraySize(pCsr->azArg); i++){
136768 sqlite3_free(pCsr->azArg[i]);
136769 pCsr->azArg[i] = 0;
136787 pCsr->iRowid++;
136788 assert( pCsr->pPragma );
136789 if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
136790 rc = sqlite3_finalize(pCsr->pPragma);
136791 pCsr->pPragma = 0;
136806 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
136815 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
136818 assert( j<ArraySize(pCsr->azArg) );
136819 assert( pCsr->azArg[j]==0 );
136821 pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
136822 if( pCsr->azArg[j]==0 ){
136827 sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
136829 if( pCsr->azArg[1] ){
136830 sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
136832 sqlite3_str_appendall(&acc, pTab->pName->zName);
136833 if( pCsr->azArg[0] ){
136834 sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
136838 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
136841 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
136852 return (pCsr->pPragma==0);
136864 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
136865 if( i<pTab->iHidden ){
136866 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
136868 sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
136878 *p = pCsr->iRowid;
136885 0, /* xCreate - create a table */
136886 pragmaVtabConnect, /* xConnect - connect to an existing table */
136887 pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
136888 pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
136889 0, /* xDestroy - Drop a table */
136890 pragmaVtabOpen, /* xOpen - open a cursor */
136891 pragmaVtabClose, /* xClose - close a cursor */
136892 pragmaVtabFilter, /* xFilter - configure scan constraints */
136893 pragmaVtabNext, /* xNext - advance a cursor */
136895 pragmaVtabColumn, /* xColumn - read data */
136896 pragmaVtabRowid, /* xRowid - read data */
136897 0, /* xUpdate - write data */
136898 0, /* xBegin - begin transaction */
136899 0, /* xSync - sync transaction */
136900 0, /* xCommit - commit transaction */
136901 0, /* xRollback - rollback transaction */
136902 0, /* xFindFunction - function overloading */
136903 0, /* xRename - rename the table */
136920 if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
136921 assert( sqlite3HashFind(&db->aModule, zName)==0 );
136934 ** The author disclaims copyright to this source code. In place of
136957 sqlite3 *db = pData->db;
136958 if( db->mallocFailed ){
136959 pData->rc = SQLITE_NOMEM_BKPT;
136960 }else if( pData->pzErrMsg[0]!=0 ){
136962 }else if( pData->mInitFlags & (INITFLAG_AlterMask) ){
136968 *pData->pzErrMsg = sqlite3MPrintf(db,
136970 azAlterType[(pData->mInitFlags&INITFLAG_AlterMask)-1],
136973 pData->rc = SQLITE_ERROR;
136974 }else if( db->flags & SQLITE_WriteSchema ){
136975 pData->rc = SQLITE_CORRUPT_BKPT;
136980 if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
136981 *pData->pzErrMsg = z;
136982 pData->rc = SQLITE_CORRUPT_BKPT;
136993 for(p=pIndex->pTable->pIndex; p; p=p->pNext){
136994 if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
137002 const char *zSql, /* UTF-8 encoded SQL statement. */
137027 sqlite3 *db = pData->db;
137028 int iDb = pData->iDb;
137032 assert( sqlite3_mutex_held(db->mutex) );
137033 db->mDbFlags |= DBFLAG_EncodingFixed;
137035 pData->nInitRow++;
137036 if( db->mallocFailed ){
137041 assert( iDb>=0 && iDb<db->nDb );
137048 ** But because db->init.busy is set to 1, no VDBE code is generated
137058 u8 saved_iDb = db->init.iDb;
137062 assert( db->init.busy );
137063 db->init.iDb = iDb;
137064 if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
137065 || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
137071 db->init.orphanTrigger = 0;
137072 db->init.azInit = (const char**)argv;
137074 TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0);
137075 rc = db->errCode;
137077 db->init.iDb = saved_iDb;
137078 /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
137080 if( db->init.orphanTrigger ){
137083 if( rc > pData->rc ) pData->rc = rc;
137091 db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
137103 pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);
137107 if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0
137108 || pIndex->tnum<2
137109 || pIndex->tnum>pData->mxPage
137140 int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);
137142 assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
137143 assert( iDb>=0 && iDb<db->nDb );
137144 assert( db->aDb[iDb].pSchema );
137145 assert( sqlite3_mutex_held(db->mutex) );
137146 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
137148 db->init.busy = 1;
137150 /* Construct the in-memory representation schema tables (sqlite_schema or
137154 ** the schema table as read-only. */
137170 db->mDbFlags &= mask;
137178 pDb = &db->aDb[iDb];
137179 if( pDb->pBt==0 ){
137186 /* If there is not already a read-only (or read-write) transaction opened
137187 ** on the b-tree database, open one now. If a transaction is opened, it
137189 sqlite3BtreeEnter(pDb->pBt);
137190 if( sqlite3BtreeTxnState(pDb->pBt)==SQLITE_TXN_NONE ){
137191 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
137206 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
137217 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
137219 if( (db->flags & SQLITE_ResetDatabase)!=0 ){
137222 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
137224 /* If opening a non-empty database, check the text encoding. For the
137229 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
137230 if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
137234 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
137242 if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){
137250 pDb->pSchema->enc = ENC(db);
137252 if( pDb->pSchema->cache_size==0 ){
137254 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
137256 pDb->pSchema->cache_size = size;
137258 pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
137260 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
137266 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
137269 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
137270 if( pDb->pSchema->file_format==0 ){
137271 pDb->pSchema->file_format = 1;
137273 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
137284 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
137285 db->flags &= ~(u64)SQLITE_LegacyFileFmt;
137290 assert( db->init.busy );
137291 initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
137296 db->aDb[iDb].zDbSName, zSchemaTabName);
137300 xAuth = db->xAuth;
137301 db->xAuth = 0;
137305 db->xAuth = xAuth;
137316 assert( pDb == &(db->aDb[iDb]) );
137317 if( db->mallocFailed ){
137320 pDb = &db->aDb[iDb];
137322 if( rc==SQLITE_OK || ((db->flags&SQLITE_NoSchemaError) && rc!=SQLITE_NOMEM)){
137343 sqlite3BtreeCommit(pDb->pBt);
137345 sqlite3BtreeLeave(pDb->pBt);
137354 db->init.busy = 0;
137359 ** Initialize all database files - the main database file, the file
137369 int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
137371 assert( sqlite3_mutex_held(db->mutex) );
137372 assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
137373 assert( db->init.busy==0 );
137375 assert( db->nDb>0 );
137382 for(i=db->nDb-1; i>0; i--){
137383 assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
137396 ** This routine is a no-op if the database schema is already initialized.
137401 sqlite3 *db = pParse->db;
137402 assert( sqlite3_mutex_held(db->mutex) );
137403 if( !db->init.busy ){
137404 rc = sqlite3Init(db, &pParse->zErrMsg);
137406 pParse->rc = rc;
137407 pParse->nErr++;
137408 }else if( db->noSharedCache ){
137409 db->mDbFlags |= DBFLAG_SchemaKnownOk;
137418 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
137419 ** make no changes to pParse->rc.
137422 sqlite3 *db = pParse->db;
137427 assert( pParse->checkSchema );
137428 assert( sqlite3_mutex_held(db->mutex) );
137429 for(iDb=0; iDb<db->nDb; iDb++){
137431 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
137434 /* If there is not already a read-only (or read-write) transaction opened
137435 ** on the b-tree database, open one now. If a transaction is opened, it
137436 ** will be closed immediately after reading the meta-value. */
137441 pParse->rc = SQLITE_NOMEM;
137448 ** value stored as part of the in-memory schema representation,
137452 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
137454 pParse->rc = SQLITE_SCHEMA;
137466 ** which database file in db->aDb[] the schema refers to.
137472 int i = -32768;
137474 /* If pSchema is NULL, then return -32768. This happens when code in
137476 ** created by a sub-select). In this case the return value of this
137479 ** We return -32768 instead of the more usual -1 simply because using
137480 ** -32768 as the incorrect index into db->aDb[] is much
137481 ** more likely to cause a segfault than -1 (of course there are assert()
137483 ** -32768 will still fit into a 16-bit signed integer.
137485 assert( sqlite3_mutex_held(db->mutex) );
137488 assert( i<db->nDb );
137489 if( db->aDb[i].pSchema==pSchema ){
137493 assert( i>=0 && i<db->nDb );
137502 sqlite3 *db = pParse->db;
137504 assert( db->pParse==pParse );
137505 assert( pParse->nested==0 );
137507 if( pParse->aTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock);
137509 while( pParse->pCleanup ){
137510 ParseCleanup *pCleanup = pParse->pCleanup;
137511 pParse->pCleanup = pCleanup->pNext;
137512 pCleanup->xCleanup(db, pCleanup->pPtr);
137515 if( pParse->aLabel ) sqlite3DbNNFreeNN(db, pParse->aLabel);
137516 if( pParse->pConstExpr ){
137517 sqlite3ExprListDelete(db, pParse->pConstExpr);
137519 assert( db->lookaside.bDisable >= pParse->disableLookaside );
137520 db->lookaside.bDisable -= pParse->disableLookaside;
137521 db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
137522 assert( pParse->db->pParse==pParse );
137523 db->pParse = pParse->pOuterParse;
137524 pParse->db = 0;
137525 pParse->disableLookaside = 0;
137536 ** common cleanups, we save a single NULL-pointer comparison in
137541 ** pParse->earlyCleanup flag is set in that case. Calling code show verify
137543 ** use-after-free errors following an OOM. The preferred way to do this is
137546 ** testcase( pParse->earlyCleanup );
137561 ParseCleanup *pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup));
137563 pCleanup->pNext = pParse->pCleanup;
137564 pParse->pCleanup = pCleanup;
137565 pCleanup->pPtr = pPtr;
137566 pCleanup->xCleanup = xCleanup;
137568 xCleanup(pParse->db, pPtr);
137571 pParse->earlyCleanup = 1;
137589 assert( db->pParse!=pParse );
137590 pParse->pOuterParse = db->pParse;
137591 db->pParse = pParse;
137592 pParse->db = db;
137593 if( db->mallocFailed ) sqlite3ErrorMsg(pParse, "out of memory");
137605 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
137609 const char *zSql, /* UTF-8 encoded SQL statement. */
137623 sParse.pOuterParse = db->pParse;
137624 db->pParse = &sParse;
137628 if( db->mallocFailed ) sqlite3ErrorMsg(&sParse, "out of memory");
137629 assert( sqlite3_mutex_held(db->mutex) );
137631 /* For a long-term use prepared statement avoid the use of
137642 ** some other database connection is holding a write-lock, which in
137663 if( !db->noSharedCache ){
137664 for(i=0; i<db->nDb; i++) {
137665 Btree *pBt = db->aDb[i].pBt;
137670 const char *zDb = db->aDb[i].zDbSName;
137672 testcase( db->flags & SQLITE_ReadUncommit );
137680 if( db->pDisconnect ) sqlite3VtabUnlockList(db);
137683 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
137685 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
137696 sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
137710 if( db->init.busy==0 ){
137711 sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
137713 if( db->mallocFailed ){
137718 if( sParse.checkSchema && db->init.busy==0 ){
137743 sParse.pTriggerPrg = pT->pNext;
137754 const char *zSql, /* UTF-8 encoded SQL statement. */
137771 sqlite3_mutex_enter(db->mutex);
137779 if( rc==SQLITE_OK || db->mallocFailed ) break;
137781 || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
137784 assert( (rc&db->errMask)==rc );
137785 db->busyHandler.nBusy = 0;
137786 sqlite3_mutex_leave(db->mutex);
137806 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
137810 assert( sqlite3_mutex_held(db->mutex) );
137812 rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
137840 const char *zSql, /* UTF-8 encoded SQL statement. */
137852 const char *zSql, /* UTF-8 encoded SQL statement. */
137858 /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
137870 const char *zSql, /* UTF-8 encoded SQL statement. */
137877 /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
137894 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
137898 const void *zSql, /* UTF-16 encoded SQL statement. */
137904 /* This function currently works by first transforming the UTF-16
137905 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
137925 sqlite3_mutex_enter(db->mutex);
137928 rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
137933 ** equivalent pointer into the UTF-16 string by counting the unicode
137935 ** the same number of characters into the UTF-16 string.
137937 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
137942 sqlite3_mutex_leave(db->mutex);
137956 const void *zSql, /* UTF-16 encoded SQL statement. */
137968 const void *zSql, /* UTF-16 encoded SQL statement. */
137980 const void *zSql, /* UTF-16 encoded SQL statement. */
138001 ** The author disclaims copyright to this source code. In place of
138031 ** The aDefer[] array is used by the sorter-references optimization. For
138041 ** When the sorter-reference optimization is used, there is one entry in the
138050 int regReturn; /* Register holding block-output return address */
138051 int labelBkOut; /* Start label for the block-output subroutine */
138078 Select *pPrior = p->pPrior;
138079 sqlite3ExprListDelete(db, p->pEList);
138080 sqlite3SrcListDelete(db, p->pSrc);
138081 sqlite3ExprDelete(db, p->pWhere);
138082 sqlite3ExprListDelete(db, p->pGroupBy);
138083 sqlite3ExprDelete(db, p->pHaving);
138084 sqlite3ExprListDelete(db, p->pOrderBy);
138085 sqlite3ExprDelete(db, p->pLimit);
138086 if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
138088 if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
138089 sqlite3WindowListDelete(db, p->pWinDefn);
138091 while( p->pWin ){
138092 assert( p->pWin->ppThis==&p->pWin );
138093 sqlite3WindowUnlinkFromSelect(p->pWin);
138106 pDest->eDest = (u8)eDest;
138107 pDest->iSDParm = iParm;
138108 pDest->iSDParm2 = 0;
138109 pDest->zAffSdst = 0;
138110 pDest->iSdst = 0;
138111 pDest->nSdst = 0;
138122 SrcList *pSrc, /* the FROM clause -- which tables to scan */
138132 pAllocated = pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
138134 assert( pParse->db->mallocFailed );
138139 sqlite3Expr(pParse->db,TK_ASTERISK,0));
138141 pNew->pEList = pEList;
138142 pNew->op = TK_SELECT;
138143 pNew->selFlags = selFlags;
138144 pNew->iLimit = 0;
138145 pNew->iOffset = 0;
138146 pNew->selId = ++pParse->nSelect;
138147 pNew->addrOpenEphm[0] = -1;
138148 pNew->addrOpenEphm[1] = -1;
138149 pNew->nSelectRow = 0;
138150 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
138151 pNew->pSrc = pSrc;
138152 pNew->pWhere = pWhere;
138153 pNew->pGroupBy = pGroupBy;
138154 pNew->pHaving = pHaving;
138155 pNew->pOrderBy = pOrderBy;
138156 pNew->pPrior = 0;
138157 pNew->pNext = 0;
138158 pNew->pLimit = pLimit;
138159 pNew->pWith = 0;
138161 pNew->pWin = 0;
138162 pNew->pWinDefn = 0;
138164 if( pParse->db->mallocFailed ) {
138165 clearSelect(pParse->db, pNew, pNew!=&standin);
138168 assert( pNew->pSrc!=0 || pParse->nErr>0 );
138182 ** Return a pointer to the right-most SELECT statement in a compound.
138185 while( p->pNext ) p = p->pNext;
138210 ** ------- ----- ----- ------------
138211 ** CROSS - - JT_CROSS
138212 ** INNER - - JT_INNER
138213 ** LEFT - - JT_LEFT|JT_OUTER
138214 ** LEFT OUTER - JT_LEFT|JT_OUTER
138215 ** RIGHT - - JT_RIGHT|JT_OUTER
138216 ** RIGHT OUTER - JT_RIGHT|JT_OUTER
138217 ** FULL - - JT_LEFT|JT_RIGHT|JT_OUTER
138218 ** FULL OUTER - JT_LEFT|JT_RIGHT|JT_OUTER
138219 ** NATURAL INNER - JT_NATURAL|JT_INNER
138220 ** NATURAL LEFT - JT_NATURAL|JT_LEFT|JT_OUTER
138222 ** NATURAL RIGHT - JT_NATURAL|JT_RIGHT|JT_OUTER
138224 ** NATURAL FULL - JT_NATURAL|JT_LEFT|JT_RIGHT
138228 ** of other non-standard and in many cases non-sensical join types.
138233 ** INNER CROSS JOIN -> same as JOIN
138234 ** NATURAL CROSS JOIN -> same as NATURAL JOIN
138235 ** OUTER LEFT JOIN -> same as LEFT JOIN
138236 ** LEFT NATURAL JOIN -> same as NATURAL LEFT JOIN
138237 ** LEFT RIGHT JOIN -> same as FULL JOIN
138238 ** RIGHT OUTER FULL JOIN -> same as FULL JOIN
138239 ** CROSS CROSS CROSS JOIN -> same as JOIN
138278 if( p->n==aKeyword[j].nChar
138279 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
138307 ** Return the index of a column in a table. Return -1 if the column
138314 for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){
138315 if( pCol->hName==h && sqlite3StrICmp(pCol->zCnName, zCol)==0 ) return i;
138317 return -1;
138325 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
138326 if( pItem->fg.isNestedFrom ){
138328 assert( pItem->pSelect!=0 );
138329 pResults = pItem->pSelect->pEList;
138331 assert( iCol>=0 && iCol<pResults->nExpr );
138332 pResults->a[iCol].fg.bUsed = 1;
138338 ** table that has a column named zCol. The search is left-to-right.
138348 int iStart, /* First member of pSrc->a[] to check */
138349 int iEnd, /* Last member of pSrc->a[] to check */
138351 int *piTab, /* Write index of pSrc->a[] here */
138352 int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
138358 assert( iEnd<pSrc->nSrc );
138363 iCol = sqlite3ColumnIndex(pSrc->a[i].pTab, zCol);
138365 && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)
138368 sqlite3SrcItemColumnUsed(&pSrc->a[i], iCol);
138410 p->w.iJoin = iTable;
138411 if( p->op==TK_FUNCTION ){
138413 if( p->x.pList ){
138415 for(i=0; i<p->x.pList->nExpr; i++){
138416 sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable, joinFlag);
138420 sqlite3SetJoinExpr(p->pLeft, iTable, joinFlag);
138421 p = p->pRight;
138441 if( iTable<0 || (ExprHasProperty(p, EP_OuterON) && p->w.iJoin==iTable) ){
138445 if( p->op==TK_COLUMN && p->iTable==iTable && !nullable ){
138448 if( p->op==TK_FUNCTION ){
138450 if( p->x.pList ){
138452 for(i=0; i<p->x.pList->nExpr; i++){
138453 unsetJoinExpr(p->x.pList->a[i].pExpr, iTable, nullable);
138457 unsetJoinExpr(p->pLeft, iTable, nullable);
138458 p = p->pRight;
138475 ** The left most table is the first entry in Select.pSrc. The right-most
138489 pSrc = p->pSrc;
138490 pLeft = &pSrc->a[0];
138492 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
138493 Table *pRightTab = pRight->pTab;
138496 if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
138497 joinType = (pRight->fg.jointype & JT_OUTER)!=0 ? EP_OuterON : EP_InnerON;
138502 if( pRight->fg.jointype & JT_NATURAL ){
138504 if( pRight->fg.isUsing || pRight->u3.pOn ){
138509 for(j=0; j<pRightTab->nCol; j++){
138512 if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
138513 zName = pRightTab->aCol[j].zCnName;
138517 assert( pUsing->nId>0 );
138518 assert( pUsing->a[pUsing->nId-1].zName==0 );
138519 pUsing->a[pUsing->nId-1].zName = sqlite3DbStrDup(pParse->db, zName);
138524 pRight->fg.isUsing = 1;
138525 pRight->fg.isSynthUsing = 1;
138526 pRight->u3.pUsing = pUsing;
138528 if( pParse->nErr ) return 1;
138538 if( pRight->fg.isUsing ){
138539 IdList *pList = pRight->u3.pUsing;
138540 sqlite3 *db = pParse->db;
138542 for(j=0; j<pList->nId; j++){
138551 zName = pList->a[j].zName;
138555 pRight->fg.isSynthUsing)==0
138557 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
138562 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
138563 if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
138566 ** contains the zName column, then this branch is a no-op.
138573 ** non-USING references to zName on the left of an INNER or LEFT
138580 pRight->fg.isSynthUsing)!=0 ){
138581 if( pSrc->a[iLeft].fg.isUsing==0
138582 || sqlite3IdListIndex(pSrc->a[iLeft].u3.pUsing, zName)<0
138590 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
138605 pEq->w.iJoin = pE2->iTable;
138607 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pEq);
138614 else if( pRight->u3.pOn ){
138615 sqlite3SetJoinExpr(pRight->u3.pOn, pRight->iCursor, joinType);
138616 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn);
138617 pRight->u3.pOn = 0;
138618 pRight->fg.isOn = 1;
138647 sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
138648 0, pInfo->ecelFlags);
138650 if( pInfo->pExtra ){
138651 sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
138652 sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
138670 int nOBSat = pSort->nOBSat;
138671 Vdbe *v = pParse->pVdbe;
138672 int regOut = ++pParse->nMem;
138673 if( pSort->pDeferredRowLoad ){
138674 innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
138676 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
138682 ** through regData+nData-1 onto the sorter.
138693 Vdbe *v = pParse->pVdbe; /* Stmt under construction */
138694 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
138695 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
138699 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
138723 regBase = regData - nPrefixReg;
138725 regBase = pParse->nMem + 1;
138726 pParse->nMem += nBase;
138728 assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
138729 iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
138730 pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
138731 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
138734 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
138748 regPrevKey = pParse->nMem+1;
138749 pParse->nMem += pSort->nOBSat;
138750 nKey = nExpr - pSort->nOBSat + bSeq;
138754 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
138757 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
138758 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
138759 if( pParse->db->mallocFailed ) return;
138760 pOp->p2 = nKey + nData;
138761 pKI = pOp->p4.pKeyInfo;
138762 memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
138763 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
138764 testcase( pKI->nAllField > pKI->nKeyField+2 );
138765 pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
138766 pKI->nAllField-pKI->nKeyField-1);
138770 pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
138771 pSort->regReturn = ++pParse->nMem;
138772 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
138773 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
138775 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
138779 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
138793 ** jump to the next iteration of the loop. If the pSort->labelOBLopt
138798 int iCsr = pSort->iECursor;
138803 iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
138810 if( pSort->sortFlags & SORTFLAG_UseSorter ){
138815 sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
138816 regBase+nOBSat, nBase-nOBSat);
138819 pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
138889 int nResultCol = pEList->nExpr;
138890 Vdbe *v = pParse->pVdbe;
138899 iRet = regPrev = pParse->nMem+1;
138900 pParse->nMem += nResultCol;
138904 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
138905 if( i<nResultCol-1 ){
138912 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
138915 assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
138916 sqlite3VdbeAddOp3(v, OP_Copy, regElem, regPrev, nResultCol-1);
138951 ** No adjustments necessary. This function is a no-op.
138970 if( pParse->nErr==0
138973 Vdbe *v = pParse->pVdbe;
138975 if( sqlite3VdbeGetOp(v, iOpenEphAddr+1)->opcode==OP_Explain ){
138984 pOp->opcode = OP_Null;
138985 pOp->p1 = 1;
138986 pOp->p2 = iVal;
138993 ** This function is called as part of inner-loop generation for a SELECT
138995 ** determines the expressions, if any, that the sorter-reference
138996 ** optimization should be used for. The sorter-reference optimization
139009 ** for which the sorter-reference optimization should be enabled.
139010 ** Additionally, the pSort->aDefer[] array is populated with entries
139025 for(i=0; i<pEList->nExpr; i++){
139026 struct ExprList_item *pItem = &pEList->a[i];
139027 if( pItem->u.x.iOrderByCol==0 ){
139028 Expr *pExpr = pItem->pExpr;
139030 if( pExpr->op==TK_COLUMN
139031 && pExpr->iColumn>=0
139033 && (pTab = pExpr->y.pTab)!=0
139035 && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)!=0
139039 if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
139042 if( nDefer==ArraySize(pSort->aDefer) ){
139050 nKey = pPk->nKeyCol;
139055 pNew->iTable = pExpr->iTable;
139057 pNew->y.pTab = pExpr->y.pTab;
139058 pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
139062 pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
139063 pSort->aDefer[nDefer].iCsr = pExpr->iTable;
139064 pSort->aDefer[nDefer].nKey = nKey;
139068 pItem->fg.bSorterRef = 1;
139072 pSort->nDefer = (u8)nDefer;
139081 ** If srcTab is negative, then the p->pEList expressions
139083 ** zero or more, then data is pulled from srcTab and p->pEList is used only
139089 int srcTab, /* Pull data from this table if non-negative */
139096 Vdbe *v = pParse->pVdbe;
139099 int eDest = pDest->eDest; /* How to dispose of results */
139100 int iParm = pDest->iSDParm; /* First argument to disposal method */
139108 ** values for any expressions that are also part of the sort-key are omitted
139114 assert( p->pEList!=0 );
139115 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
139116 if( pSort && pSort->pOrderBy==0 ) pSort = 0;
139119 if( hasDistinct && (pDistinct->eTnctType==WHERE_DISTINCT_UNIQUE) ){
139121 sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
139127 codeOffset(v, p->iOffset, iContinue);
139130 if( p->iLimit ){
139131 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak);
139142 nResultCol = p->pEList->nExpr;
139144 if( pDest->iSdst==0 ){
139146 nPrefixReg = pSort->pOrderBy->nExpr;
139147 if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
139148 pParse->nMem += nPrefixReg;
139150 pDest->iSdst = pParse->nMem+1;
139151 pParse->nMem += nResultCol;
139152 }else if( pDest->iSdst+nResultCol > pParse->nMem ){
139154 ** on the right-hand side of an INSERT contains more result columns than
139158 pParse->nMem += nResultCol;
139160 pDest->nSdst = nResultCol;
139161 regOrig = regResult = pDest->iSdst;
139165 VdbeComment((v, "%s", p->pEList->a[i].zEName));
139182 /* For each expression in p->pEList that is a copy of an expression in
139183 ** the ORDER BY clause (pSort->pOrderBy), set the associated
139185 ** expression within the sort-key that pushOntoSorter() will generate.
139186 ** This allows the p->pEList field to be omitted from the sorted record,
139190 for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
139192 if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
139193 p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
139197 selectExprDefer(pParse, pSort, p->pEList, &pExtra);
139198 if( pExtra && pParse->db->mallocFailed==0 ){
139204 VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
139205 pOp->p2 += (pExtra->nExpr - pSort->nDefer);
139206 pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
139207 pParse->nMem += pExtra->nExpr;
139213 pEList = p->pEList;
139214 for(i=0; i<pEList->nExpr; i++){
139215 if( pEList->a[i].u.x.iOrderByCol>0
139217 || pEList->a[i].fg.bSorterRef
139220 nResultCol--;
139239 if( pExtra ) nResultCol += pExtra->nExpr;
139241 if( p->iLimit
139247 pSort->pDeferredRowLoad = &sRowLoadInfo;
139259 int eType = pDistinct->eTnctType;
139260 int iTab = pDistinct->tabTnct;
139261 assert( nResultCol==p->pEList->nExpr );
139262 iTab = codeDistinct(pParse, eType, iTab, iContinue, p->pEList, regResult);
139263 fixDistinctOpenEph(pParse, eType, iTab, pDistinct->addrTnct);
139265 codeOffset(v, p->iOffset, iContinue);
139268 if( p->iLimit ){
139269 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak);
139315 if( pDest->zAffSdst ){
139316 sqlite3VdbeChangeP4(v, -1, pDest->zAffSdst, nResultCol);
139351 int i2 = pDest->iSDParm2;
139360 regResult+(i2<0), nResultCol-(i2<0), r1);
139385 assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
139387 r1, pDest->zAffSdst, nResultCol);
139409 assert( nResultCol<=pDest->nSdst );
139413 assert( nResultCol==pDest->nSdst );
139421 case SRT_Coroutine: /* Send data to a co-routine */
139429 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
139438 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
139439 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
139440 ** pSO->nExpr columns, then make sure all keys are unique by adding a
139449 pSO = pDest->pOrderBy;
139451 nKey = pSO->nExpr;
139470 regResult + pSO->a[i].u.x.iOrderByCol - 1,
139488 ** user-defined functions that have side effects. We do not care
139502 if( pSort==0 && p->iLimit ){
139503 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
139512 int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
139515 p->aSortFlags = (u8*)&p->aColl[N+X];
139516 p->nKeyField = (u16)N;
139517 p->nAllField = (u16)(N+X);
139518 p->enc = ENC(db);
139519 p->db = db;
139520 p->nRef = 1;
139533 assert( p->db!=0 );
139534 assert( p->nRef>0 );
139535 p->nRef--;
139536 if( p->nRef==0 ) sqlite3DbNNFreeNN(p->db, p);
139545 assert( p->nRef>0 );
139546 p->nRef++;
139558 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
139584 sqlite3 *db = pParse->db;
139587 nExpr = pList->nExpr;
139588 pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
139591 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
139592 pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
139593 pInfo->aSortFlags[i-iStart] = pItem->fg.sortFlags;
139616 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
139619 ** "USE TEMP B-TREE FOR xxx"
139625 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
139629 ** Assign expression b to lvalue a. A second, no-op, version of this macro
139638 /* No-op versions of the explainXXX() functions and macros. */
139645 ** If the inner loop was generated using a non-null pOrderBy argument,
139657 Vdbe *v = pParse->pVdbe; /* The prepared statement */
139658 int addrBreak = pSort->labelDone; /* Jump here to exit loop */
139663 ExprList *pOrderBy = pSort->pOrderBy;
139664 int eDest = pDest->eDest;
139665 int iParm = pDest->iSDParm;
139674 struct ExprList_item *aOutEx = p->pEList->a;
139677 if( pSort->labelBkOut ){
139678 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
139680 sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
139684 /* Open any cursors needed for sorter-reference expressions */
139685 for(i=0; i<pSort->nDefer; i++){
139686 Table *pTab = pSort->aDefer[i].pTab;
139687 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
139688 sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
139689 nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
139693 iTab = pSort->iECursor;
139695 if( eDest==SRT_Mem && p->iOffset ){
139696 sqlite3VdbeAddOp2(v, OP_Null, 0, pDest->iSdst);
139699 regRow = pDest->iSdst;
139709 nKey = pOrderBy->nExpr - pSort->nOBSat;
139710 if( pSort->sortFlags & SORTFLAG_UseSorter ){
139711 int regSortOut = ++pParse->nMem;
139712 iSortTab = pParse->nTab++;
139713 if( pSort->labelBkOut ){
139721 assert( p->iLimit==0 && p->iOffset==0 );
139732 codeOffset(v, p->iOffset, addrContinue);
139741 if( p->iOffset>0 ){
139742 sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
139745 for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
139752 if( pSort->nDefer ){
139756 for(i=0; i<pSort->nDefer; i++){
139757 int iCsr = pSort->aDefer[i].iCsr;
139758 Table *pTab = pSort->aDefer[i].pTab;
139759 int nKey = pSort->aDefer[i].nKey;
139769 assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
139782 for(i=nColumn-1; i>=0; i--){
139791 iRead = aOutEx[i].u.x.iOrderByCol-1;
139793 iRead = iCol--;
139810 assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
139812 pDest->zAffSdst, nColumn);
139822 int i2 = pDest->iSDParm2;
139824 sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1);
139837 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
139839 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
139855 if( pSort->sortFlags & SORTFLAG_UseSorter ){
139860 if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
139872 ** result-set expression in all of the following SELECT statements is
139883 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
139910 assert( pNC->pSrcList!=0 );
139911 switch( pExpr->op ){
139919 int iCol = pExpr->iColumn; /* Index of column in pTab */
139921 SrcList *pTabList = pNC->pSrcList;
139922 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
139923 if( j<pTabList->nSrc ){
139924 pTab = pTabList->a[j].pTab;
139925 pS = pTabList->a[j].pSelect;
139927 pNC = pNC->pNext;
139942 ** sub-select. In this case, set the column type to NULL, even
139952 assert( pTab && ExprUseYTab(pExpr) && pExpr->y.pTab==pTab );
139954 /* The "table" is actually a sub-select or a view in the FROM clause
139956 ** data for the result-set column of the sub-select.
139958 if( iCol<pS->pEList->nExpr
139966 ** rowid of the sub-select or view. This expression is legal (see
139967 ** test case misc2.2.2) - it always evaluates to NULL.
139970 Expr *p = pS->pEList->a[iCol].pExpr;
139971 sNC.pSrcList = pS->pSrc;
139973 sNC.pParse = pNC->pParse;
139980 if( iCol<0 ) iCol = pTab->iPKey;
139981 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
139986 zOrigCol = pTab->aCol[iCol].zCnName;
139987 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
139989 zOrigTab = pTab->zName;
139990 if( pNC->pParse && pTab->pSchema ){
139991 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
139992 zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
139995 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
139999 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
140007 /* The expression is a sub-select. Return the declaration type and
140015 pS = pExpr->x.pSelect;
140016 p = pS->pEList->a[0].pExpr;
140017 sNC.pSrcList = pS->pSrc;
140019 sNC.pParse = pNC->pParse;
140047 Vdbe *v = pParse->pVdbe;
140053 for(i=0; i<pEList->nExpr; i++){
140054 Expr *p = pEList->a[i].pExpr;
140062 /* The vdbe must make its own copy of the column-type and other
140112 Vdbe *v = pParse->pVdbe;
140117 sqlite3 *db = pParse->db;
140123 if( pParse->explain ){
140128 if( pParse->colNamesSet ) return;
140129 /* Column names are determined by the left-most term of a compound select */
140130 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
140132 pTabList = pSelect->pSrc;
140133 pEList = pSelect->pEList;
140136 pParse->colNamesSet = 1;
140137 fullName = (db->flags & SQLITE_FullColNames)!=0;
140138 srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
140139 sqlite3VdbeSetNumCols(v, pEList->nExpr);
140140 for(i=0; i<pEList->nExpr; i++){
140141 Expr *p = pEList->a[i].pExpr;
140144 assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
140145 assert( p->op!=TK_COLUMN
140146 || (ExprUseYTab(p) && p->y.pTab!=0) ); /* Covering idx not yet coded */
140147 if( pEList->a[i].zEName && pEList->a[i].fg.eEName==ENAME_NAME ){
140149 char *zName = pEList->a[i].zEName;
140151 }else if( srcName && p->op==TK_COLUMN ){
140153 int iCol = p->iColumn;
140154 pTab = p->y.pTab;
140156 if( iCol<0 ) iCol = pTab->iPKey;
140157 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
140161 zCol = pTab->aCol[iCol].zCnName;
140165 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
140171 const char *z = pEList->a[i].zEName;
140207 sqlite3 *db = pParse->db; /* Database connection */
140219 nCol = pEList->nExpr;
140231 for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
140232 struct ExprList_item *pX = &pEList->a[i];
140236 if( (zName = pX->zEName)!=0 && pX->fg.eEName==ENAME_NAME ){
140239 Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pX->pExpr);
140240 while( ALWAYS(pColExpr!=0) && pColExpr->op==TK_DOT ){
140241 pColExpr = pColExpr->pRight;
140244 if( pColExpr->op==TK_COLUMN
140246 && ALWAYS( pColExpr->y.pTab!=0 )
140249 int iCol = pColExpr->iColumn;
140250 pTab = pColExpr->y.pTab;
140251 if( iCol<0 ) iCol = pTab->iPKey;
140252 zName = iCol>=0 ? pTab->aCol[iCol].zCnName : "rowid";
140253 }else if( pColExpr->op==TK_ID ){
140255 zName = pColExpr->u.zToken;
140258 assert( zName==pX->zEName ); /* pointer comparison intended */
140272 if( pCollide->fg.bUsingTerm ){
140273 pCol->colFlags |= COLFLAG_NOEXPAND;
140277 for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
140283 pCol->zCnName = zName;
140284 pCol->hName = sqlite3StrIHash(zName);
140285 if( pX->fg.bNoExpand ){
140286 pCol->colFlags |= COLFLAG_NOEXPAND;
140294 if( db->mallocFailed ){
140323 sqlite3 *db = pParse->db;
140332 assert( (pSelect->selFlags & SF_Resolved)!=0 );
140333 assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
140334 if( db->mallocFailed ) return;
140336 sNC.pSrcList = pSelect->pSrc;
140337 a = pSelect->pEList->a;
140338 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
140341 pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
140344 /* pCol->szEst = ... // Column size est for SELECT tables never used */
140345 pCol->affinity = sqlite3ExprAffinity(p);
140348 n = sqlite3Strlen30(pCol->zCnName);
140349 pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+m+2);
140350 if( pCol->zCnName ){
140351 memcpy(&pCol->zCnName[n+1], zType, m+1);
140352 pCol->colFlags |= COLFLAG_HASTYPE;
140354 testcase( pCol->colFlags & COLFLAG_HASTYPE );
140355 pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
140358 if( pCol->affinity<=SQLITE_AFF_NONE ) pCol->affinity = aff;
140361 assert( pTab->pIndex==0 );
140362 sqlite3ColumnSetColl(db, pCol, pColl->zName);
140365 pTab->szTabRow = 1; /* Any non-zero value works */
140374 sqlite3 *db = pParse->db;
140377 savedFlags = db->flags;
140378 db->flags &= ~(u64)SQLITE_FullColNames;
140379 db->flags |= SQLITE_ShortColNames;
140381 db->flags = savedFlags;
140382 if( pParse->nErr ) return 0;
140383 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
140388 pTab->nTabRef = 1;
140389 pTab->zName = 0;
140390 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
140391 sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
140393 pTab->iPKey = -1;
140394 if( db->mallocFailed ){
140406 if( pParse->pVdbe ){
140407 return pParse->pVdbe;
140409 if( pParse->pToplevel==0
140410 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
140412 pParse->okConstFactor = 1;
140420 ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
140428 ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
140436 ** Only if pLimit->pLeft!=0 do the limit registers get
140446 Expr *pLimit = p->pLimit;
140448 if( p->iLimit ) return;
140451 ** "LIMIT -1" always shows all rows. There is some
140457 assert( pLimit->op==TK_LIMIT );
140458 assert( pLimit->pLeft!=0 );
140459 p->iLimit = iLimit = ++pParse->nMem;
140462 if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
140467 }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
140468 p->nSelectRow = sqlite3LogEst((u64)n);
140469 p->selFlags |= SF_FixedLimit;
140472 sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
140477 if( pLimit->pRight ){
140478 p->iOffset = iOffset = ++pParse->nMem;
140479 pParse->nMem++; /* Allocate an extra register for limit+offset */
140480 sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
140491 ** Return the appropriate collating sequence for the iCol-th column of
140492 ** the result set for the compound-select statement "p". Return NULL if
140496 ** left-most term of the select that has a collating sequence.
140500 if( p->pPrior ){
140501 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
140506 /* iCol must be less than p->pEList->nExpr. Otherwise an error would
140509 if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
140510 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
140525 ExprList *pOrderBy = p->pOrderBy;
140526 int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0;
140527 sqlite3 *db = pParse->db;
140532 struct ExprList_item *pItem = &pOrderBy->a[i];
140533 Expr *pTerm = pItem->pExpr;
140536 if( pTerm->flags & EP_Collate ){
140539 pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
140540 if( pColl==0 ) pColl = db->pDfltColl;
140541 pOrderBy->a[i].pExpr =
140542 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
140545 pRet->aColl[i] = pColl;
140546 pRet->aSortFlags[i] = pOrderBy->a[i].fg.sortFlags;
140558 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
140560 ** p->pPrior p
140563 ** There is exactly one reference to the recursive-table in the FROM clause
140564 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
140566 ** The setup-query runs once to generate an initial set of rows that go
140570 ** recursive-table for a recursive-query run. The output of the recursive-query
140595 SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
140596 int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
140597 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
140599 Select *pFirstRec; /* Left-most recursive term */
140615 if( p->pWin ){
140626 p->nSelectRow = 320; /* 4 billion rows */
140628 pLimit = p->pLimit;
140629 regLimit = p->iLimit;
140630 regOffset = p->iOffset;
140631 p->pLimit = 0;
140632 p->iLimit = p->iOffset = 0;
140633 pOrderBy = p->pOrderBy;
140636 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
140637 if( pSrc->a[i].fg.isRecursive ){
140638 iCurrent = pSrc->a[i].iCursor;
140646 iQueue = pParse->nTab++;
140647 if( p->op==TK_UNION ){
140649 iDistinct = pParse->nTab++;
140656 regCurrent = ++pParse->nMem;
140660 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
140668 p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
140669 p->selFlags |= SF_UsesEphemeral;
140673 p->pOrderBy = 0;
140679 ** iDistinct table. pFirstRec is left pointing to the left-most
140682 for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){
140683 if( pFirstRec->selFlags & SF_Aggregate ){
140687 pFirstRec->op = TK_ALL;
140688 if( (pFirstRec->pPrior->selFlags & SF_Recursive)==0 ) break;
140691 /* Store the results of the setup-query in Queue. */
140692 pSetup = pFirstRec->pPrior;
140693 pSetup->pNext = 0;
140696 pSetup->pNext = p;
140705 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
140723 ** the value for the recursive-table. Store the results in the Queue.
140725 pFirstRec->pPrior = 0;
140728 assert( pFirstRec->pPrior==0 );
140729 pFirstRec->pPrior = pSetup;
140736 sqlite3ExprListDelete(pParse->db, p->pOrderBy);
140737 p->pOrderBy = pOrderBy;
140738 p->pLimit = pLimit;
140746 Select *p, /* The right-most of SELECTs to be coded */
140751 ** Handle the special case of a compound-select that originates from a
140764 ** Since the limit is exactly 1, we only need to evaluate the left-most VALUES.
140768 Select *p, /* The right-most of SELECTs to be coded */
140773 int bShowAll = p->pLimit==0;
140774 assert( p->selFlags & SF_MultiValue );
140776 assert( p->selFlags & SF_Values );
140777 assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
140778 assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
140780 if( p->pWin ) return -1;
140782 if( p->pPrior==0 ) break;
140783 assert( p->pPrior->pNext==p );
140784 p = p->pPrior;
140790 selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
140792 p->nSelectRow = nRow;
140793 p = p->pNext;
140804 while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
140813 ** "p" points to the right-most of the two queries. the query on the
140814 ** left is p->pPrior. The left query could also be a compound query
140820 ** Example 1: Consider a three-way compound SQL statement.
140828 ** `-----> SELECT b FROM t2
140830 ** `------> SELECT a FROM t1
140834 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
140841 Select *p, /* The right-most of SELECTs to be coded */
140852 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
140854 assert( p && p->pPrior ); /* Calling function guarantees this much */
140855 assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
140856 assert( p->selFlags & SF_Compound );
140857 db = pParse->db;
140858 pPrior = p->pPrior;
140860 assert( pPrior->pOrderBy==0 );
140861 assert( pPrior->pLimit==0 );
140869 assert( p->pEList );
140870 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
140874 /* Special handling for a compound-select that originates as a VALUES clause.
140876 if( p->selFlags & SF_MultiValue ){
140885 assert( p->pEList && pPrior->pEList );
140886 assert( p->pEList->nExpr==pPrior->pEList->nExpr );
140889 if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){
140896 if( p->pOrderBy ){
140901 if( pPrior->pPrior==0 ){
140903 ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
140909 switch( p->op ){
140913 assert( !pPrior->pLimit );
140914 pPrior->iLimit = p->iLimit;
140915 pPrior->iOffset = p->iOffset;
140916 pPrior->pLimit = p->pLimit;
140919 pPrior->pLimit = 0;
140923 p->pPrior = 0;
140924 p->iLimit = pPrior->iLimit;
140925 p->iOffset = pPrior->iOffset;
140926 if( p->iLimit ){
140927 addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
140929 if( p->iOffset ){
140931 p->iLimit, p->iOffset+1, p->iOffset);
140938 pDelete = p->pPrior;
140939 p->pPrior = pPrior;
140940 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
140941 if( p->pLimit
140942 && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit)
140943 && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
140945 p->nSelectRow = sqlite3LogEst((u64)nLimit);
140957 Expr *pLimit; /* Saved values of p->nLimit */
140961 testcase( p->op==TK_EXCEPT );
140962 testcase( p->op==TK_UNION );
140968 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
140974 unionTab = pParse->nTab++;
140975 assert( p->pOrderBy==0 );
140977 assert( p->addrOpenEphm[0] == -1 );
140978 p->addrOpenEphm[0] = addr;
140979 findRightmost(p)->selFlags |= SF_UsesEphemeral;
140980 assert( p->pEList );
140986 assert( !pPrior->pOrderBy );
140996 if( p->op==TK_EXCEPT ){
140999 assert( p->op==TK_UNION );
141002 p->pPrior = 0;
141003 pLimit = p->pLimit;
141004 p->pLimit = 0;
141006 ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
141007 sqlite3SelectOpName(p->op)));
141011 assert( p->pOrderBy==0 );
141012 pDelete = p->pPrior;
141013 p->pPrior = pPrior;
141014 p->pOrderBy = 0;
141015 if( p->op==TK_UNION ){
141016 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
141018 sqlite3ExprDelete(db, p->pLimit);
141019 p->pLimit = pLimit;
141020 p->iLimit = 0;
141021 p->iOffset = 0;
141027 assert( p->pEList || db->mallocFailed );
141028 if( dest.eDest!=priorOp && db->mallocFailed==0 ){
141044 default: assert( p->op==TK_INTERSECT ); {
141056 tab1 = pParse->nTab++;
141057 tab2 = pParse->nTab++;
141058 assert( p->pOrderBy==0 );
141061 assert( p->addrOpenEphm[0] == -1 );
141062 p->addrOpenEphm[0] = addr;
141063 findRightmost(p)->selFlags |= SF_UsesEphemeral;
141064 assert( p->pEList );
141078 assert( p->addrOpenEphm[1] == -1 );
141079 p->addrOpenEphm[1] = addr;
141080 p->pPrior = 0;
141081 pLimit = p->pLimit;
141082 p->pLimit = 0;
141084 ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
141085 sqlite3SelectOpName(p->op)));
141089 pDelete = p->pPrior;
141090 p->pPrior = pPrior;
141091 if( p->nSelectRow>pPrior->nSelectRow ){
141092 p->nSelectRow = pPrior->nSelectRow;
141094 sqlite3ExprDelete(db, p->pLimit);
141095 p->pLimit = pLimit;
141101 assert( p->pEList );
141123 if( p->pNext==0 ){
141128 if( pParse->nErr ) goto multi_select_end;
141134 ** This section is run by the right-most SELECT statement only.
141135 ** SELECT statements to the left always skip this part. The right-most
141139 if( p->selFlags & SF_UsesEphemeral ){
141143 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
141146 assert( p->pNext==0 );
141147 assert( p->pEList!=0 );
141148 nCol = p->pEList->nExpr;
141154 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
141157 *apColl = db->pDfltColl;
141161 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
141163 int addr = pLoop->addrOpenEphm[i];
141167 assert( pLoop->addrOpenEphm[1]<0 );
141173 pLoop->addrOpenEphm[i] = -1;
141180 pDest->iSdst = dest.iSdst;
141181 pDest->nSdst = dest.nSdst;
141196 if( p->selFlags & SF_Values ){
141201 sqlite3SelectOpName(p->op));
141209 ** The data to be output is contained in pIn->iSdst. There are
141210 ** pIn->nSdst columns to be output. pDest is where the output should
141222 ** If the LIMIT found in p->iLimit is reached, jump immediately to
141235 Vdbe *v = pParse->pVdbe;
141247 addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
141251 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
141254 if( pParse->db->mallocFailed ) return 0;
141258 codeOffset(v, p->iOffset, iContinue);
141260 assert( pDest->eDest!=SRT_Exists );
141261 assert( pDest->eDest!=SRT_Table );
141262 switch( pDest->eDest ){
141268 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
141269 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
141270 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
141282 testcase( pIn->nSdst>1 );
141284 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
141285 r1, pDest->zAffSdst, pIn->nSdst);
141286 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
141287 pIn->iSdst, pIn->nSdst);
141295 ** if it is the RHS of a row-value IN operator.
141298 testcase( pIn->nSdst>1 );
141299 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
141306 ** starting at pDest->iSdst. Then the co-routine yields.
141309 if( pDest->iSdst==0 ){
141310 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
141311 pDest->nSdst = pIn->nSdst;
141313 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
141314 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
141327 assert( pDest->eDest==SRT_Output );
141328 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
141335 if( p->iLimit ){
141336 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
141357 ** co-routines. Then run the co-routines in parallel and merge the results
141384 ** ------------- ----------------- -------------- -----------------
141435 Select *p, /* The right-most of SELECTs to be coded */
141440 Select *pSplit; /* Left-most SELECT in the right-hand group */
141445 int regAddrA; /* Address register for select-A coroutine */
141446 int regAddrB; /* Address register for select-B coroutine */
141447 int addrSelectA; /* Address of the select-A coroutine */
141448 int addrSelectB; /* Address of the select-B coroutine */
141449 int regOutA; /* Address register for the output-A subroutine */
141450 int regOutB; /* Address register for the output-B subroutine */
141451 int addrOutA; /* Address of the output-A subroutine */
141452 int addrOutB = 0; /* Address of the output-B subroutine */
141453 int addrEofA; /* Address of the select-A-exhausted subroutine */
141455 int addrEofB; /* Address of the select-B-exhausted subroutine */
141459 int regLimitA; /* Limit register for select-A */
141460 int regLimitB; /* Limit register for select-A */
141462 int savedLimit; /* Saved value of p->iLimit */
141463 int savedOffset; /* Saved value of p->iOffset */
141475 assert( p->pOrderBy!=0 );
141477 db = pParse->db;
141478 v = pParse->pVdbe;
141486 op = p->op;
141487 assert( p->pPrior->pOrderBy==0 );
141488 pOrderBy = p->pOrderBy;
141490 nOrderBy = pOrderBy->nExpr;
141497 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
141499 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
141501 assert( pItem->u.x.iOrderByCol>0 );
141502 if( pItem->u.x.iOrderByCol==i ) break;
141507 pNew->flags |= EP_IntValue;
141508 pNew->u.iValue = i;
141509 p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
141510 if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
141526 for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
141528 assert( pItem->u.x.iOrderByCol>0 );
141529 assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
141530 aPermute[i] = pItem->u.x.iOrderByCol - 1;
141544 int nExpr = p->pEList->nExpr;
141545 assert( nOrderBy>=nExpr || db->mallocFailed );
141546 regPrev = pParse->nMem+1;
141547 pParse->nMem += nExpr+1;
141553 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
141554 pKeyDup->aSortFlags[i] = 0;
141565 for(pSplit=p; pSplit->pPrior!=0 && pSplit->op==op; pSplit=pSplit->pPrior){
141567 assert( pSplit->pPrior->pNext==pSplit );
141574 for(i=2; i<nSelect; i+=2){ pSplit = pSplit->pPrior; }
141576 pPrior = pSplit->pPrior;
141578 pSplit->pPrior = 0;
141579 pPrior->pNext = 0;
141580 assert( p->pOrderBy == pOrderBy );
141581 assert( pOrderBy!=0 || db->mallocFailed );
141582 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
141583 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
141584 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
141588 if( p->iLimit && op==TK_ALL ){
141589 regLimitA = ++pParse->nMem;
141590 regLimitB = ++pParse->nMem;
141591 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
141597 sqlite3ExprDelete(db, p->pLimit);
141598 p->pLimit = 0;
141600 regAddrA = ++pParse->nMem;
141601 regAddrB = ++pParse->nMem;
141602 regOutA = ++pParse->nMem;
141603 regOutB = ++pParse->nMem;
141607 ExplainQueryPlan((pParse, 1, "MERGE (%s)", sqlite3SelectOpName(p->op)));
141610 ** left of the compound operator - the "A" select.
141615 pPrior->iLimit = regLimitA;
141622 ** the right - the "B" select
141627 savedLimit = p->iLimit;
141628 savedOffset = p->iOffset;
141629 p->iLimit = regLimitB;
141630 p->iOffset = 0;
141633 p->iLimit = savedLimit;
141634 p->iOffset = savedOffset;
141662 VdbeNoopComment((v, "eof-A subroutine"));
141667 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
141675 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
141677 VdbeNoopComment((v, "eof-B subroutine"));
141685 VdbeNoopComment((v, "A-lt-B subroutine"));
141698 VdbeNoopComment((v, "A-eq-B subroutine"));
141706 VdbeNoopComment((v, "A-gt-B subroutine"));
141735 if( pSplit->pPrior ){
141737 (void(*)(sqlite3*,void*))sqlite3SelectDelete, pSplit->pPrior);
141739 pSplit->pPrior = pPrior;
141740 pPrior->pNext = pSplit;
141741 sqlite3ExprListDelete(db, pPrior->pOrderBy);
141742 pPrior->pOrderBy = 0;
141747 return pParse->nErr!=0;
141762 ** position in the parent that NULL-able due to an OUTER JOIN. Either the
141785 ** when processing a non-matched row of the left.
141802 ** a column in table number iTable with a copy of the iColumn-th
141810 ** changes to pExpr so that it refers directly to the source table
141819 && pExpr->w.iJoin==pSubst->iTable
141822 pExpr->w.iJoin = pSubst->iNewTable;
141824 if( pExpr->op==TK_COLUMN
141825 && pExpr->iTable==pSubst->iTable
141829 if( pExpr->iColumn<0 ){
141830 pExpr->op = TK_NULL;
141835 int iColumn = pExpr->iColumn;
141836 Expr *pCopy = pSubst->pEList->a[iColumn].pExpr;
141838 assert( pSubst->pEList!=0 && iColumn<pSubst->pEList->nExpr );
141839 assert( pExpr->pRight==0 );
141841 sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
141843 sqlite3 *db = pSubst->pParse->db;
141844 if( pSubst->isOuterJoin && pCopy->op!=TK_COLUMN ){
141848 ifNullRow.iTable = pSubst->iNewTable;
141849 ifNullRow.iColumn = -99;
141855 if( db->mallocFailed ){
141859 if( pSubst->isOuterJoin ){
141863 sqlite3SetJoinExpr(pNew, pExpr->w.iJoin,
141864 pExpr->flags & (EP_OuterON|EP_InnerON));
141868 if( pExpr->op==TK_TRUEFALSE ){
141869 pExpr->u.iValue = sqlite3ExprTruthValue(pExpr);
141870 pExpr->op = TK_INTEGER;
141875 ** just as it did when it was a column of a view or sub-query. */
141877 CollSeq *pNat = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
141878 CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse,
141879 pSubst->pCList->a[iColumn].pExpr
141881 if( pNat!=pColl || (pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE) ){
141882 pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
141883 (pColl ? pColl->zName : "BINARY")
141891 if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
141892 pExpr->iTable = pSubst->iNewTable;
141894 pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
141895 pExpr->pRight = substExpr(pSubst, pExpr->pRight);
141897 substSelect(pSubst, pExpr->x.pSelect, 1);
141899 substExprList(pSubst, pExpr->x.pList);
141903 Window *pWin = pExpr->y.pWin;
141904 pWin->pFilter = substExpr(pSubst, pWin->pFilter);
141905 substExprList(pSubst, pWin->pPartition);
141906 substExprList(pSubst, pWin->pOrderBy);
141918 for(i=0; i<pList->nExpr; i++){
141919 pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
141925 int doPrior /* Do substitutes on p->pPrior too */
141932 substExprList(pSubst, p->pEList);
141933 substExprList(pSubst, p->pGroupBy);
141934 substExprList(pSubst, p->pOrderBy);
141935 p->pHaving = substExpr(pSubst, p->pHaving);
141936 p->pWhere = substExpr(pSubst, p->pWhere);
141937 pSrc = p->pSrc;
141939 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
141940 substSelect(pSubst, pItem->pSelect, 1);
141941 if( pItem->fg.isTabFunc ){
141942 substExprList(pSubst, pItem->u1.pFuncArg);
141945 }while( doPrior && (p = p->pPrior)!=0 );
141955 ** pSrcItem->colUsed mask.
141959 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
141960 pItem = pWalker->u.pSrcItem;
141961 if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
141962 if( pExpr->iColumn<0 ) return WRC_Continue;
141963 pItem->colUsed |= sqlite3ExprColUsed(pExpr);
141971 if( NEVER(pSrcItem->pTab==0) ) return;
141976 pSrcItem->colUsed = 0;
141992 ** If pSrc contains any sub-selects, call this routine recursively
141993 ** on the FROM clause of each such sub-select, with iExcept set to -1.
142003 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
142006 assert( pItem->iCursor < aCsrMap[0] );
142007 if( !pItem->fg.isRecursive || aCsrMap[pItem->iCursor+1]==0 ){
142008 aCsrMap[pItem->iCursor+1] = pParse->nTab++;
142010 pItem->iCursor = aCsrMap[pItem->iCursor+1];
142011 for(p=pItem->pSelect; p; p=p->pPrior){
142012 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1);
142022 int *aCsrMap = pWalker->u.aiCol;
142034 int op = pExpr->op;
142036 renumberCursorDoMapping(pWalker, &pExpr->iTable);
142039 renumberCursorDoMapping(pWalker, &pExpr->w.iJoin);
142047 ** cursor in the FROM clause of any FROM clause sub-selects, recursively.
142069 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, iExcept);
142084 while( pSel->pPrior ){
142085 pSel = pSel->pPrior;
142087 return pSel->pEList;
142126 ** other than the one FROM-clause subquery that is a candidate
142128 ** from 2015-02-09.)
142142 ** sub-queries that were excluded from this optimization. Restriction
142157 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
142158 ** accidently carried the comment forward until 2014-09-15. Original
142195 ** The parent and sub-query may contain WHERE clauses. Subject to
142202 ** Also, each component of the sub-query must return the same number
142205 ** such (illegal) sub-query is flattened. The caller will detect the
142208 ** (18) If the sub-query is a compound select, then all terms of the
142215 ** (20) If the sub-query is a compound select, then it must not use
142226 ** (23) If the outer query is a recursive CTE, then the sub-query may not be
142232 ** The subquery may not be an aggregate that uses the built-in min() or
142254 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
142257 ** If flattening is not attempted, this routine is a no-op and returns 0.
142266 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
142269 const char *zSavedAuthContext = pParse->zAuthContext;
142272 Select *pSub1; /* Pointer to the rightmost select in sub-query */
142276 int iNewParent = -1;/* Replacement table for iParent */
142281 sqlite3 *db = pParse->db;
142288 assert( p->pPrior==0 );
142290 pSrc = p->pSrc;
142291 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
142292 pSubitem = &pSrc->a[iFrom];
142293 iParent = pSubitem->iCursor;
142294 pSub = pSubitem->pSelect;
142298 if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
142301 pSubSrc = pSub->pSrc;
142305 ** because they could be computed at compile-time. But when LIMIT and OFFSET
142308 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
142309 if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
142310 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
142313 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
142314 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
142315 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
142318 if( p->pOrderBy && pSub->pOrderBy ){
142321 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
142322 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
142323 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
142326 if( pSub->selFlags & (SF_Recursive) ){
142345 if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){
142346 if( pSubSrc->nSrc>1 /* (3a) */
142347 || IsVirtual(pSubSrc->a[0].pTab) /* (3b) */
142348 || (p->selFlags & SF_Distinct)!=0 /* (3d) */
142349 || (pSubitem->fg.jointype & JT_RIGHT)!=0 /* (26) */
142356 assert( pSubSrc->nSrc>0 ); /* True by restriction (7) */
142357 if( iFrom>0 && (pSubSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
142360 if( pSubitem->fg.isCte && pSubitem->u2.pCteUse->eM10d==M10d_Yes ){
142364 /* Restriction (17): If the sub-query is a compound SELECT, then it must
142369 if( pSub->pPrior ){
142371 if( pSub->pOrderBy ){
142374 if( isAgg || (p->selFlags & SF_Distinct)!=0 || isOuterJoin>0 ){
142377 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
142378 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
142379 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
142380 assert( pSub->pSrc!=0 );
142381 assert( (pSub->selFlags & SF_Recursive)==0 );
142382 assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
142383 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
142384 || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
142385 || pSub1->pSrc->nSrc<1 /* (17c) */
142387 || pSub1->pWin /* (17e) */
142392 if( iFrom>0 && (pSub1->pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
142394 ** omitted on left-hand tables of the right join that is being
142398 testcase( pSub1->pSrc->nSrc>1 );
142402 if( p->pOrderBy ){
142403 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
142404 if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
142409 if( (p->selFlags & SF_Recursive) ) return 0;
142412 for(ii=0; ii<pSub->pEList->nExpr; ii++){
142414 assert( pSub->pEList->a[ii].pExpr!=0 );
142415 aff = sqlite3ExprAffinity(pSub->pEList->a[ii].pExpr);
142416 for(pSub1=pSub->pPrior; pSub1; pSub1=pSub1->pPrior){
142417 assert( pSub1->pEList!=0 );
142418 assert( pSub1->pEList->nExpr>ii );
142419 assert( pSub1->pEList->a[ii].pExpr!=0 );
142420 if( sqlite3ExprAffinity(pSub1->pEList->a[ii].pExpr)!=aff ){
142426 if( pSrc->nSrc>1 ){
142427 if( pParse->nSelect>500 ) return 0;
142429 aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
142430 if( aCsrMap ) aCsrMap[0] = pParse->nTab;
142436 pSub->selId, pSub, iFrom));
142439 pParse->zAuthContext = pSubitem->zName;
142442 pParse->zAuthContext = zSavedAuthContext;
142445 pSub1 = pSubitem->pSelect;
142446 sqlite3DbFree(db, pSubitem->zDatabase);
142447 sqlite3DbFree(db, pSubitem->zName);
142448 sqlite3DbFree(db, pSubitem->zAlias);
142449 pSubitem->zDatabase = 0;
142450 pSubitem->zName = 0;
142451 pSubitem->zAlias = 0;
142452 pSubitem->pSelect = 0;
142453 assert( pSubitem->fg.isUsing!=0 || pSubitem->u3.pOn==0 );
142455 /* If the sub-query is a compound SELECT statement, then (by restrictions
142459 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
142462 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
142463 ** OFFSET clauses and joins them to the left-hand-side of the original
142465 ** select statements in the compound sub-query.
142486 ** We call this the "compound-subquery flattening".
142488 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
142490 ExprList *pOrderBy = p->pOrderBy;
142491 Expr *pLimit = p->pLimit;
142492 Select *pPrior = p->pPrior;
142493 Table *pItemTab = pSubitem->pTab;
142494 pSubitem->pTab = 0;
142495 p->pOrderBy = 0;
142496 p->pPrior = 0;
142497 p->pLimit = 0;
142499 p->pLimit = pLimit;
142500 p->pOrderBy = pOrderBy;
142501 p->op = TK_ALL;
142502 pSubitem->pTab = pItemTab;
142504 p->pPrior = pPrior;
142506 pNew->selId = ++pParse->nSelect;
142507 if( aCsrMap && ALWAYS(db->mallocFailed==0) ){
142510 pNew->pPrior = pPrior;
142511 if( pPrior ) pPrior->pNext = pNew;
142512 pNew->pNext = p;
142513 p->pPrior = pNew;
142514 SELECTTRACE(2,pParse,p,("compound-subquery flattener"
142515 " creates %u as peer\n",pNew->selId));
142517 assert( pSubitem->pSelect==0 );
142520 if( db->mallocFailed ){
142521 pSubitem->pSelect = pSub1;
142530 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
142532 if( ALWAYS(pSubitem->pTab!=0) ){
142533 Table *pTabToDel = pSubitem->pTab;
142534 if( pTabToDel->nTabRef==1 ){
142539 testcase( pToplevel->earlyCleanup );
142541 pTabToDel->nTabRef--;
142543 pSubitem->pTab = 0;
142546 /* The following loop runs once for each term in a compound-subquery
142548 ** of flattening - a flattening other than a compound-subquery flattening -
142560 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
142563 u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ;
142565 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
142566 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
142567 pSrc = pParent->pSrc; /* FROM clause of the outer query */
142570 jointype = pSubitem->fg.jointype; /* First time through the loop */
142589 pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
142591 pParent->pSrc = pSrc;
142598 SrcItem *pItem = &pSrc->a[i+iFrom];
142599 if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing);
142600 assert( pItem->fg.isTabFunc==0 );
142601 *pItem = pSubSrc->a[i];
142602 pItem->fg.jointype |= ltorj;
142603 iNewParent = pSubSrc->a[i].iCursor;
142604 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
142606 pSrc->a[iFrom].fg.jointype &= JT_LTORJ;
142607 pSrc->a[iFrom].fg.jointype |= jointype | ltorj;
142621 if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){
142622 /* At this point, any non-zero iOrderByCol values indicate that the
142629 ** function attempts to flatten a compound sub-query into pParent
142630 ** (the only way this can happen is if the compound sub-query is
142631 ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
142632 ExprList *pOrderBy = pSub->pOrderBy;
142633 for(i=0; i<pOrderBy->nExpr; i++){
142634 pOrderBy->a[i].u.x.iOrderByCol = 0;
142636 assert( pParent->pOrderBy==0 );
142637 pParent->pOrderBy = pOrderBy;
142638 pSub->pOrderBy = 0;
142640 pWhere = pSub->pWhere;
142641 pSub->pWhere = 0;
142646 if( pParent->pWhere ){
142647 pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
142649 pParent->pWhere = pWhere;
142652 if( db->mallocFailed==0 ){
142658 x.pEList = pSub->pEList;
142665 pParent->selFlags |= pSub->selFlags & SF_Compound;
142666 assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
142674 if( pSub->pLimit ){
142675 pParent->pLimit = pSub->pLimit;
142676 pSub->pLimit = 0;
142682 recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
142711 u8 *pOomFault; /* Pointer to pParse->db->mallocFailed */
142735 assert( pColumn->op==TK_COLUMN );
142740 if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
142744 /* 2018-10-25 ticket [cf5ed20f]
142746 for(i=0; i<pConst->nConst; i++){
142747 const Expr *pE2 = pConst->apExpr[i*2];
142748 assert( pE2->op==TK_COLUMN );
142749 if( pE2->iTable==pColumn->iTable
142750 && pE2->iColumn==pColumn->iColumn
142756 pConst->bHasAffBlob = 1;
142759 pConst->nConst++;
142760 pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
142761 pConst->nConst*2*sizeof(Expr*));
142762 if( pConst->apExpr==0 ){
142763 pConst->nConst = 0;
142765 pConst->apExpr[pConst->nConst*2-2] = pColumn;
142766 pConst->apExpr[pConst->nConst*2-1] = pValue;
142773 ** is part of the AND-connected terms of the expression. For each term
142779 if( ExprHasProperty(pExpr, pConst->mExcludeOn) ){
142784 if( pExpr->op==TK_AND ){
142785 findConstInWhere(pConst, pExpr->pRight);
142786 findConstInWhere(pConst, pExpr->pLeft);
142789 if( pExpr->op!=TK_EQ ) return;
142790 pRight = pExpr->pRight;
142791 pLeft = pExpr->pLeft;
142794 if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){
142797 if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){
142806 ** pExpr is equivalent to one of the columns named in pWalker->u.pConst,
142808 ** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr
142817 if( pConst->pOomFault[0] ) return WRC_Prune;
142818 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
142819 if( ExprHasProperty(pExpr, EP_FixedCol|pConst->mExcludeOn) ){
142825 for(i=0; i<pConst->nConst; i++){
142826 Expr *pColumn = pConst->apExpr[i*2];
142828 if( pColumn->iTable!=pExpr->iTable ) continue;
142829 if( pColumn->iColumn!=pExpr->iColumn ) continue;
142834 pConst->nChng++;
142837 assert( pExpr->pLeft==0 );
142838 pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
142839 if( pConst->pParse->db->mallocFailed ) return WRC_Prune;
142848 ** any substitutions based on the contents of pWalker->u.pConst should
142854 ** one of the columns in pWalker->u.pConst, or
142859 ** pWalker->u.pConst.
142862 WhereConst *pConst = pWalker->u.pConst;
142867 if( pConst->bHasAffBlob ){
142868 if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
142869 || pExpr->op==TK_IS
142871 propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
142872 if( pConst->pOomFault[0] ) return WRC_Prune;
142873 if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
142874 propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
142878 return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob);
142882 ** The WHERE-clause constant propagation optimization.
142885 ** CONSTANT=COLUMN that are top-level AND-connected terms that are not
142917 ** 2021-05-25 forum post 6a06202608: Another troublesome case is...
142940 x.pOomFault = &pParse->db->mallocFailed;
142946 if( ALWAYS(p->pSrc!=0)
142947 && p->pSrc->nSrc>0
142948 && (p->pSrc->a[0].fg.jointype & JT_LTORJ)!=0
142957 findConstInWhere(&x, p->pWhere);
142966 sqlite3WalkExpr(&w, p->pWhere);
142967 sqlite3DbFree(x.pParse->db, x.apExpr);
142978 ** push WHERE clause expression pExpr down to FROM clause sub-query
142985 ** BY clause of all window function used by the sub-query. It is safe
142991 ** * the sub-query uses only one distinct window frame, and
142995 assert( pSubq->pWin->pPartition );
142996 assert( (pSubq->selFlags & SF_MultiPart)==0 );
142997 assert( pSubq->pPrior==0 );
142998 return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition);
143008 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
143012 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
143020 ** (1) (** This restriction was removed on 2017-09-29. We used to
143038 ** of a LEFT JOIN where iCursor is not the right-hand table of that
143057 ** (6b) The inner query is a compound and uses window-functions.
143061 ** all window-functions used by the sub-query. It is safe to
143063 ** window over which any window-function is calculated.
143076 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
143088 if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ) return 0;
143089 if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ) return 0;
143092 if( pSubq->pPrior ){
143094 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
143095 u8 op = pSel->op;
143099 if( pSel->pWin ) return 0; /* restriction (6b) */
143102 if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0;
143113 for(pX=pSubq; pX; pX=pX->pPrior){
143114 assert( (pX->selFlags & (SF_Recursive))==0 );
143119 if( pSubq->pLimit!=0 ){
143122 while( pWhere->op==TK_AND ){
143123 nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrc);
143124 pWhere = pWhere->pLeft;
143130 || pWhere->w.iJoin!=iCursor)
143135 && pWhere->w.iJoin!=iCursor
143143 pSubq->selFlags |= SF_PushDown;
143146 pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
143147 unsetJoinExpr(pNew, -1, 1);
143149 x.iTable = pSrc->iCursor;
143150 x.iNewTable = pSrc->iCursor;
143152 x.pEList = pSubq->pEList;
143156 if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){
143157 /* Restriction 6c has prevented push-down in this case */
143158 sqlite3ExprDelete(pParse->db, pNew);
143159 nChng--;
143163 if( pSubq->selFlags & SF_Aggregate ){
143164 pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
143166 pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
143168 pSubq = pSubq->pPrior;
143199 assert( pFunc->op==TK_AGG_FUNCTION );
143202 pEList = pFunc->x.pList;
143204 || pEList->nExpr!=1
143211 zFunc = pFunc->u.zToken;
143214 if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
143224 assert( pOrderBy!=0 || db->mallocFailed );
143225 if( pOrderBy ) pOrderBy->a[0].fg.sortFlags = sortFlags;
143231 ** The second argument is the associated aggregate-info object. This
143236 ** where table is a database table, not a sub-select or view. If the query
143250 assert( !p->pGroupBy );
143252 if( p->pWhere
143253 || p->pEList->nExpr!=1
143254 || p->pSrc->nSrc!=1
143255 || p->pSrc->a[0].pSelect
143256 || pAggInfo->nFunc!=1
143257 || p->pHaving
143261 pTab = p->pSrc->a[0].pTab;
143265 pExpr = p->pEList->a[0].pExpr;
143267 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
143268 if( pExpr->pAggInfo!=pAggInfo ) return 0;
143269 if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
143270 assert( pAggInfo->aFunc[0].pFExpr==pExpr );
143279 ** If the source-list item passed as an argument was augmented with an
143283 ** pFrom->pIndex and return SQLITE_OK.
143286 Table *pTab = pFrom->pTab;
143287 char *zIndexedBy = pFrom->u1.zIndexedBy;
143290 assert( pFrom->fg.isIndexedBy!=0 );
143292 for(pIdx=pTab->pIndex;
143293 pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
143294 pIdx=pIdx->pNext
143298 pParse->checkSchema = 1;
143301 assert( pFrom->fg.isCte==0 );
143302 pFrom->u2.pIBIndex = pIdx;
143337 if( p->pPrior==0 ) return WRC_Continue;
143338 if( p->pOrderBy==0 ) return WRC_Continue;
143339 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
143341 a = p->pOrderBy->a;
143343 /* If iOrderByCol is already non-zero, then it has already been matched
143345 ** SELECT is rewritten for window-functions processing and then passed
143350 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
143351 if( a[i].pExpr->flags & EP_Collate ) break;
143357 pParse = pWalker->pParse;
143358 db = pParse->db;
143365 p->pSrc = pNewSrc;
143366 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
143367 p->op = TK_SELECT;
143368 p->pWhere = 0;
143369 pNew->pGroupBy = 0;
143370 pNew->pHaving = 0;
143371 pNew->pOrderBy = 0;
143372 p->pPrior = 0;
143373 p->pNext = 0;
143374 p->pWith = 0;
143376 p->pWinDefn = 0;
143378 p->selFlags &= ~SF_Compound;
143379 assert( (p->selFlags & SF_Converted)==0 );
143380 p->selFlags |= SF_Converted;
143381 assert( pNew->pPrior!=0 );
143382 pNew->pPrior->pNext = pNew;
143383 pNew->pLimit = 0;
143388 ** Check to see if the FROM clause term pFrom has table-valued function
143390 ** non-zero, since pFrom is not allowed to be a table-valued function.
143393 if( pFrom->fg.isTabFunc ){
143394 sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
143404 ** FROM clause element pItem is really a common-table-expression (CTE)
143408 ** If a non-NULL value is returned, set *ppContext to point to the With
143416 const char *zName = pItem->zName;
143418 assert( pItem->zDatabase==0 );
143420 for(p=pWith; p; p=p->pOuter){
143422 for(i=0; i<p->nCte; i++){
143423 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
143425 return &p->a[i];
143428 if( p->bView ) break;
143434 ** with the inner-most WITH clause being at the top of the stack.
143458 if( pParse->nErr==0 ){
143459 assert( pParse->pWith!=pWith );
143460 pWith->pOuter = pParse->pWith;
143461 pParse->pWith = pWith;
143470 ** pParse->pWith linked list). And if currently processing a CTE
143474 ** If pFrom matches a CTE according to either of these two above, pFrom->pTab
143489 assert( pFrom->pTab==0 );
143490 if( pParse->pWith==0 ){
143494 if( pParse->nErr ){
143495 /* Prior errors might have left pParse->pWith in a goofy state, so
143499 if( pFrom->zDatabase!=0 ){
143504 if( pFrom->fg.notCte ){
143512 pCte = searchWith(pParse->pWith, pFrom, &pWith);
143514 sqlite3 *db = pParse->db;
143518 Select *pLeft; /* Left-most SELECT statement */
143519 Select *pRecTerm; /* Left-most recursive term */
143521 With *pSavedWith; /* Initial value of pParse->pWith */
143522 int iRecTab = -1; /* Cursor for recursive table */
143525 /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
143527 ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
143529 if( pCte->zCteErr ){
143530 sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
143535 assert( pFrom->pTab==0 );
143538 pCteUse = pCte->pUse;
143540 pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0]));
143547 pCteUse->eM10d = pCte->eM10d;
143549 pFrom->pTab = pTab;
143550 pTab->nTabRef = 1;
143551 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
143552 pTab->iPKey = -1;
143553 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
143554 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
143555 pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
143556 if( db->mallocFailed ) return 2;
143557 pFrom->pSelect->selFlags |= SF_CopyCte;
143558 assert( pFrom->pSelect );
143559 if( pFrom->fg.isIndexedBy ){
143560 sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy);
143563 pFrom->fg.isCte = 1;
143564 pFrom->u2.pCteUse = pCteUse;
143565 pCteUse->nUse++;
143566 if( pCteUse->nUse>=2 && pCteUse->eM10d==M10d_Any ){
143567 pCteUse->eM10d = M10d_Yes;
143571 pRecTerm = pSel = pFrom->pSelect;
143572 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
143573 while( bMayRecursive && pRecTerm->op==pSel->op ){
143575 SrcList *pSrc = pRecTerm->pSrc;
143576 assert( pRecTerm->pPrior!=0 );
143577 for(i=0; i<pSrc->nSrc; i++){
143578 SrcItem *pItem = &pSrc->a[i];
143579 if( pItem->zDatabase==0
143580 && pItem->zName!=0
143581 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
143583 pItem->pTab = pTab;
143584 pTab->nTabRef++;
143585 pItem->fg.isRecursive = 1;
143586 if( pRecTerm->selFlags & SF_Recursive ){
143588 "multiple references to recursive table: %s", pCte->zName
143592 pRecTerm->selFlags |= SF_Recursive;
143593 if( iRecTab<0 ) iRecTab = pParse->nTab++;
143594 pItem->iCursor = iRecTab;
143597 if( (pRecTerm->selFlags & SF_Recursive)==0 ) break;
143598 pRecTerm = pRecTerm->pPrior;
143601 pCte->zCteErr = "circular reference: %s";
143602 pSavedWith = pParse->pWith;
143603 pParse->pWith = pWith;
143604 if( pSel->selFlags & SF_Recursive ){
143607 assert( (pRecTerm->selFlags & SF_Recursive)==0 );
143608 assert( pRecTerm->pNext!=0 );
143609 assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
143610 assert( pRecTerm->pWith==0 );
143611 pRecTerm->pWith = pSel->pWith;
143613 pRecTerm->pWith = 0;
143615 pParse->pWith = pSavedWith;
143620 pParse->pWith = pSavedWith;
143624 pParse->pWith = pWith;
143626 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
143627 pEList = pLeft->pEList;
143628 if( pCte->pCols ){
143629 if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
143631 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
143633 pParse->pWith = pSavedWith;
143636 pEList = pCte->pCols;
143639 sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
143641 if( pSel->selFlags & SF_Recursive ){
143642 pCte->zCteErr = "multiple recursive references: %s";
143644 pCte->zCteErr = "recursive reference in a subquery: %s";
143648 pCte->zCteErr = 0;
143649 pParse->pWith = pSavedWith;
143666 Parse *pParse = pWalker->pParse;
143667 if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
143668 With *pWith = findRightmost(p)->pWith;
143670 assert( pParse->pWith==pWith || pParse->nErr );
143671 pParse->pWith = pWith->pOuter;
143679 ** sub-query in the FROM clause of a SELECT statement. This function
143685 Select *pSel = pFrom->pSelect;
143689 pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
143691 pTab->nTabRef = 1;
143692 if( pFrom->zAlias ){
143693 pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
143695 pTab->zName = sqlite3MPrintf(pParse->db, "%!S", pFrom);
143697 while( pSel->pPrior ){ pSel = pSel->pPrior; }
143698 sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
143699 pTab->iPKey = -1;
143700 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
143702 /* The usual case - do not allow ROWID on a subquery */
143703 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
143705 pTab->tabFlags |= TF_Ephemeral; /* Legacy compatibility mode */
143707 return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
143726 N--;
143728 if( pBase->fg.isUsing==0 ) continue;
143729 if( NEVER(pBase->u3.pUsing==0) ) continue;
143730 if( sqlite3IdListIndex(pBase->u3.pUsing, zName)>=0 ) return 1;
143743 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
143745 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
143761 Parse *pParse = pWalker->pParse;
143766 sqlite3 *db = pParse->db;
143768 u16 selFlags = p->selFlags;
143771 p->selFlags |= SF_Expanded;
143772 if( db->mallocFailed ){
143775 assert( p->pSrc!=0 );
143779 if( pWalker->eCode ){
143781 p->selId = ++pParse->nSelect;
143783 pTabList = p->pSrc;
143784 pEList = p->pEList;
143785 if( pParse->pWith && (p->selFlags & SF_View) ){
143786 if( p->pWith==0 ){
143787 p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With));
143788 if( p->pWith==0 ){
143792 p->pWith->bView = 1;
143794 sqlite3WithPush(pParse, p->pWith, 0);
143805 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
143807 assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
143808 if( pFrom->pTab ) continue;
143809 assert( pFrom->fg.isRecursive==0 );
143810 if( pFrom->zName==0 ){
143812 Select *pSel = pFrom->pSelect;
143813 /* A sub-query in the FROM clause of a SELECT */
143815 assert( pFrom->pTab==0 );
143822 pTab = pFrom->pTab;
143827 assert( pFrom->pTab==0 );
143828 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
143830 if( pTab->nTabRef>=0xffff ){
143832 pTab->zName);
143833 pFrom->pTab = 0;
143836 pTab->nTabRef++;
143843 u8 eCodeOrig = pWalker->eCode;
143845 assert( pFrom->pSelect==0 );
143847 if( (db->flags & SQLITE_EnableView)==0
143848 && pTab->pSchema!=db->aDb[1].pSchema
143851 pTab->zName);
143853 pFrom->pSelect = sqlite3SelectDup(db, pTab->u.view.pSelect, 0);
143857 && pFrom->fg.fromDDL
143858 && ALWAYS(pTab->u.vtab.p!=0)
143859 && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
143862 pTab->zName);
143866 nCol = pTab->nCol;
143867 pTab->nCol = -1;
143868 pWalker->eCode = 1; /* Turn on Select.selId renumbering */
143869 sqlite3WalkSelect(pWalker, pFrom->pSelect);
143870 pWalker->eCode = eCodeOrig;
143871 pTab->nCol = nCol;
143877 if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){
143884 assert( db->mallocFailed==0 || pParse->nErr!=0 );
143885 if( pParse->nErr || sqlite3ProcessJoin(pParse, p) ){
143900 for(k=0; k<pEList->nExpr; k++){
143901 pE = pEList->a[k].pExpr;
143902 if( pE->op==TK_ASTERISK ) break;
143903 assert( pE->op!=TK_DOT || pE->pRight!=0 );
143904 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
143905 if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
143906 elistFlags |= pE->flags;
143908 if( k<pEList->nExpr ){
143914 struct ExprList_item *a = pEList->a;
143916 int flags = pParse->db->flags;
143920 for(k=0; k<pEList->nExpr; k++){
143922 elistFlags |= pE->flags;
143923 pRight = pE->pRight;
143924 assert( pE->op!=TK_DOT || pRight!=0 );
143925 if( pE->op!=TK_ASTERISK
143926 && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
143932 pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
143933 pNew->a[pNew->nExpr-1].fg.eEName = a[k].fg.eEName;
143942 if( pE->op==TK_DOT ){
143943 assert( pE->pLeft!=0 );
143944 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
143945 zTName = pE->pLeft->u.zToken;
143947 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
143948 Table *pTab = pFrom->pTab; /* Table for this data source */
143949 ExprList *pNestedFrom; /* Result-set of a nested FROM clause */
143950 char *zTabName; /* AS name for this data source */
143951 const char *zSchemaName = 0; /* Schema name for this data source */
143955 if( (zTabName = pFrom->zAlias)==0 ){
143956 zTabName = pTab->zName;
143958 if( db->mallocFailed ) break;
143959 assert( (int)pFrom->fg.isNestedFrom == IsNestedFrom(pFrom->pSelect) );
143960 if( pFrom->fg.isNestedFrom ){
143961 assert( pFrom->pSelect!=0 );
143962 pNestedFrom = pFrom->pSelect->pEList;
143964 assert( pNestedFrom->nExpr==pTab->nCol );
143970 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
143971 zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
143973 if( i+1<pTabList->nSrc
143979 for(ii=0; ii<pUsing->nId; ii++){
143980 const char *zUName = pUsing->a[ii].zName;
143984 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
143985 assert( pX->zEName==0 );
143986 pX->zEName = sqlite3MPrintf(db,"..%s", zUName);
143987 pX->fg.eEName = ENAME_TAB;
143988 pX->fg.bUsingTerm = 1;
143994 for(j=0; j<pTab->nCol; j++){
143995 char *zName = pTab->aCol[j].zCnName;
144001 && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0)==0
144007 ** result-set list unless the SELECT has the SF_IncludeHidden
144010 if( (p->selFlags & SF_IncludeHidden)==0
144011 && IsHiddenColumn(&pTab->aCol[j])
144015 if( (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
144024 if( pFrom->fg.isUsing
144025 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0
144033 if( (pTabList->nSrc>1
144034 && ( (pFrom->fg.jointype & JT_LTORJ)==0
144036 || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1)
144044 if( IN_RENAME_OBJECT && pE->pLeft ){
144045 sqlite3RenameTokenRemap(pParse, pLeft, pE->pLeft);
144058 pX = &pNew->a[pNew->nExpr-1];
144059 assert( pX->zEName==0 );
144062 pX->zEName = sqlite3DbStrDup(db, pNestedFrom->a[j].zEName);
144063 testcase( pX->zEName==0 );
144065 pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
144067 testcase( pX->zEName==0 );
144069 pX->fg.eEName = ENAME_TAB;
144070 if( (pFrom->fg.isUsing
144071 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0)
144073 || (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
144075 pX->fg.bNoExpand = 1;
144078 pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
144079 pX->fg.eEName = ENAME_NAME;
144081 pX->zEName = sqlite3DbStrDup(db, zName);
144082 pX->fg.eEName = ENAME_NAME;
144096 p->pEList = pNew;
144098 if( p->pEList ){
144099 if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
144104 p->selFlags |= SF_ComplexResult;
144109 SELECTTRACE(0x100,pParse,p,("After result-set wildcard expansion:\n"));
144136 ** The calling function can detect the problem by looking at pParse->nErr
144137 ** and/or pParse->db->mallocFailed.
144143 if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
144160 ** For each FROM-clause subquery, add Column.zType and Column.zColl
144175 assert( p->selFlags & SF_Resolved );
144176 if( p->selFlags & SF_HasTypeInfo ) return;
144177 p->selFlags |= SF_HasTypeInfo;
144178 pParse = pWalker->pParse;
144179 pTabList = p->pSrc;
144180 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
144181 Table *pTab = pFrom->pTab;
144183 if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
144184 /* A sub-query in the FROM clause of a SELECT */
144185 Select *pSel = pFrom->pSelect;
144187 while( pSel->pPrior ) pSel = pSel->pPrior;
144199 ** the Table structures of all FROM-clause subqueries in a
144220 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
144221 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
144233 assert( p!=0 || pParse->db->mallocFailed );
144234 assert( pParse->db->pParse==pParse );
144235 if( pParse->db->mallocFailed ) return;
144236 if( p->selFlags & SF_HasTypeInfo ) return;
144238 if( pParse->nErr ) return;
144240 if( pParse->nErr ) return;
144253 Vdbe *v = pParse->pVdbe;
144256 int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
144257 assert( pParse->db->pParse==pParse );
144258 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
144260 if( pParse->nErr ) return;
144264 assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
144265 for(i=0; i<pAggInfo->nColumn; i++){
144266 assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
144267 && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
144269 for(i=0; i<pAggInfo->nFunc; i++){
144270 assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
144271 && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
144274 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
144275 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
144276 if( pFunc->iDistinct>=0 ){
144277 Expr *pE = pFunc->pFExpr;
144279 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
144282 pFunc->iDistinct = -1;
144284 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
144285 pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
144286 pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO);
144287 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)",
144288 pFunc->pFunc->zName));
144299 Vdbe *v = pParse->pVdbe;
144302 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
144304 assert( ExprUseXList(pF->pFExpr) );
144305 pList = pF->pFExpr->x.pList;
144306 sqlite3VdbeAddOp2(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0);
144307 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
144316 ** If regAcc is non-zero and there are no min() or max() aggregates
144317 ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
144327 Vdbe *v = pParse->pVdbe;
144334 pAggInfo->directMode = 1;
144335 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
144340 assert( ExprUseXList(pF->pFExpr) );
144341 assert( !IsWindowFunc(pF->pFExpr) );
144342 pList = pF->pFExpr->x.pList;
144343 if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
144344 Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
144345 if( pAggInfo->nAccumulator
144346 && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
144352 if( regHit==0 ) regHit = ++pParse->nMem;
144366 nArg = pList->nExpr;
144373 if( pF->iDistinct>=0 && pList ){
144377 pF->iDistinct = codeDistinct(pParse, eDistinctType,
144378 pF->iDistinct, addrNext, pList, regAgg);
144380 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
144384 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
144385 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
144386 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
144389 pColl = pParse->db->pDfltColl;
144391 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
144394 sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, pF->iMem);
144395 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
144402 if( regHit==0 && pAggInfo->nAccumulator ){
144408 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
144409 sqlite3ExprCode(pParse, pC->pCExpr, pC->iMem);
144412 pAggInfo->directMode = 0;
144428 if( pParse->explain==2 ){
144431 pTab->zName,
144433 bCover ? pIdx->zName : ""
144448 ** sub-expression matches the criteria for being moved to the WHERE
144449 ** clause. If so, add it to the WHERE clause and replace the sub-expression
144453 if( pExpr->op!=TK_AND ){
144454 Select *pS = pWalker->u.pSelect;
144456 ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
144462 if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
144464 && pExpr->pAggInfo==0
144466 sqlite3 *db = pWalker->pParse->db;
144469 Expr *pWhere = pS->pWhere;
144471 pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
144472 pS->pWhere = pNew;
144473 pWalker->eCode = 1;
144502 sqlite3WalkExpr(&sWalker, p->pHaving);
144512 ** Check to see if the pThis entry of pTabList is a self-join of a prior view.
144517 SrcList *pTabList, /* Search for self-joins in this FROM clause */
144521 assert( pThis->pSelect!=0 );
144522 if( pThis->pSelect->selFlags & SF_PushDown ) return 0;
144523 for(pItem = pTabList->a; pItem<pThis; pItem++){
144525 if( pItem->pSelect==0 ) continue;
144526 if( pItem->fg.viaCoroutine ) continue;
144527 if( pItem->zName==0 ) continue;
144528 assert( pItem->pTab!=0 );
144529 assert( pThis->pTab!=0 );
144530 if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
144531 if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
144532 pS1 = pItem->pSelect;
144533 if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
144538 if( pItem->pSelect->selFlags & SF_PushDown ){
144552 sqlite3DbFree(db, p->aCol);
144553 sqlite3DbFree(db, p->aFunc);
144582 if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
144583 if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
144584 if( p->pWhere ) return 0;
144585 if( p->pGroupBy ) return 0;
144586 pExpr = p->pEList->a[0].pExpr;
144587 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
144589 if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
144591 if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
144592 if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
144593 pSub = p->pSrc->a[0].pSelect;
144595 if( pSub->pPrior==0 ) return 0; /* Must be a compound ry */
144597 if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
144598 if( pSub->pWhere ) return 0; /* No WHERE clause */
144599 if( pSub->pLimit ) return 0; /* No LIMIT clause */
144600 if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
144601 pSub = pSub->pPrior; /* Repeat over compound */
144606 db = pParse->db;
144609 pSub = p->pSrc->a[0].pSelect;
144610 p->pSrc->a[0].pSelect = 0;
144611 sqlite3SrcListDelete(db, p->pSrc);
144612 p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
144615 pPrior = pSub->pPrior;
144616 pSub->pPrior = 0;
144617 pSub->pNext = 0;
144618 pSub->selFlags |= SF_Aggregate;
144619 pSub->selFlags &= ~SF_Compound;
144620 pSub->nSelectRow = 0;
144621 sqlite3ExprListDelete(db, pSub->pEList);
144623 pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
144633 p->pEList->a[0].pExpr = pExpr;
144634 p->selFlags &= ~SF_Aggregate;
144638 SELECTTRACE(0x400,pParse,p,("After count-of-view optimization:\n"));
144647 ** If any term of pSrc, or any SF_NestedFrom sub-query, is not the same
144653 for(i=0; i<pSrc->nSrc; i++){
144654 SrcItem *p1 = &pSrc->a[i];
144656 if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
144659 if( p1->pSelect
144660 && (p1->pSelect->selFlags & SF_NestedFrom)!=0
144661 && sameSrcAlias(p0, p1->pSelect->pSrc)
144677 ** pParse->zErrMsg.
144705 db = pParse->db;
144706 assert( pParse==db->pParse );
144708 if( p==0 || pParse->nErr ){
144711 assert( db->mallocFailed==0 );
144714 SELECTTRACE(1,pParse,p, ("begin processing:\n", pParse->addrExplain));
144724 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
144725 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
144726 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
144727 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
144729 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
144730 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
144731 pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_DistFifo );
144733 if( p->pOrderBy ){
144737 sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
144742 p->pOrderBy);
144743 testcase( pParse->earlyCleanup );
144744 p->pOrderBy = 0;
144746 p->selFlags &= ~SF_Distinct;
144747 p->selFlags |= SF_NoopOrderBy;
144750 if( pParse->nErr ){
144753 assert( db->mallocFailed==0 );
144754 assert( p->pEList!=0 );
144764 ** In this case, it is an error if the target object (pSrc->a[0]) name
144765 ** or alias is duplicated within FROM clause (pSrc->a[1..n]).
144771 if( p->selFlags & SF_UFSrcCheck ){
144772 SrcItem *p0 = &p->pSrc->a[0];
144773 if( sameSrcAlias(p0, p->pSrc) ){
144776 p0->zAlias ? p0->zAlias : p0->pTab->zName
144782 ** and leaving this flag set can cause errors if a compound sub-query
144783 ** in p->pSrc is flattened into this query and this function called
144785 p->selFlags &= ~SF_UFSrcCheck;
144788 if( pDest->eDest==SRT_Output ){
144794 assert( pParse->nErr );
144798 if( p->pWin && (sqlite3TreeTrace & 0x108)!=0 ){
144804 pTabList = p->pSrc;
144805 isAgg = (p->selFlags & SF_Aggregate)!=0;
144807 sSort.pOrderBy = p->pOrderBy;
144813 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
144814 SrcItem *pItem = &pTabList->a[i];
144815 Select *pSub = pItem->pSelect;
144816 Table *pTab = pItem->pTab;
144826 if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))==JT_LEFT
144827 && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
144831 ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
144832 pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
144833 assert( pItem->iCursor>=0 );
144834 unsetJoinExpr(p->pWhere, pItem->iCursor,
144835 pTabList->a[0].fg.jointype & JT_LTORJ);
144843 if( pTab->nCol!=pSub->pEList->nExpr ){
144845 pTab->nCol, pTab->zName, pSub->pEList->nExpr);
144853 ** will be implemented as a co-routine and there is no advantage to
144856 if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
144857 assert( pSub->pGroupBy==0 );
144859 /* If a FROM-clause subquery has an ORDER BY clause that is not
144868 ** (2) The subquery was added to help with window-function
144872 ** the built-in count(), min(), or max().
144879 if( pSub->pOrderBy!=0
144880 && (p->pOrderBy!=0 || pTabList->nSrc>1) /* Condition (5) */
144881 && pSub->pLimit==0 /* Condition (1) */
144882 && (pSub->selFlags & SF_OrderByReqd)==0 /* Condition (2) */
144883 && (p->selFlags & SF_OrderByReqd)==0 /* Condition (3) and (4) */
144887 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
144890 pSub->pOrderBy);
144891 pSub->pOrderBy = 0;
144897 ** it will be implemented as a co-routine, then do not flatten. This
144912 if( pSub->pOrderBy!=0
144914 && (p->selFlags & SF_ComplexResult)!=0
144915 && (pTabList->nSrc==1
144916 || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)
144922 if( pParse->nErr ) goto select_end;
144924 i = -1;
144926 pTabList = p->pSrc;
144927 if( db->mallocFailed ) goto select_end;
144929 sSort.pOrderBy = p->pOrderBy;
144938 if( p->pPrior ){
144941 SELECTTRACE(0x1,pParse,p,("end compound-select processing\n"));
144946 if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
144951 /* Do the WHERE-clause constant propagation optimization if this is
144952 ** a join. No need to speed time on this operation for non-join queries
144956 if( p->pWhere!=0
144957 && p->pWhere->op==TK_AND
144975 if( db->mallocFailed ) goto select_end;
144976 pEList = p->pEList;
144977 pTabList = p->pSrc;
144983 ** (2) Generate code for all sub-queries
144985 for(i=0; i<pTabList->nSrc; i++){
144986 SrcItem *pItem = &pTabList->a[i];
144999 ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
145000 ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
145007 ** assume the column name is non-NULL and segfault. The use of an empty
145010 if( pItem->colUsed==0 && pItem->zName!=0 ){
145011 sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
145015 /* Generate code for all sub-queries in the FROM clause
145017 pSub = pItem->pSelect;
145021 assert( pItem->addrFillSub==0 );
145026 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
145030 pParse->nHeight += sqlite3SelectExprHeight(p);
145032 /* Make copies of constant WHERE-clause terms in the outer query down
145036 && (pItem->fg.isCte==0
145037 || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
145038 && pushDownWhereTerms(pParse, pSub, p->pWhere, pItem)
145043 ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
145047 assert( pItem->pSelect && (pItem->pSelect->selFlags & SF_PushDown)!=0 );
145049 SELECTTRACE(0x100,pParse,p,("Push-down not possible\n"));
145052 zSavedAuthContext = pParse->zAuthContext;
145053 pParse->zAuthContext = pItem->zName;
145057 ** The subquery is implemented as a co-routine if all of the following are
145066 && (pTabList->nSrc==1
145067 || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0) /* (1) */
145068 && (pItem->fg.isCte==0 || pItem->u2.pCteUse->eM10d!=M10d_Yes) /* (2) */
145069 && (pTabList->a[0].fg.jointype & JT_LTORJ)==0 /* (3) */
145071 /* Implement a co-routine that will return a single row of the result
145076 pItem->regReturn = ++pParse->nMem;
145077 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
145079 pItem->addrFillSub = addrTop;
145080 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
145081 ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem));
145083 pItem->pTab->nRowLogEst = pSub->nSelectRow;
145084 pItem->fg.viaCoroutine = 1;
145085 pItem->regResult = dest.iSdst;
145086 sqlite3VdbeEndCoroutine(v, pItem->regReturn);
145087 sqlite3VdbeJumpHere(v, addrTop-1);
145089 }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){
145092 ** the make the pItem->iCursor be a copy of the ephemerial table that
145094 CteUse *pCteUse = pItem->u2.pCteUse;
145095 sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
145096 if( pItem->iCursor!=pCteUse->iCur ){
145097 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
145100 pSub->nSelectRow = pCteUse->nRowEst;
145104 if( pPrior->addrFillSub ){
145105 sqlite3VdbeAddOp2(v, OP_Gosub, pPrior->regReturn, pPrior->addrFillSub);
145107 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
145108 pSub->nSelectRow = pPrior->pSelect->nSelectRow;
145116 pItem->regReturn = ++pParse->nMem;
145118 pItem->addrFillSub = topAddr+1;
145119 pItem->fg.isMaterialized = 1;
145120 if( pItem->fg.isCorrelated==0 ){
145129 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
145131 dest.zAffSdst = sqlite3TableAffinityStr(db, pItem->pTab);
145135 pItem->pTab->nRowLogEst = pSub->nSelectRow;
145137 sqlite3VdbeAddOp2(v, OP_Return, pItem->regReturn, topAddr+1);
145141 if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
145142 CteUse *pCteUse = pItem->u2.pCteUse;
145143 pCteUse->addrM9e = pItem->addrFillSub;
145144 pCteUse->regRtn = pItem->regReturn;
145145 pCteUse->iCur = pItem->iCursor;
145146 pCteUse->nRowEst = pSub->nSelectRow;
145149 if( db->mallocFailed ) goto select_end;
145150 pParse->nHeight -= sqlite3SelectExprHeight(p);
145151 pParse->zAuthContext = zSavedAuthContext;
145157 pEList = p->pEList;
145158 pWhere = p->pWhere;
145159 pGroupBy = p->pGroupBy;
145160 pHaving = p->pHaving;
145161 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
145165 SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
145171 ** if the select-list is the same as the ORDER BY list, then this query
145180 ** The second form is preferred as a single index (or temp-table) may be
145182 ** written the query must use a temp-table for at least one of the ORDER
145183 ** BY and DISTINCT, and an index or separate temp-table for the other.
145185 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
145186 && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
145188 && p->pWin==0
145191 p->selFlags &= ~SF_Distinct;
145192 pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
145193 p->selFlags |= SF_Aggregate;
145194 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
145210 ** being unused if the data can be extracted in pre-sorted order.
145219 pParse, sSort.pOrderBy, 0, pEList->nExpr);
145220 sSort.iECursor = pParse->nTab++;
145223 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
145227 sSort.addrSortIndex = -1;
145232 if( pDest->eDest==SRT_EphemTab ){
145233 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
145234 if( p->selFlags & SF_NestedFrom ){
145235 /* Delete or NULL-out result columns that will never be used */
145237 for(ii=pEList->nExpr-1; ii>0 && pEList->a[ii].fg.bUsed==0; ii--){
145238 sqlite3ExprDelete(db, pEList->a[ii].pExpr);
145239 sqlite3DbFree(db, pEList->a[ii].zEName);
145240 pEList->nExpr--;
145242 for(ii=0; ii<pEList->nExpr; ii++){
145243 if( pEList->a[ii].fg.bUsed==0 ) pEList->a[ii].pExpr->op = TK_NULL;
145251 if( (p->selFlags & SF_FixedLimit)==0 ){
145252 p->nSelectRow = 320; /* 4 billion rows */
145254 if( p->pLimit ) computeLimitRegisters(pParse, p, iEnd);
145255 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
145262 if( p->selFlags & SF_Distinct ){
145263 sDistinct.tabTnct = pParse->nTab++;
145266 (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
145277 | (p->selFlags & SF_FixedLimit);
145279 Window *pWin = p->pWin; /* Main window object (or NULL) */
145290 p->pEList, p, wctrlFlags, p->nSelectRow);
145292 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
145293 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
145301 if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
145315 assert( p->pEList==pEList );
145321 int regGosub = ++pParse->nMem;
145327 VdbeNoopComment((v, "inner-loop subroutine"));
145329 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
145332 VdbeComment((v, "end inner-loop subroutine"));
145338 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
145357 int groupBySort; /* Rows come from source in GROUP BY order */
145370 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
145371 pItem->u.x.iAlias = 0;
145373 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
145374 pItem->u.x.iAlias = 0;
145377 if( p->nSelectRow>66 ) p->nSelectRow = 66;
145382 ** in the correct order. It also may not - the GROUP BY might use a
145387 if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
145390 ** ASC or DESC order - only that each group is returned contiguously.
145394 for(ii=0; ii<pGroupBy->nExpr; ii++){
145396 sortFlags = sSort.pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_DESC;
145397 pGroupBy->a[ii].fg.sortFlags = sortFlags;
145399 if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
145405 p->nSelectRow = 0;
145419 testcase( pParse->earlyCleanup );
145421 if( db->mallocFailed ){
145424 pAggInfo->selId = p->selId;
145430 pAggInfo->mnReg = pParse->nMem+1;
145431 pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
145432 pAggInfo->pGroupBy = pGroupBy;
145437 assert( pWhere==p->pWhere );
145438 assert( pHaving==p->pHaving );
145439 assert( pGroupBy==p->pGroupBy );
145441 pWhere = p->pWhere;
145445 pAggInfo->nAccumulator = pAggInfo->nColumn;
145446 if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
145447 minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
145451 for(i=0; i<pAggInfo->nFunc; i++){
145452 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
145455 sqlite3ExprAnalyzeAggList(&sNC, pExpr->x.pList);
145459 sqlite3ExprAnalyzeAggregates(&sNC, pExpr->y.pWin->pFilter);
145464 pAggInfo->mxReg = pParse->nMem;
145465 if( db->mallocFailed ) goto select_end;
145475 for(ii=0; ii<pAggInfo->nColumn; ii++){
145476 struct AggInfo_col *pCol = &pAggInfo->aCol[ii];
145478 "agg-column[%d] pTab=%s iTable=%d iColumn=%d iMem=%d"
145480 ii, pCol->pTab ? pCol->pTab->zName : "NULL",
145481 pCol->iTable, pCol->iColumn, pCol->iMem,
145482 pCol->iSorterColumn);
145483 sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
145485 for(ii=0; ii<pAggInfo->nFunc; ii++){
145486 sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
145487 ii, pAggInfo->aFunc[ii].iMem);
145488 sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
145499 int addr1; /* A-vs-B comparision jump */
145511 if( pAggInfo->nFunc==1
145512 && pAggInfo->aFunc[0].iDistinct>=0
145513 && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0)
145514 && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr))
145515 && pAggInfo->aFunc[0].pFExpr->x.pList!=0
145517 Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr;
145529 pAggInfo->sortingIdx = pParse->nTab++;
145531 0, pAggInfo->nColumn);
145533 pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
145538 iUseFlag = ++pParse->nMem;
145539 iAbortFlag = ++pParse->nMem;
145540 regOutputRow = ++pParse->nMem;
145542 regReset = ++pParse->nMem;
145544 iAMem = pParse->nMem + 1;
145545 pParse->nMem += pGroupBy->nExpr;
145546 iBMem = pParse->nMem + 1;
145547 pParse->nMem += pGroupBy->nExpr;
145550 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
145552 /* Begin a loop that will extract all source rows in GROUP BY order.
145569 if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
145587 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
145591 nGroupBy = pGroupBy->nExpr;
145594 for(i=0; i<pAggInfo->nColumn; i++){
145595 if( pAggInfo->aCol[i].iSorterColumn>=j ){
145603 pAggInfo->directMode = 1;
145604 for(i=0; i<pAggInfo->nColumn; i++){
145605 struct AggInfo_col *pCol = &pAggInfo->aCol[i];
145606 if( pCol->iSorterColumn>=j ){
145607 sqlite3ExprCode(pParse, pCol->pCExpr, j + regBase);
145611 pAggInfo->directMode = 0;
145614 sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
145619 pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
145622 sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
145624 pAggInfo->useSortingIdx = 1;
145631 ** This is an optimization - the correct answer should result regardless.
145648 sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
145651 for(j=0; j<pGroupBy->nExpr; j++){
145655 pAggInfo->directMode = 1;
145656 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
145659 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
145673 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
145692 sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop);
145712 ** is less than or equal to zero, the subroutine is a no-op. If
145729 selectInnerLoop(pParse, p, -1, &sSort,
145735 /* Generate a subroutine that will reset the group-by accumulator
145744 struct AggInfo_func *pF = &pAggInfo->aFunc[0];
145745 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
145764 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
145765 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
145769 Pgno iRoot = pTab->tnum; /* Root page of scanned b-tree */
145772 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
145776 ** (2011-04-15) Do not do a full scan of an unordered index.
145778 ** (2013-10-03) Do not count the entries in a partial index.
145784 if( !p->pSrc->a[0].fg.notIndexed ){
145785 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
145786 if( pIdx->bUnordered==0
145787 && pIdx->szIdxRow<pTab->szTabRow
145788 && pIdx->pPartIdxWhere==0
145789 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
145796 iRoot = pBest->tnum;
145800 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
145803 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
145805 sqlite3VdbeAddOp2(v, OP_Count, iCsr, pAggInfo->aFunc[0].iMem);
145823 if( pAggInfo->nAccumulator ){
145824 for(i=0; i<pAggInfo->nFunc; i++){
145825 if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
145828 if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
145832 if( i==pAggInfo->nFunc ){
145833 regAcc = ++pParse->nMem;
145836 }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){
145837 assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) );
145838 pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList;
145846 assert( p->pGroupBy==0 );
145855 assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
145867 struct AggInfo_func *pF = pAggInfo->aFunc;
145869 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
145884 selectInnerLoop(pParse, p, -1, 0, 0,
145901 assert( p->pEList==pEList );
145902 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
145911 rc = (pParse->nErr>0);
145917 assert( db->mallocFailed==0 || db->mallocFailed==1 );
145918 assert( db->mallocFailed==0 || pParse->nErr!=0 );
145921 if( pAggInfo && !db->mallocFailed ){
145922 for(i=0; i<pAggInfo->nColumn; i++){
145923 Expr *pExpr = pAggInfo->aCol[i].pCExpr;
145925 assert( pExpr->pAggInfo==pAggInfo );
145926 assert( pExpr->iAgg==i );
145928 for(i=0; i<pAggInfo->nFunc; i++){
145929 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
145931 assert( pExpr->pAggInfo==pAggInfo );
145932 assert( pExpr->iAgg==i );
145952 ** The author disclaims copyright to this source code. In place of
145992 int need; /* Slots needed in p->azResult[] */
145996 /* Make sure there is enough space in p->azResult to hold everything
145999 if( p->nRow==0 && argv!=0 ){
146004 if( p->nData + need > p->nAlloc ){
146006 p->nAlloc = p->nAlloc*2 + need;
146007 azNew = sqlite3Realloc( p->azResult, sizeof(char*)*p->nAlloc );
146009 p->azResult = azNew;
146015 if( p->nRow==0 ){
146016 p->nColumn = nCol;
146020 p->azResult[p->nData++] = z;
146022 }else if( (int)p->nColumn!=nCol ){
146023 sqlite3_free(p->zErrMsg);
146024 p->zErrMsg = sqlite3_mprintf(
146027 p->rc = SQLITE_ERROR;
146043 p->azResult[p->nData++] = z;
146045 p->nRow++;
146050 p->rc = SQLITE_NOMEM_BKPT;
146090 db->errCode = SQLITE_NOMEM;
146106 db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
146119 db->errCode = SQLITE_NOMEM;
146138 azResult--;
146152 ** The author disclaims copyright to this source code. In place of
146171 pTriggerStep = pTriggerStep->pNext;
146173 sqlite3ExprDelete(db, pTmp->pWhere);
146174 sqlite3ExprListDelete(db, pTmp->pExprList);
146175 sqlite3SelectDelete(db, pTmp->pSelect);
146176 sqlite3IdListDelete(db, pTmp->pIdList);
146177 sqlite3UpsertDelete(db, pTmp->pUpsert);
146178 sqlite3SrcListDelete(db, pTmp->pFrom);
146179 sqlite3DbFree(db, pTmp->zSpan);
146190 ** are already attached to pTab->pTrigger. But there might be additional
146192 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
146197 ** pTab as well as the triggers lised in pTab->pTrigger.
146204 assert( pParse->disableTriggers==0 );
146205 pTmpSchema = pParse->db->aDb[1].pSchema;
146206 p = sqliteHashFirst(&pTmpSchema->trigHash);
146207 pList = pTab->pTrigger;
146210 if( pTrig->pTabSchema==pTab->pSchema
146211 && pTrig->table
146212 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
146213 && (pTrig->pTabSchema!=pTmpSchema || pTrig->bReturning)
146215 pTrig->pNext = pList;
146217 }else if( pTrig->op==TK_RETURNING ){
146219 assert( pParse->db->pVtabCtx==0 );
146221 assert( pParse->bReturning );
146222 assert( &(pParse->u1.pReturning->retTrig) == pTrig );
146223 pTrig->table = pTab->zName;
146224 pTrig->pTabSchema = pTab->pSchema;
146225 pTrig->pNext = pList;
146233 printf("Triggers for %s:", pTab->zName);
146234 for(pX=pList; pX; pX=pX->pNext){
146235 printf(" %s", pX->zName);
146248 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
146267 sqlite3 *db = pParse->db; /* The database connection */
146272 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
146278 if( pName2->n>0 ){
146291 if( !pTableName || db->mallocFailed ){
146295 /* A long-standing parser bug is that this syntax was allowed:
146303 if( db->init.busy && iDb!=1 ){
146304 sqlite3DbFree(db, pTableName->a[0].zDatabase);
146305 pTableName->a[0].zDatabase = 0;
146314 if( db->init.busy==0 && pName2->n==0 && pTab
146315 && pTab->pSchema==db->aDb[1].pSchema ){
146320 if( db->mallocFailed ) goto trigger_cleanup;
146321 assert( pTableName->nSrc==1 );
146340 assert( db->mallocFailed );
146343 if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName) ){
146348 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
146352 assert( !db->init.busy );
146360 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
146370 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName->a);
146375 " trigger on table: %S", pTableName->a);
146381 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
146383 const char *zDb = db->aDb[iTabDb].zDbSName;
146384 const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
146386 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
146407 pTrigger->zName = zName;
146409 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
146410 pTrigger->pSchema = db->aDb[iDb].pSchema;
146411 pTrigger->pTabSchema = pTab->pSchema;
146412 pTrigger->op = (u8)op;
146413 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
146415 sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);
146416 pTrigger->pWhen = pWhen;
146419 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
146421 pTrigger->pColumns = pColumns;
146423 assert( pParse->pNewTrigger==0 );
146424 pParse->pNewTrigger = pTrigger;
146431 if( !pParse->pNewTrigger ){
146434 assert( pParse->pNewTrigger==pTrigger );
146439 if( db->init.iDb==1 ){
146442 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
146446 ** "orphaned trigger" - a trigger whose associated table is missing.
146448 ** 2020-11-05 see also https://sqlite.org/forum/forumpost/157dc791df
146450 db->init.orphanTrigger = 1;
146464 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
146466 sqlite3 *db = pParse->db; /* The database */
146471 pParse->pNewTrigger = 0;
146472 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
146473 zName = pTrig->zName;
146474 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
146475 pTrig->step_list = pStepList;
146477 pStepList->pTrig = pTrig;
146478 pStepList = pStepList->pNext;
146480 sqlite3TokenInit(&nameToken, pTrig->zName);
146482 if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
146483 || sqlite3FixExpr(&sFix, pTrig->pWhen)
146490 assert( !db->init.busy );
146491 pParse->pNewTrigger = pTrig;
146499 if( !db->init.busy ){
146504 ** are read-only, and the trigger makes a change to a shadow table,
146505 ** then raise an error - do not allow the trigger to be created. */
146508 for(pStep=pTrig->step_list; pStep; pStep=pStep->pNext){
146509 if( pStep->zTarget!=0
146510 && sqlite3ShadowTableName(db, pStep->zTarget)
146514 pTrig->zName, pStep->zTarget);
146524 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
146529 db->aDb[iDb].zDbSName, zName,
146530 pTrig->table, z);
146537 if( db->init.busy ){
146539 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
146545 }else if( pLink->pSchema==pLink->pTabSchema ){
146547 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
146549 pLink->pNext = pTab->pTrigger;
146550 pTab->pTrigger = pLink;
146556 assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
146589 pTriggerStep->op = TK_SELECT;
146590 pTriggerStep->pSelect = pSelect;
146591 pTriggerStep->orconf = OE_Default;
146592 pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
146600 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
146609 sqlite3 *db = pParse->db;
146612 if( pParse->nErr ) return 0;
146613 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
146616 memcpy(z, pName->z, pName->n);
146618 pTriggerStep->zTarget = z;
146619 pTriggerStep->op = op;
146620 pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
146622 sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
146645 sqlite3 *db = pParse->db;
146648 assert(pSelect != 0 || db->mallocFailed);
146653 pTriggerStep->pSelect = pSelect;
146656 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
146658 pTriggerStep->pIdList = pColumn;
146659 pTriggerStep->pUpsert = pUpsert;
146660 pTriggerStep->orconf = orconf;
146662 sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget);
146683 SrcList *pFrom, /* FROM clause for an UPDATE-FROM, or NULL */
146690 sqlite3 *db = pParse->db;
146696 pTriggerStep->pExprList = pEList;
146697 pTriggerStep->pWhere = pWhere;
146698 pTriggerStep->pFrom = pFrom;
146703 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
146704 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
146705 pTriggerStep->pFrom = sqlite3SrcListDup(db, pFrom, EXPRDUP_REDUCE);
146707 pTriggerStep->orconf = orconf;
146727 sqlite3 *db = pParse->db;
146733 pTriggerStep->pWhere = pWhere;
146736 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
146738 pTriggerStep->orconf = OE_Default;
146748 if( pTrigger==0 || pTrigger->bReturning ) return;
146749 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
146750 sqlite3DbFree(db, pTrigger->zName);
146751 sqlite3DbFree(db, pTrigger->table);
146752 sqlite3ExprDelete(db, pTrigger->pWhen);
146753 sqlite3IdListDelete(db, pTrigger->pColumns);
146770 sqlite3 *db = pParse->db;
146772 if( db->mallocFailed ) goto drop_trigger_cleanup;
146777 assert( pName->nSrc==1 );
146778 zDb = pName->a[0].zDatabase;
146779 zName = pName->a[0].zName;
146781 for(i=OMIT_TEMPDB; i<db->nDb; i++){
146785 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
146790 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName->a);
146794 pParse->checkSchema = 1;
146808 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
146818 sqlite3 *db = pParse->db;
146821 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
146822 assert( iDb>=0 && iDb<db->nDb );
146824 assert( (pTable && pTable->pSchema==pTrigger->pSchema) || iDb==1 );
146828 const char *zDb = db->aDb[iDb].zDbSName;
146831 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
146843 db->aDb[iDb].zDbSName, pTrigger->zName
146846 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
146858 pHash = &(db->aDb[iDb].pSchema->trigHash);
146861 if( pTrigger->pSchema==pTrigger->pTabSchema ){
146865 for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){
146867 *pp = (*pp)->pNext;
146874 db->mDbFlags |= DBFLAG_SchemaChange;
146890 for(e=0; e<pEList->nExpr; e++){
146891 if( sqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1;
146900 if( NEVER(db->aDb[1].pSchema==0) ) return 0;
146901 if( sqliteHashFirst(&db->aDb[1].pSchema->trigHash)==0 ) return 0;
146924 || (pList->bReturning && pList->pNext==0) );
146927 if( (pParse->db->flags & SQLITE_EnableTrigger)==0
146928 && pTab->pTrigger!=0
146933 if( pList==pTab->pTrigger ){
146937 while( ALWAYS(p->pNext) && p->pNext!=pTab->pTrigger ) p = p->pNext;
146938 p->pNext = 0;
146942 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
146943 mask |= p->tr_tm;
146944 }else if( p->op==TK_RETURNING ){
146948 p->op = op;
146955 p->tr_tm = TRIGGER_BEFORE;
146957 p->tr_tm = TRIGGER_AFTER;
146959 mask |= p->tr_tm;
146960 }else if( p->bReturning && p->op==TK_INSERT && op==TK_UPDATE
146963 mask |= p->tr_tm;
146965 p = p->pNext;
146982 if( (pTab->pTrigger==0 && !tempTriggersExist(pParse->db))
146983 || pParse->disableTriggers
146992 ** Convert the pStep->zTarget string into a SrcList and return a pointer
147005 sqlite3 *db = pParse->db;
147007 char *zName = sqlite3DbStrDup(db, pStep->zTarget);
147009 assert( pSrc==0 || pSrc->nSrc==1 );
147012 Schema *pSchema = pStep->pTrig->pSchema;
147013 pSrc->a[0].zName = zName;
147014 if( pSchema!=db->aDb[1].pSchema ){
147015 pSrc->a[0].pSchema = pSchema;
147017 if( pStep->pFrom ){
147018 SrcList *pDup = sqlite3SrcListDup(db, pStep->pFrom, 0);
147019 if( pDup && pDup->nSrc>1 && !IN_RENAME_OBJECT ){
147045 if( pTerm->op==TK_ASTERISK ) return 1;
147046 if( pTerm->op!=TK_DOT ) return 0;
147047 assert( pTerm->pRight!=0 );
147048 assert( pTerm->pLeft!=0 );
147049 if( pTerm->pRight->op!=TK_ASTERISK ) return 0;
147066 sqlite3 *db = pParse->db;
147069 for(i=0; i<pList->nExpr; i++){
147070 Expr *pOldExpr = pList->a[i].pExpr;
147074 for(jj=0; jj<pTab->nCol; jj++){
147076 if( IsHiddenColumn(pTab->aCol+jj) ) continue;
147077 pNewExpr = sqlite3Expr(db, TK_ID, pTab->aCol[jj].zCnName);
147079 if( !db->mallocFailed ){
147080 struct ExprList_item *pItem = &pNew->a[pNew->nExpr-1];
147081 pItem->zEName = sqlite3DbStrDup(db, pTab->aCol[jj].zCnName);
147082 pItem->fg.eEName = ENAME_NAME;
147088 if( !db->mallocFailed && ALWAYS(pList->a[i].zEName!=0) ){
147089 struct ExprList_item *pItem = &pNew->a[pNew->nExpr-1];
147090 pItem->zEName = sqlite3DbStrDup(db, pList->a[i].zEName);
147091 pItem->fg.eEName = pList->a[i].fg.eEName;
147101 ** is generated in-line.
147109 Vdbe *v = pParse->pVdbe;
147110 sqlite3 *db = pParse->db;
147117 assert( pParse->bReturning );
147118 assert( db->pParse==pParse );
147119 pReturning = pParse->u1.pReturning;
147120 assert( pTrigger == &(pReturning->retTrig) );
147123 sSelect.pEList = sqlite3ExprListDup(db, pReturning->pReturnEL, 0);
147127 sFrom.a[0].iCursor = -1;
147129 if( pParse->nErr==0 ){
147130 assert( db->mallocFailed==0 );
147134 pNew = sqlite3ExpandReturning(pParse, pReturning->pReturnEL, pTab);
147135 if( !db->mallocFailed ){
147138 if( pReturning->nRetCol==0 ){
147139 pReturning->nRetCol = pNew->nExpr;
147140 pReturning->iRetCur = pParse->nTab++;
147145 pParse->eTriggerOp = pTrigger->op;
147146 pParse->pTriggerTab = pTab;
147148 && ALWAYS(!db->mallocFailed)
147151 int nCol = pNew->nExpr;
147152 int reg = pParse->nMem+1;
147153 pParse->nMem += nCol+2;
147154 pReturning->iRetReg = reg;
147156 Expr *pCol = pNew->a[i].pExpr;
147157 assert( pCol!=0 ); /* Due to !db->mallocFailed ~9 lines above */
147164 sqlite3VdbeAddOp2(v, OP_NewRowid, pReturning->iRetCur, reg+i+1);
147165 sqlite3VdbeAddOp3(v, OP_Insert, pReturning->iRetCur, reg+i, reg+i+1);
147169 pParse->eTriggerOp = 0;
147170 pParse->pTriggerTab = 0;
147185 Vdbe *v = pParse->pVdbe;
147186 sqlite3 *db = pParse->db;
147188 assert( pParse->pTriggerTab && pParse->pToplevel );
147191 for(pStep=pStepList; pStep; pStep=pStep->pNext){
147202 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
147203 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
147205 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
147206 assert( pParse->okConstFactor==0 );
147209 if( pStep->zSpan ){
147211 sqlite3MPrintf(db, "-- %s", pStep->zSpan),
147216 switch( pStep->op ){
147220 sqlite3ExprListDup(db, pStep->pExprList, 0),
147221 sqlite3ExprDup(db, pStep->pWhere, 0),
147222 pParse->eOrconf, 0, 0, 0
147230 sqlite3SelectDup(db, pStep->pSelect, 0),
147231 sqlite3IdListDup(db, pStep->pIdList),
147232 pParse->eOrconf,
147233 sqlite3UpsertDup(db, pStep->pUpsert)
147241 sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
147246 default: assert( pStep->op==TK_SELECT ); {
147248 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
147279 ** Parse context structure pFrom has just been used to create a sub-vdbe
147284 assert( pFrom->zErrMsg==0 || pFrom->nErr );
147285 assert( pTo->zErrMsg==0 || pTo->nErr );
147286 if( pTo->nErr==0 ){
147287 pTo->zErrMsg = pFrom->zErrMsg;
147288 pTo->nErr = pFrom->nErr;
147289 pTo->rc = pFrom->rc;
147291 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
147296 ** Create and populate a new TriggerPrg object with a sub-program
147306 sqlite3 *db = pParse->db; /* Database handle */
147310 NameContext sNC; /* Name context for sub-vdbe */
147311 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
147313 Parse sSubParse; /* Parse context for sub-vdbe */
147315 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
147316 assert( pTop->pVdbe );
147320 ** list of the top-level Parse object sooner rather than later. */
147323 pPrg->pNext = pTop->pTriggerPrg;
147324 pTop->pTriggerPrg = pPrg;
147325 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
147327 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
147328 pPrg->pTrigger = pTrigger;
147329 pPrg->orconf = orconf;
147330 pPrg->aColmask[0] = 0xffffffff;
147331 pPrg->aColmask[1] = 0xffffffff;
147334 ** trigger sub-program. */
147340 sSubParse.zAuthContext = pTrigger->zName;
147341 sSubParse.eTriggerOp = pTrigger->op;
147342 sSubParse.nQueryLoop = pParse->nQueryLoop;
147343 sSubParse.prepFlags = pParse->prepFlags;
147348 pTrigger->zName, onErrorText(orconf),
147349 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
147350 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
147351 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
147352 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
147353 pTab->zName
147356 if( pTrigger->zName ){
147357 sqlite3VdbeChangeP4(v, -1,
147358 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
147364 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
147366 if( pTrigger->pWhen ){
147367 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
147368 if( db->mallocFailed==0
147377 /* Code the trigger program into the sub-vdbe. */
147378 codeTriggerProgram(&sSubParse, pTrigger->step_list, orconf);
147380 /* Insert an OP_Halt at the end of the sub-program. */
147385 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
147388 if( pParse->nErr==0 ){
147389 assert( db->mallocFailed==0 );
147390 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
147392 pProgram->nMem = sSubParse.nMem;
147393 pProgram->nCsr = sSubParse.nTab;
147394 pProgram->token = (void *)pTrigger;
147395 pPrg->aColmask[0] = sSubParse.oldmask;
147396 pPrg->aColmask[1] = sSubParse.newmask;
147408 ** Return a pointer to a TriggerPrg object containing the sub-program for
147422 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
147428 for(pPrg=pRoot->pTriggerPrg;
147429 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
147430 pPrg=pPrg->pNext
147436 pParse->db->errByteOffset = -1;
147459 assert( pPrg || pParse->nErr );
147462 ** is a pointer to the sub-vdbe containing the trigger program. */
147464 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
147466 sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
147467 (const char *)pPrg->pProgram, P4_SUBPROGRAM);
147469 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
147471 /* Set the P5 operand of the OP_Program instruction to non-zero if
147473 ** invocation is disallowed if (a) the sub-program is really a trigger,
147488 ** operation on pTab, this function is a no-op.
147493 ** (a copy of pTab->nCol), then registers are populated as follows:
147496 ** ------------------------------------------------------
147498 ** reg+1 OLD.* value of left-most column of pTab
147500 ** reg+N OLD.* value of right-most column of pTab
147502 ** reg+N+2 NEW.* value of left-most column of pTab
147504 ** reg+N+N+1 NEW.* value of right-most column of pTab
147537 for(p=pTrigger; p; p=p->pNext){
147542 assert( p->pSchema!=0 );
147543 assert( p->pTabSchema!=0 );
147544 assert( p->pSchema==p->pTabSchema
147545 || p->pSchema==pParse->db->aDb[1].pSchema );
147552 if( (p->op==op || (p->bReturning && p->op==TK_INSERT && op==TK_UPDATE))
147553 && p->tr_tm==tr_tm
147554 && checkColumnOverlap(p->pColumns, pChanges)
147556 if( !p->bReturning ){
147566 ** Triggers may access values stored in the old.* or new.* pseudo-table.
147567 ** This function returns a 32-bit bitmask indicating which columns of the
147572 ** Bit 0 of the returned mask is set if the left-most column of the
147604 for(p=pTrigger; p; p=p->pNext){
147605 if( p->op==op
147606 && (tr_tm&p->tr_tm)
147607 && checkColumnOverlap(p->pColumns,pChanges)
147609 if( p->bReturning ){
147615 mask |= pPrg->aColmask[isNew];
147631 ** The author disclaims copyright to this source code. In place of
147660 ** i-th column of table pTab. This routine sets the P4 parameter of the
147666 ** command. If the latter, then the row-records in the table btree on disk
147669 ** If the former, then all row-records are guaranteed to include a value
147683 ** If column as REAL affinity and the table is an ordinary b-tree table
147691 assert( pTab->nCol>i );
147692 pCol = &pTab->aCol[i];
147693 if( pCol->iDflt ){
147697 VdbeComment((v, "%s.%s", pTab->zName, pCol->zCnName));
147698 assert( i<pTab->nCol );
147701 pCol->affinity, &pValue);
147707 if( pCol->affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){
147716 ** and false if not. This is an optimization. False-positives are a
147717 ** performance degradation, but false-negatives can result in a corrupt
147720 ** aXRef[j] will be non-negative if column j of the original table is
147730 i16 iIdxCol = pIdx->aiColumn[iCol];
147736 assert( pIdx->aColExpr!=0 );
147737 assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
147738 return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
147746 ** to be unchanged. This is an optimization. False-positives are a
147747 ** performance degradation, but false-negatives can result in a corrupt
147750 ** aXRef[j] will be non-negative if column j of the original table is
147759 if( pIdx->pPartIdxWhere==0 ) return 0;
147760 return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
147768 ** table in the source-list (pSrc->a[0]).
147772 if( pRet ) pRet->iColumn = iCol+1;
147780 ** SELECT <other-columns>, pChanges FROM pTabList WHERE pWhere
147788 ** SELECT <other-columns>, pChanges FROM pTabList
147790 ** GROUP BY <other-columns>
147796 ** the <other-columns> in the query above are is determined by the type
147797 ** of table pTabList->a[0].pTab.
147800 ** PRIMARY KEY. In this case <other-columns> are the primary key columns
147804 ** If the table is actually a view, then <other-columns> are all columns of
147808 ** If the table is a virtual or ordinary intkey table, then <other-columns>
147811 ** rowid value in <other-columns> is used as the integer key, and the
147831 sqlite3 *db = pParse->db;
147832 Table *pTab = pTabList->a[0].pTab;
147852 assert( pTabList->nSrc>1 );
147854 pSrc->a[0].fg.notCte = 1;
147855 pSrc->a[0].iCursor = -1;
147856 pSrc->a[0].pTab->nTabRef--;
147857 pSrc->a[0].pTab = 0;
147860 for(i=0; i<pPk->nKeyCol; i++){
147861 Expr *pNew = exprRowColumn(pParse, pPk->aiColumn[i]);
147871 for(i=0; i<pTab->nCol; i++){
147884 assert( pChanges!=0 || pParse->db->mallocFailed );
147886 for(i=0; i<pChanges->nExpr; i++){
147888 sqlite3ExprDup(db, pChanges->a[i].pExpr, 0)
147895 if( pSelect ) pSelect->selFlags |= SF_OrderByReqd;
147897 dest.iSDParm2 = (pPk ? pPk->nKeyCol : -1);
147935 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
147936 ** an expression for the i-th column of the table.
147937 ** aXRef[i]==-1 if the i-th column is not changed. */
147943 int iRowidExpr = -1; /* Index of "rowid=" (or IPK) assignment in pChanges */
147945 NameContext sNC; /* The name-context to resolve expressions in */
147967 int nChangeFrom = 0; /* If there is a FROM, pChanges->nExpr, else 0 */
147979 db = pParse->db;
147980 assert( db->pParse==pParse );
147981 if( pParse->nErr ){
147984 assert( db->mallocFailed==0 );
147990 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
148012 sqlite3TreeViewUpdate(pParse->pWith, pTabList, pChanges, pWhere,
148018 ** in the change-list. Otherwise, set it to 0. There cannot be a FROM
148021 nChangeFrom = (pTabList->nSrc>1) ? pChanges->nExpr : 0;
148046 iBaseCur = iDataCur = pParse->nTab++;
148049 testcase( pPk!=0 && pPk!=pTab->pIndex );
148050 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
148052 iDataCur = pParse->nTab;
148054 pParse->nTab++;
148058 iDataCur = pUpsert->iDataCur;
148059 iIdxCur = pUpsert->iIdxCur;
148060 pParse->nTab = iBaseCur;
148062 pTabList->a[0].iCursor = iDataCur;
148067 aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 );
148069 aRegIdx = aXRef+pTab->nCol;
148073 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
148075 /* Initialize the name-context */
148093 for(i=0; i<pChanges->nExpr; i++){
148094 u8 hCol = sqlite3StrIHash(pChanges->a[i].zEName);
148097 if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
148100 for(j=0; j<pTab->nCol; j++){
148101 if( pTab->aCol[j].hName==hCol
148102 && sqlite3StrICmp(pTab->aCol[j].zCnName, pChanges->a[i].zEName)==0
148104 if( j==pTab->iPKey ){
148106 pRowidExpr = pChanges->a[i].pExpr;
148108 }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
148112 else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){
148113 testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );
148114 testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );
148117 pTab->aCol[j].zCnName);
148125 if( j>=pTab->nCol ){
148126 if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){
148127 j = -1;
148129 pRowidExpr = pChanges->a[i].pExpr;
148132 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName);
148133 pParse->checkSchema = 1;
148140 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
148141 j<0 ? "ROWID" : pTab->aCol[j].zCnName,
148142 db->aDb[iDb].zDbSName);
148146 aXRef[j] = -1;
148160 ** is non-negative, so the value of aXRef[] for generated columns can be
148161 ** set to any non-negative number. We use 99999 so that the value is
148164 if( pTab->tabFlags & TF_HasGenerated ){
148166 testcase( pTab->tabFlags & TF_HasVirtual );
148167 testcase( pTab->tabFlags & TF_HasStored );
148170 for(i=0; i<pTab->nCol; i++){
148172 if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue;
148174 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
148190 pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
148199 for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){
148204 reg = ++pParse->nMem;
148205 pParse->nMem += pIdx->nColumn;
148208 for(i=0; i<pIdx->nKeyCol; i++){
148210 reg = ++pParse->nMem;
148211 pParse->nMem += pIdx->nColumn;
148212 if( onError==OE_Default && pIdx->onError==OE_Replace ){
148222 aRegIdx[nAllIdx] = ++pParse->nMem; /* Register storing the table record */
148229 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
148238 ** two-pass update algorithm. */
148239 assert( aRegIdx[nAllIdx]==pParse->nMem );
148241 regOldRowid = regNewRowid = ++pParse->nMem;
148243 regOld = pParse->nMem + 1;
148244 pParse->nMem += pTab->nCol;
148247 regNewRowid = ++pParse->nMem;
148249 regNew = pParse->nMem + 1;
148250 pParse->nMem += pTab->nCol;
148255 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
148292 if( (db->flags&SQLITE_CountRows)!=0
148293 && !pParse->pTriggerTab
148294 && !pParse->nested
148295 && !pParse->bReturning
148298 regRowCount = ++pParse->nMem;
148304 iEph = pParse->nTab++;
148308 nPk = pPk ? pPk->nKeyCol : 0;
148309 iPk = pParse->nMem+1;
148310 pParse->nMem += nPk;
148311 pParse->nMem += nChangeFrom;
148312 regKey = ++pParse->nMem;
148314 int nEphCol = nPk + nChangeFrom + (isView ? pTab->nCol : 0);
148315 iEph = pParse->nTab++;
148316 if( pPk ) sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
148321 pKeyInfo->nAllField = nEphCol;
148355 ** Do not consider a single-pass strategy for a multi-row update if
148359 ** or index, causing a single-pass approach to malfunction. */
148361 if( !pParse->nested && !pTrigger && !hasFK && !chngKey && !bReplace ){
148367 /* A one-pass strategy that might update more than one row may not
148383 if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
148393 ** mode, write the rowid into the FIFO. In either of the one-pass modes,
148397 aRegIdx[nAllIdx] = ++pParse->nMem;
148409 assert( pPk->aiColumn[i]>=0 );
148411 pPk->aiColumn[i], iPk+i);
148435 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
148436 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
148439 if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
148517 /* Compute the old pre-UPDATE content of the row being changed, if that
148524 for(i=0; i<pTab->nCol; i++){
148525 u32 colFlags = pTab->aCol[i].colFlags;
148558 for(i=0, k=regNew; i<pTab->nCol; i++, k++){
148559 if( i==pTab->iPKey ){
148561 }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){
148562 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
148567 int nOff = (isView ? pTab->nCol : nPk);
148571 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k);
148589 if( pTab->tabFlags & TF_HasGenerated ){
148590 testcase( pTab->tabFlags & TF_HasVirtual );
148591 testcase( pTab->tabFlags & TF_HasStored );
148605 /* The row-trigger may have deleted the row being updated. In this
148607 ** required. This behavior - what happens when the row being updated
148608 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
148619 /* After-BEFORE-trigger-reload-loop:
148625 ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26)
148628 for(i=0, k=regNew; i<pTab->nCol; i++, k++){
148629 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
148630 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
148631 }else if( aXRef[i]<0 && i!=pTab->iPKey ){
148636 if( pTab->tabFlags & TF_HasGenerated ){
148637 testcase( pTab->tabFlags & TF_HasVirtual );
148638 testcase( pTab->tabFlags & TF_HasStored );
148670 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
148683 ** to invoke the pre-update hook.
148686 ** pre-update hook. If the caller invokes preupdate_new(), the returned
148700 if( !pParse->nested ){
148741 /* Nothing to do at end-of-loop for a single-pass */
148755 if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
148793 ** There are two possible strategies - the default and the special
148821 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
148824 sqlite3 *db = pParse->db; /* Database connection */
148827 int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
148831 int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
148840 ephemTab = pParse->nTab++;
148842 regArg = pParse->nMem + 1;
148843 pParse->nMem += nArg;
148844 if( pSrc->nSrc>1 ){
148858 assert( pPk->nKeyCol==1 );
148859 iPk = pPk->aiColumn[0];
148861 pRow = sqlite3ExprDup(db, pChanges->a[aXRef[iPk]].pExpr, 0);
148868 for(i=0; i<pTab->nCol; i++){
148871 sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0)
148882 regRec = ++pParse->nMem;
148883 regRowid = ++pParse->nMem;
148892 for(i=0; i<pTab->nCol; i++){
148893 assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 );
148895 sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
148913 assert( pPk->nKeyCol==1 );
148914 iPk = pPk->aiColumn[0];
148925 /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
148936 ** accept no-change records with serial_type 10 */
148947 if( pSrc->nSrc==1 ){
148980 ** 2018-04-12
148982 ** The author disclaims copyright to this source code. In place of
149001 Upsert *pNext = p->pNextUpsert;
149002 sqlite3ExprListDelete(db, p->pUpsertTarget);
149003 sqlite3ExprDelete(db, p->pUpsertTargetWhere);
149004 sqlite3ExprListDelete(db, p->pUpsertSet);
149005 sqlite3ExprDelete(db, p->pUpsertWhere);
149006 sqlite3DbFree(db, p->pToFree);
149022 sqlite3ExprListDup(db, p->pUpsertTarget, 0),
149023 sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
149024 sqlite3ExprListDup(db, p->pUpsertSet, 0),
149025 sqlite3ExprDup(db, p->pUpsertWhere, 0),
149026 sqlite3UpsertDup(db, p->pNextUpsert)
149051 pNew->pUpsertTarget = pTarget;
149052 pNew->pUpsertTargetWhere = pTargetWhere;
149053 pNew->pUpsertSet = pSet;
149054 pNew->pUpsertWhere = pWhere;
149055 pNew->isDoUpdate = pSet!=0;
149056 pNew->pNextUpsert = pNext;
149063 ** symbols in the conflict-target.
149077 ExprList *pTarget; /* The conflict-target clause */
149078 Expr *pTerm; /* One term of the conflict-target clause */
149083 assert( pTabList->nSrc==1 );
149084 assert( pTabList->a[0].pTab!=0 );
149086 assert( pUpsert->pUpsertTarget!=0 );
149088 /* Resolve all symbolic names in the conflict-target clause, which
149089 ** includes both the list of columns and the optional partial-index
149095 for(; pUpsert && pUpsert->pUpsertTarget;
149096 pUpsert=pUpsert->pNextUpsert, nClause++){
149097 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
149099 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
149103 pTab = pTabList->a[0].pTab;
149104 pTarget = pUpsert->pUpsertTarget;
149105 iCursor = pTabList->a[0].iCursor;
149107 && pTarget->nExpr==1
149108 && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
149109 && pTerm->iColumn==XN_ROWID
149111 /* The conflict-target is the rowid of the primary table */
149112 assert( pUpsert->pUpsertIdx==0 );
149120 ** prior to comparing against the conflict-target expression.
149126 sCol[1].iTable = pTabList->a[0].iCursor;
149129 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
149132 if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
149133 if( pIdx->pPartIdxWhere ){
149134 if( pUpsert->pUpsertTargetWhere==0 ) continue;
149135 if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
149136 pIdx->pPartIdxWhere, iCursor)!=0 ){
149140 nn = pIdx->nKeyCol;
149143 sCol[0].u.zToken = (char*)pIdx->azColl[ii];
149144 if( pIdx->aiColumn[ii]==XN_EXPR ){
149145 assert( pIdx->aColExpr!=0 );
149146 assert( pIdx->aColExpr->nExpr>ii );
149147 assert( pIdx->bHasExpr );
149148 pExpr = pIdx->aColExpr->a[ii].pExpr;
149149 if( pExpr->op!=TK_COLLATE ){
149155 sCol[1].iColumn = pIdx->aiColumn[ii];
149159 if( sqlite3ExprCompare(pParse,pTarget->a[jj].pExpr,pExpr,iCursor)<2 ){
149173 pUpsert->pUpsertIdx = pIdx;
149176 if( pUpsert->pUpsertIdx==0 ){
149178 if( nClause==0 && pUpsert->pNextUpsert==0 ){
149199 pNext = pUpsert->pNextUpsert;
149201 if( pNext->pUpsertTarget==0 ) return 1;
149202 if( pNext->pUpsertIdx==0 ) return 1;
149215 && pUpsert->pUpsertTarget!=0
149216 && pUpsert->pUpsertIdx!=pIdx
149218 pUpsert = pUpsert->pNextUpsert;
149227 ** In this case parameter iCur is a cursor open on the table b-tree that
149233 Parse *pParse, /* The parsing and code-generating context */
149239 Vdbe *v = pParse->pVdbe;
149240 sqlite3 *db = pParse->db;
149248 iDataCur = pUpsert->iDataCur;
149260 int nPk = pPk->nKeyCol;
149261 int iPk = pParse->nMem+1;
149262 pParse->nMem += nPk;
149265 assert( pPk->aiColumn[i]>=0 );
149266 k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
149268 VdbeComment((v, "%s.%s", pIdx->zName,
149269 pTab->aCol[pPk->aiColumn[i]].zCnName));
149280 /* pUpsert does not own pTop->pUpsertSrc - the outer INSERT statement does.
149282 pSrc = sqlite3SrcListDup(db, pTop->pUpsertSrc, 0);
149284 for(i=0; i<pTab->nCol; i++){
149285 if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
149286 sqlite3VdbeAddOp1(v, OP_RealAffinity, pTop->regData+i);
149289 sqlite3Update(pParse, pSrc, sqlite3ExprListDup(db,pUpsert->pUpsertSet,0),
149290 sqlite3ExprDup(db,pUpsert->pUpsertWhere,0), OE_Abort, 0, 0, pUpsert);
149301 ** The author disclaims copyright to this source code. In place of
149334 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
149406 if( pParse->nErr ) goto build_vacuum_end;
149415 ** to VACUUM are silently ignored. This is a back-out of a bug fix that
149416 ** occurred on 2016-08-19 (https://www.sqlite.org/src/info/083f9e6270).
149419 iDb = sqlite3FindDb(pParse->db, pNm);
149426 iIntoReg = ++pParse->nMem;
149433 sqlite3ExprDelete(pParse->db, pInto);
149449 u32 saved_mDbFlags; /* Saved value of db->mDbFlags */
149450 u64 saved_flags; /* Saved value of db->flags */
149451 i64 saved_nChange; /* Saved value of db->nChange */
149452 i64 saved_nTotalChange; /* Saved value of db->nTotalChange */
149453 u32 saved_openFlags; /* Saved value of db->openFlags */
149463 if( !db->autoCommit ){
149465 return SQLITE_ERROR; /* IMP: R-12218-18073 */
149467 if( db->nVdbeActive>1 ){
149468 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
149469 return SQLITE_ERROR; /* IMP: R-15610-35227 */
149471 saved_openFlags = db->openFlags;
149474 sqlite3SetString(pzErrMsg, db, "non-text filename");
149478 db->openFlags &= ~SQLITE_OPEN_READONLY;
149479 db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
149485 ** restored before returning. Then set the writable-schema flag, and
149487 saved_flags = db->flags;
149488 saved_mDbFlags = db->mDbFlags;
149489 saved_nChange = db->nChange;
149490 saved_nTotalChange = db->nTotalChange;
149491 saved_mTrace = db->mTrace;
149492 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
149493 db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
149494 db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder
149496 db->mTrace = 0;
149498 zDbMain = db->aDb[iDb].zDbSName;
149499 pMain = db->aDb[iDb].pBt;
149508 ** An optimisation would be to use a non-journaled pager.
149516 nDb = db->nDb;
149518 db->openFlags = saved_openFlags;
149520 assert( (db->nDb-1)==nDb );
149521 pDb = &db->aDb[nDb];
149522 assert( strcmp(pDb->zDbSName,"vacuum_db")==0 );
149523 pTemp = pDb->pBt;
149527 if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){
149532 db->mDbFlags |= DBFLAG_VacuumInto;
149534 /* For a VACUUM INTO, the pager-flags are set to the same values as
149537 pgflags = db->aDb[iDb].safety_level | (db->flags & PAGER_FLAGS_MASK);
149542 if( db->nextPagesize ){
149547 if( nKey ) db->nextPagesize = 0;
149551 sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
149557 ** to ensure that we do not try to change the page-size on a WAL database.
149569 db->nextPagesize = 0;
149573 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
149574 || NEVER(db->mallocFailed)
149581 sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
149588 db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
149602 db->init.iDb = 0;
149615 assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
149616 db->mDbFlags &= ~DBFLAG_Vacuum;
149635 ** both transactions are closed by this block - the main database
149689 /* Restore the original value of db->flags */
149690 db->init.iDb = 0;
149691 db->mDbFlags = saved_mDbFlags;
149692 db->flags = saved_flags;
149693 db->nChange = saved_nChange;
149694 db->nTotalChange = saved_nTotalChange;
149695 db->mTrace = saved_mTrace;
149696 sqlite3BtreeSetPageSize(pMain, -1, 0, 1);
149705 db->autoCommit = 1;
149708 sqlite3BtreeClose(pDb->pBt);
149709 pDb->pBt = 0;
149710 pDb->pSchema = 0;
149713 /* This both clears the schemas and reduces the size of the db->aDb[]
149727 ** The author disclaims copyright to this source code. In place of
149784 pMod->zName = zCopy;
149785 pMod->pModule = pModule;
149786 pMod->pAux = pAux;
149787 pMod->xDestroy = xDestroy;
149788 pMod->pEpoTab = 0;
149789 pMod->nRefModule = 1;
149791 pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
149819 sqlite3_mutex_enter(db->mutex);
149823 sqlite3_mutex_leave(db->mutex);
149829 ** External API function used to create a new virtual-table module.
149844 ** External API function used to create a new virtual-table module.
149860 ** External API to drop all virtual-table modules, except those named
149868 for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){
149873 for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){}
149876 createModule(db, pMod->zName, 0, 0, 0);
149886 assert( pMod->nRefModule>0 );
149887 pMod->nRefModule--;
149888 if( pMod->nRefModule==0 ){
149889 if( pMod->xDestroy ){
149890 pMod->xDestroy(pMod->pAux);
149892 assert( pMod->pEpoTab==0 );
149906 pVTab->nRef++;
149911 ** pTab is a pointer to a Table structure representing a virtual-table.
149913 ** this virtual-table, if one has been created, or NULL otherwise.
149918 for(pVtab=pTab->u.vtab.p; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
149923 ** Decrement the ref-count on a virtual table object. When the ref-count
149927 sqlite3 *db = pVTab->db;
149930 assert( pVTab->nRef>0 );
149931 assert( db->eOpenState==SQLITE_STATE_OPEN
149932 || db->eOpenState==SQLITE_STATE_ZOMBIE );
149934 pVTab->nRef--;
149935 if( pVTab->nRef==0 ){
149936 sqlite3_vtab *p = pVTab->pVtab;
149937 sqlite3VtabModuleUnref(pVTab->db, pVTab->pMod);
149939 p->pModule->xDisconnect(p);
149947 ** p->u.vtab.p list to the sqlite3.pDisconnect lists of their associated
149950 ** connection db is left in the p->u.vtab.p list.
149957 pVTable = p->u.vtab.p;
149958 p->u.vtab.p = 0;
149964 ** database connection that may have an entry in the p->u.vtab.p list.
149966 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
149969 sqlite3 *db2 = pVTable->db;
149970 VTable *pNext = pVTable->pNext;
149974 p->u.vtab.p = pRet;
149975 pRet->pNext = 0;
149977 pVTable->pNext = db2->pDisconnect;
149978 db2->pDisconnect = pVTable;
149990 ** list in p->pVTab. It also decrements the VTable ref count. This is
149993 ** be being used by other shared-cache connections).
150000 assert( sqlite3_mutex_held(db->mutex) );
150002 for(ppVTab=&p->u.vtab.p; *ppVTab; ppVTab=&(*ppVTab)->pNext){
150003 if( (*ppVTab)->db==db ){
150005 *ppVTab = pVTab->pNext;
150017 ** shared b-tree databases opened using connection db are held by the
150027 ** or, if the virtual table is stored in a non-sharable database, then
150031 ** by multiple threads. It is thread-safe.
150034 VTable *p = db->pDisconnect;
150037 assert( sqlite3_mutex_held(db->mutex) );
150040 db->pDisconnect = 0;
150043 VTable *pNext = p->pNext;
150051 ** Clear any and all virtual-table information from the Table record.
150055 ** Since it is a virtual-table, the Table structure contains a pointer
150067 if( db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
150068 if( p->u.vtab.azArg ){
150070 for(i=0; i<p->u.vtab.nArg; i++){
150071 if( i!=1 ) sqlite3DbFree(db, p->u.vtab.azArg[i]);
150073 sqlite3DbFree(db, p->u.vtab.azArg);
150078 ** Add a new module argument to pTable->u.vtab.azArg[].
150079 ** The string is not copied - the pointer is stored. The
150086 sqlite3 *db = pParse->db;
150089 nBytes = sizeof(char *)*(2+pTable->u.vtab.nArg);
150090 if( pTable->u.vtab.nArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){
150091 sqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName);
150093 azModuleArg = sqlite3DbRealloc(db, pTable->u.vtab.azArg, nBytes);
150097 int i = pTable->u.vtab.nArg++;
150100 pTable->u.vtab.azArg = azModuleArg;
150120 pTable = pParse->pNewTable;
150122 assert( 0==pTable->pIndex );
150123 pTable->eTabType = TABTYP_VTAB;
150125 db = pParse->db;
150127 assert( pTable->u.vtab.nArg==0 );
150130 addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName));
150131 assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
150132 || (pParse->sNameToken.z==pName1->z && pName2->z==0)
150134 pParse->sNameToken.n = (int)(
150135 &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
150144 if( pTable->u.vtab.azArg ){
150145 int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
150147 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
150148 pTable->u.vtab.azArg[0], pParse->db->aDb[iDb].zDbSName);
150155 ** in pParse->zArg[] and appends it to the list of arguments on the
150156 ** virtual table currently under construction in pParse->pTable.
150159 if( pParse->sArg.z && pParse->pNewTable ){
150160 const char *z = (const char*)pParse->sArg.z;
150161 int n = pParse->sArg.n;
150162 sqlite3 *db = pParse->db;
150163 addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
150172 Table *pTab = pParse->pNewTable; /* The table being constructed */
150173 sqlite3 *db = pParse->db; /* The database connection */
150178 pParse->sArg.z = 0;
150179 if( pTab->u.vtab.nArg<1 ) return;
150187 if( !db->init.busy ){
150198 pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
150200 zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
150206 ** The VM register number pParse->regRowid holds the rowid of an
150210 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
150215 db->aDb[iDb].zDbSName,
150216 pTab->zName,
150217 pTab->zName,
150219 pParse->regRowid
150225 zWhere = sqlite3MPrintf(db, "name=%Q AND sql=%Q", pTab->zName, zStmt);
150229 iReg = ++pParse->nMem;
150230 sqlite3VdbeLoadString(v, iReg, pTab->zName);
150233 /* If we are rereading the sqlite_schema table create the in-memory
150236 Schema *pSchema = pTab->pSchema;
150237 const char *zName = pTab->zName;
150240 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
150246 pParse->pNewTable = 0;
150256 pParse->sArg.z = 0;
150257 pParse->sArg.n = 0;
150265 Token *pArg = &pParse->sArg;
150266 if( pArg->z==0 ){
150267 pArg->z = p->z;
150268 pArg->n = p->n;
150270 assert(pArg->z <= p->z);
150271 pArg->n = (int)(&p->z[p->n] - pArg->z);
150291 int nArg = pTab->u.vtab.nArg;
150298 azArg = (const char *const*)pTab->u.vtab.azArg;
150300 /* Check that the virtual-table is not already being initialized */
150301 for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
150302 if( pCtx->pTab==pTab ){
150304 "vtable constructor called recursively: %s", pTab->zName
150310 zModuleName = sqlite3DbStrDup(db, pTab->zName);
150321 pVTable->db = db;
150322 pVTable->pMod = pMod;
150323 pVTable->eVtabRisk = SQLITE_VTABRISK_Normal;
150325 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
150326 pTab->u.vtab.azArg[1] = db->aDb[iDb].zDbSName;
150329 assert( &db->pVtabCtx );
150333 sCtx.pPrior = db->pVtabCtx;
150335 db->pVtabCtx = &sCtx;
150336 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
150337 db->pVtabCtx = sCtx.pPrior;
150349 }else if( ALWAYS(pVTable->pVtab) ){
150352 memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
150353 pVTable->pVtab->pModule = pMod->pModule;
150354 pMod->nRefModule++;
150355 pVTable->nRef = 1;
150358 *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
150365 ** into the linked list headed by pTab->u.vtab.p. Then loop through the
150369 pVTable->pNext = pTab->u.vtab.p;
150370 pTab->u.vtab.p = pVTable;
150372 for(iCol=0; iCol<pTab->nCol; iCol++){
150373 char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
150379 && (i==0 || zType[i-1]==' ')
150392 assert(zType[i-1]==' ');
150393 zType[i-1] = '\0';
150395 pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
150396 pTab->tabFlags |= TF_HasHidden;
150399 pTab->tabFlags |= oooHidden;
150414 ** This call is a no-op if table pTab is not a virtual table.
150417 sqlite3 *db = pParse->db;
150429 zMod = pTab->u.vtab.azArg[0];
150430 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
150433 const char *zModule = pTab->u.vtab.azArg[0];
150438 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
150441 pParse->rc = rc;
150449 ** Grow the db->aVTrans[] array so that there is room for at least one
150450 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
150456 if( (db->nVTrans%ARRAY_INCR)==0 ){
150459 ((sqlite3_int64)db->nVTrans + ARRAY_INCR);
150460 aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
150464 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
150465 db->aVTrans = aVTrans;
150477 db->aVTrans[db->nVTrans++] = pVTab;
150495 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
150496 assert( pTab && IsVirtual(pTab) && !pTab->u.vtab.p );
150499 zMod = pTab->u.vtab.azArg[0];
150500 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
150506 if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
150510 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
150542 sqlite3_mutex_enter(db->mutex);
150543 pCtx = db->pVtabCtx;
150544 if( !pCtx || pCtx->bDeclared ){
150546 sqlite3_mutex_leave(db->mutex);
150549 pTab = pCtx->pTab;
150556 ** schema. Nevertheless, defend against that (turn off db->init.busy)
150558 assert( db->init.busy==0 );
150559 initBusy = db->init.busy;
150560 db->init.busy = 0;
150564 && ALWAYS(!db->mallocFailed)
150568 if( !pTab->aCol ){
150571 pTab->aCol = pNew->aCol;
150572 sqlite3ExprListDelete(db, pNew->u.tab.pDfltList);
150573 pTab->nNVCol = pTab->nCol = pNew->nCol;
150574 pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
150575 pNew->nCol = 0;
150576 pNew->aCol = 0;
150577 assert( pTab->pIndex==0 );
150580 && pCtx->pVTable->pMod->pModule->xUpdate!=0
150581 && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
150583 /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
150584 ** or else must have a single-column PRIMARY KEY */
150587 pIdx = pNew->pIndex;
150589 assert( pIdx->pNext==0 );
150590 pTab->pIndex = pIdx;
150591 pNew->pIndex = 0;
150592 pIdx->pTable = pTab;
150595 pCtx->bDeclared = 1;
150609 db->init.busy = initBusy;
150613 sqlite3_mutex_leave(db->mutex);
150622 ** This call is a no-op if zTab is not a virtual table.
150628 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
150631 && ALWAYS(pTab->u.vtab.p!=0)
150635 for(p=pTab->u.vtab.p; p; p=p->pNext){
150636 assert( p->pVtab );
150637 if( p->pVtab->nRef>0 ){
150642 xDestroy = p->pMod->pModule->xDestroy;
150643 if( xDestroy==0 ) xDestroy = p->pMod->pModule->xDisconnect;
150645 pTab->nTabRef++;
150646 rc = xDestroy(p->pVtab);
150649 assert( pTab->u.vtab.p==p && p->pNext==0 );
150650 p->pVtab = 0;
150651 pTab->u.vtab.p = 0;
150670 if( db->aVTrans ){
150671 VTable **aVTrans = db->aVTrans;
150672 db->aVTrans = 0;
150673 for(i=0; i<db->nVTrans; i++){
150675 sqlite3_vtab *p = pVTab->pVtab;
150678 x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
150681 pVTab->iSavepoint = 0;
150685 db->nVTrans = 0;
150694 ** If an error message is available, leave it in p->zErrMsg.
150699 VTable **aVTrans = db->aVTrans;
150701 db->aVTrans = 0;
150702 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
150704 sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
150705 if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
150710 db->aVTrans = aVTrans;
150744 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
150755 pModule = pVTab->pVtab->pModule;
150757 if( pModule->xBegin ){
150761 for(i=0; i<db->nVTrans; i++){
150762 if( db->aVTrans[i]==pVTab ){
150771 rc = pModule->xBegin(pVTab->pVtab);
150773 int iSvpt = db->nStatement + db->nSavepoint;
150775 if( iSvpt && pModule->xSavepoint ){
150776 pVTab->iSavepoint = iSvpt;
150777 rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
150804 assert( iSavepoint>=-1 );
150805 if( db->aVTrans ){
150807 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
150808 VTable *pVTab = db->aVTrans[i];
150809 const sqlite3_module *pMod = pVTab->pMod->pModule;
150810 if( pVTab->pVtab && pMod->iVersion>=2 ){
150815 xMethod = pMod->xSavepoint;
150816 pVTab->iSavepoint = iSavepoint+1;
150819 xMethod = pMod->xRollbackTo;
150822 xMethod = pMod->xRelease;
150825 if( xMethod && pVTab->iSavepoint>iSavepoint ){
150826 rc = xMethod(pVTab->pVtab, iSavepoint);
150864 if( pExpr->op!=TK_COLUMN ) return pDef;
150866 pTab = pExpr->y.pTab;
150869 pVtab = sqlite3GetVTable(db, pTab)->pVtab;
150871 assert( pVtab->pModule!=0 );
150872 pMod = (sqlite3_module *)pVtab->pModule;
150873 if( pMod->xFindFunction==0 ) return pDef;
150879 ** with an all lower-case function name. Continue in this tradition to
150885 for(i=0; pDef->zName[i]; i++){
150886 unsigned char x = (unsigned char)pDef->zName[i];
150891 rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
150899 + sqlite3Strlen30(pDef->zName) + 1);
150904 pNew->zName = (const char*)&pNew[1];
150905 memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
150906 pNew->xSFunc = xSFunc;
150907 pNew->pUserData = pArg;
150908 pNew->funcFlags |= SQLITE_FUNC_EPHEM;
150913 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
150916 ** is a no-op.
150924 for(i=0; i<pToplevel->nVtabLock; i++){
150925 if( pTab==pToplevel->apVtabLock[i] ) return;
150927 n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
150928 apVtabLock = sqlite3Realloc(pToplevel->apVtabLock, n);
150930 pToplevel->apVtabLock = apVtabLock;
150931 pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
150933 sqlite3OomFault(pToplevel->db);
150940 ** exist. Return non-zero if either the eponymous virtual table instance
150947 ** instances always exist. They cannot be DROP-ed.
150953 const sqlite3_module *pModule = pMod->pModule;
150957 sqlite3 *db = pParse->db;
150958 if( pMod->pEpoTab ) return 1;
150959 if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
150962 pTab->zName = sqlite3DbStrDup(db, pMod->zName);
150963 if( pTab->zName==0 ){
150967 pMod->pEpoTab = pTab;
150968 pTab->nTabRef = 1;
150969 pTab->eTabType = TABTYP_VTAB;
150970 pTab->pSchema = db->aDb[0].pSchema;
150971 assert( pTab->u.vtab.nArg==0 );
150972 pTab->iPKey = -1;
150973 pTab->tabFlags |= TF_Eponymous;
150974 addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
150976 addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
150977 rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
150991 Table *pTab = pMod->pEpoTab;
150996 pTab->tabFlags |= TF_Ephemeral;
150998 pMod->pEpoTab = 0;
151018 assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
151019 return (int)aMap[db->vtabOnConflict-1];
151035 sqlite3_mutex_enter(db->mutex);
151036 p = db->pVtabCtx;
151040 assert( p->pTab==0 || IsVirtual(p->pTab) );
151044 p->pVTable->bConstraint = (u8)va_arg(ap, int);
151048 p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low;
151052 p->pVTable->eVtabRisk = SQLITE_VTABRISK_High;
151064 sqlite3_mutex_leave(db->mutex);
151073 ** 2015-06-06
151075 ** The author disclaims copyright to this source code. In place of
151086 ** This file was split off from where.c on 2015-06-06 in order to reduce the
151095 ** 2013-11-12
151097 ** The author disclaims copyright to this source code. In place of
151108 ** a separate source file for easier editing.
151164 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
151172 int addrSkip; /* Jump here for next iteration of skip-scan */
151176 int regBignull; /* big-null flag reg. True if a NULL-scan is needed */
151177 int addrBignull; /* Jump here for next part of big-null scan */
151187 union { /* Information that depends on pWLoop->wsFlags */
151193 int iBase; /* Base register of multi-key index record */
151197 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
151211 ** prevent a query solution - which is an error) and many terms of the
151213 ** potential way of implementing that FROM-clause term, together with
151229 LogEst rSetup; /* One-time setup cost (ex: create transient index) */
151272 ** correspond to the subquery(s) of OR-clause processing. Only the
151288 ** vector, not a scalar, and because dependencies are many-to-one, not
151289 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
151305 i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
151318 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
151349 ** spread out over the non-negative integers. For example, the cursor
151368 int iParent; /* Disable pWC->a[iParent] when this term disabled */
151378 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
151391 #define TERM_OK 0x0040 /* Used during OR-clause processing */
151397 #define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
151404 #define TERM_SLICE 0x8000 /* One slice of a row-value/vector comparison */
151415 int k; /* Resume scanning at this->pWC->a[this->k] */
151421 i16 aiColumn[11]; /* Corresponding column number in the eq-class */
151443 int nBase; /* Number of terms through the last non-Virtual */
151481 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
151482 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
151489 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
151490 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
151529 ** routine. The limit is high enough that is should not impact real-world
151567 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
151576 unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */
151590 ** Private interfaces - callable only by other where.c routines.
151642 int iLevel, /* Which level of pWInfo->a[] should be coded */
151670 ** OR-ed combination of these values can be used when searching for
151682 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
151683 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
151684 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
151685 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
151689 #define WO_OR 0x0200 /* Two or more OR-connected terms */
151690 #define WO_AND 0x0400 /* Two or more AND-connected terms */
151693 #define WO_ROWVAL 0x2000 /* A row-value term */
151696 #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
151711 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
151719 #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
151724 #define WHERE_IN_SEEKSCAN 0x00100000 /* Seek-scan optimization for IN */
151726 #define WHERE_BLOOMFILTER 0x00400000 /* Consider using a Bloom-filter */
151729 #define WHERE_VIEWSCAN 0x02000000 /* A full-scan of a VIEW or subquery */
151739 ** Return the name of the i-th column of the pIdx index.
151742 i = pIdx->aiColumn[i];
151745 return pIdx->pTable->aCol[i].zCnName;
151760 int iTerm, /* Zero-based index of first term. */
151761 int bAnd, /* Non-zero to append " AND " */
151801 Index *pIndex = pLoop->u.btree.pIndex;
151802 u16 nEq = pLoop->u.btree.nEq;
151803 u16 nSkip = pLoop->nSkip;
151806 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
151815 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
151816 explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
151819 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
151820 explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
151826 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
151828 ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
151842 if( sqlite3ParseToplevel(pParse)->explain==2 )
151845 SrcItem *pItem = &pTabList->a[pLevel->iFrom];
151846 Vdbe *v = pParse->pVdbe; /* VM being constructed */
151847 sqlite3 *db = pParse->db; /* Database handle */
151855 pLoop = pLevel->pWLoop;
151856 flags = pLoop->wsFlags;
151860 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
151870 assert( pLoop->u.btree.pIndex!=0 );
151871 pIdx = pLoop->u.btree.pIndex;
151873 if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
151888 sqlite3_str_appendf(&str, zFmt, pIdx->zName);
151894 const Table *pTab = pItem->pTab;
151895 const char *zRowid = pTab->iPKey>=0 ? pTab->aCol[pTab->iPKey].zCnName:
151917 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
151920 if( pItem->fg.jointype & JT_LEFT ){
151921 sqlite3_str_appendf(&str, " LEFT-JOIN");
151924 if( pLoop->nOut>=10 ){
151926 sqlite3LogEstToInt(pLoop->nOut));
151934 pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
151944 ** required and this routine is a no-op.
151955 SrcItem *pItem = &pWInfo->pTabList->a[pLevel->iFrom];
151956 Vdbe *v = pParse->pVdbe; /* VM being constructed */
151957 sqlite3 *db = pParse->db; /* Database handle */
151967 pLoop = pLevel->pWLoop;
151968 if( pLoop->wsFlags & WHERE_IPK ){
151969 const Table *pTab = pItem->pTab;
151970 if( pTab->iPKey>=0 ){
151971 sqlite3_str_appendf(&str, "%s=?", pTab->aCol[pTab->iPKey].zCnName);
151976 for(i=pLoop->nSkip; i<pLoop->u.btree.nEq; i++){
151977 const char *z = explainIndexColumnName(pLoop->u.btree.pIndex, i);
151978 if( i>pLoop->nSkip ) sqlite3_str_append(&str, " AND ", 5);
151985 pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
152007 WhereLoop *pLoop = pLvl->pWLoop;
152008 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
152009 zObj = pLoop->u.btree.pIndex->zName;
152011 zObj = pSrclist->a[pLvl->iFrom].zName;
152014 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
152060 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
152065 while( (pTerm->wtFlags & TERM_CODED)==0
152066 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_OuterON))
152067 && (pLevel->notReady & pTerm->prereqAll)==0
152069 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
152070 pTerm->wtFlags |= TERM_LIKECOND;
152072 pTerm->wtFlags |= TERM_CODED;
152076 sqlite3DebugPrintf("DISABLE-");
152077 sqlite3WhereTermPrint(pTerm, (int)(pTerm - (pTerm->pWC->a)));
152080 if( pTerm->iParent<0 ) break;
152081 pTerm = &pTerm->pWC->a[pTerm->iParent];
152083 pTerm->nChild--;
152084 if( pTerm->nChild!=0 ) break;
152094 ** are no-ops) at the beginning and end of zAff are ignored. If all entries
152101 Vdbe *v = pParse->pVdbe;
152103 assert( pParse->db->mallocFailed );
152113 n--;
152117 while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){
152118 n--;
152189 sqlite3 *db = pParse->db;
152192 if( db->mallocFailed==0 ){
152201 pOrigRhs = pNew->x.pSelect->pEList;
152202 assert( pNew->pLeft!=0 );
152203 assert( ExprUseXList(pNew->pLeft) );
152204 pOrigLhs = pNew->pLeft->x.pList;
152205 for(i=iEq; i<pLoop->nLTerm; i++){
152206 if( pLoop->aLTerm[i]->pExpr==pX ){
152208 assert( (pLoop->aLTerm[i]->eOperator & (WO_OR|WO_AND))==0 );
152209 iField = pLoop->aLTerm[i]->u.x.iField - 1;
152210 if( pOrigRhs->a[iField].pExpr==0 ) continue; /* Duplicate PK column */
152211 pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
152212 pOrigRhs->a[iField].pExpr = 0;
152213 assert( pOrigLhs->a[iField].pExpr!=0 );
152214 pLhs = sqlite3ExprListAppend(pParse, pLhs, pOrigLhs->a[iField].pExpr);
152215 pOrigLhs->a[iField].pExpr = 0;
152220 pNew->pLeft->x.pList = pLhs;
152221 pNew->x.pSelect->pEList = pRhs;
152222 if( pLhs && pLhs->nExpr==1 ){
152226 Expr *p = pLhs->a[0].pExpr;
152227 pLhs->a[0].pExpr = 0;
152228 sqlite3ExprDelete(db, pNew->pLeft);
152229 pNew->pLeft = p;
152231 pSelect = pNew->x.pSelect;
152232 if( pSelect->pOrderBy ){
152234 ** iOrderByCol variables. These are set to non-zero when an
152236 ** result-set. Since the result-set of the SELECT statement may
152240 ExprList *pOrderBy = pSelect->pOrderBy;
152241 for(i=0; i<pOrderBy->nExpr; i++){
152242 pOrderBy->a[i].u.x.iOrderByCol = 0;
152269 ** straight-line code. For constraints of the form X IN (...)
152277 int bRev, /* True for reverse-order IN operations */
152280 Expr *pX = pTerm->pExpr;
152281 Vdbe *v = pParse->pVdbe;
152284 assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
152286 if( pX->op==TK_EQ || pX->op==TK_IS ){
152287 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
152288 }else if( pX->op==TK_ISNULL ){
152296 WhereLoop *pLoop = pLevel->pWLoop;
152301 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
152302 && pLoop->u.btree.pIndex!=0
152303 && pLoop->u.btree.pIndex->aSortOrder[iEq]
152309 assert( pX->op==TK_IN );
152313 if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
152318 for(i=iEq;i<pLoop->nLTerm; i++){
152319 assert( pLoop->aLTerm[i]!=0 );
152320 if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
152324 if( !ExprUseXSelect(pX) || pX->x.pSelect->pEList->nExpr==1 ){
152327 Expr *pExpr = pTerm->pExpr;
152328 if( pExpr->iTable==0 || !ExprHasProperty(pExpr, EP_Subrtn) ){
152329 sqlite3 *db = pParse->db;
152331 if( !db->mallocFailed ){
152332 aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*nEq);
152334 pExpr->iTable = iTab;
152338 int n = sqlite3ExprVectorSize(pX->pLeft);
152339 aiMap = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*MAX(nEq,n));
152353 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
152354 pLoop->wsFlags |= WHERE_IN_ABLE;
152355 if( pLevel->u.in.nIn==0 ){
152356 pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
152358 if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){
152359 pLoop->wsFlags |= WHERE_IN_EARLYOUT;
152362 i = pLevel->u.in.nIn;
152363 pLevel->u.in.nIn += nEq;
152364 pLevel->u.in.aInLoop =
152365 sqlite3WhereRealloc(pTerm->pWC->pWInfo,
152366 pLevel->u.in.aInLoop,
152367 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
152368 pIn = pLevel->u.in.aInLoop;
152372 for(i=iEq;i<pLoop->nLTerm; i++){
152373 if( pLoop->aLTerm[i]->pExpr==pX ){
152374 int iOut = iReg + i - iEq;
152376 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
152379 pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
152383 pIn->iCur = iTab;
152384 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
152386 pIn->iBase = iReg - i;
152387 pIn->nPrefix = i;
152389 pIn->nPrefix = 0;
152392 pIn->eEndLoopOp = OP_Noop;
152398 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
152399 && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 );
152401 && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0
152403 sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq);
152406 pLevel->u.in.nIn = 0;
152408 sqlite3DbFree(pParse->db, aiMap);
152419 ** work, see https://sqlite.org/forum/forumpost/eb8613976a (2021-05-04)
152421 if( (pLevel->pWLoop->wsFlags & WHERE_TRANSCONS)==0
152422 || (pTerm->eOperator & WO_EQUIV)==0
152443 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
152444 ** The only thing it does is allocate the pLevel->iMem memory cell and
152483 u16 nSkip; /* Number of left-most columns to skip */
152484 Vdbe *v = pParse->pVdbe; /* The vm under construction */
152494 pLoop = pLevel->pWLoop;
152495 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
152496 nEq = pLoop->u.btree.nEq;
152497 nSkip = pLoop->nSkip;
152498 pIdx = pLoop->u.btree.pIndex;
152503 regBase = pParse->nMem + 1;
152504 nReg = pLoop->u.btree.nEq + nExtraReg;
152505 pParse->nMem += nReg;
152507 zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
152508 assert( zAff!=0 || pParse->db->mallocFailed );
152511 int iIdxCur = pLevel->iIdxCur;
152512 sqlite3VdbeAddOp3(v, OP_Null, 0, regBase, regBase+nSkip-1);
152516 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
152518 assert( pLevel->addrSkip==0 );
152519 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
152526 testcase( pIdx->aiColumn[j]==XN_EXPR );
152536 pTerm = pLoop->aLTerm[j];
152540 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
152541 testcase( pTerm->wtFlags & TERM_VIRTUAL );
152553 pTerm = pLoop->aLTerm[j];
152554 if( pTerm->eOperator & WO_IN ){
152555 if( pTerm->pExpr->flags & EP_xIsSelect ){
152562 }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
152563 Expr *pRight = pTerm->pExpr->pRight;
152564 if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
152565 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
152568 if( pParse->nErr==0 ){
152569 assert( pParse->db->mallocFailed==0 );
152599 ** becomes a no-op.
152606 if( pTerm->wtFlags & TERM_LIKEOPT ){
152608 assert( pLevel->iLikeRepCntr>0 );
152611 assert( pOp->opcode==OP_String8
152612 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
152613 pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
152614 pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
152637 ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
152640 struct CCurHint *pHint = pWalker->u.pCCurHint;
152641 assert( pHint->pIdx!=0 );
152642 if( pExpr->op==TK_COLUMN
152643 && pExpr->iTable==pHint->iTabCur
152644 && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0
152646 pWalker->eCode = 1;
152653 ** should be included in the cursor-hint for a table that is on the rhs
152654 ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
152667 if( pExpr->op==TK_IS
152668 || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
152669 || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
152671 pWalker->eCode = 1;
152672 }else if( pExpr->op==TK_FUNCTION ){
152675 if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
152676 pWalker->eCode = 1;
152703 struct CCurHint *pHint = pWalker->u.pCCurHint;
152704 if( pExpr->op==TK_COLUMN ){
152705 if( pExpr->iTable!=pHint->iTabCur ){
152706 int reg = ++pWalker->pParse->nMem; /* Register for column value */
152707 sqlite3ExprCode(pWalker->pParse, pExpr, reg);
152708 pExpr->op = TK_REGISTER;
152709 pExpr->iTable = reg;
152710 }else if( pHint->pIdx!=0 ){
152711 pExpr->iTable = pHint->iIdxCur;
152712 pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);
152713 assert( pExpr->iColumn>=0 );
152715 }else if( pExpr->op==TK_AGG_FUNCTION ){
152717 ** be a correlated sub-query, and expression pExpr is an aggregate from
152735 WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
152737 Parse *pParse = pWInfo->pParse;
152738 sqlite3 *db = pParse->db;
152739 Vdbe *v = pParse->pVdbe;
152741 WhereLoop *pLoop = pLevel->pWLoop;
152750 iCur = pLevel->iTabCur;
152751 assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
152753 sHint.iIdxCur = pLevel->iIdxCur;
152754 sHint.pIdx = pLoop->u.btree.pIndex;
152758 pWC = &pWInfo->sWC;
152759 for(i=0; i<pWC->nBase; i++){
152760 pTerm = &pWC->a[i];
152761 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
152762 if( pTerm->prereqAll & pLevel->notReady ) continue;
152766 ** from the cursor-hint.
152786 if( pTabItem->fg.jointype & JT_LEFT ){
152787 Expr *pExpr = pTerm->pExpr;
152789 || pExpr->w.iJoin!=pTabItem->iCursor
152793 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
152797 if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) continue;
152800 /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
152803 if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
152804 for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
152805 if( j<pLoop->nLTerm ) continue;
152808 /* No subqueries or non-deterministic functions allowed */
152809 if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
152816 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
152821 pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
152832 # define codeCursorHint(A,B,C,D) /* No-op */
152836 ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
152847 ** However, if the scan currently being coded is a branch of an OR-loop and
152864 int iCur, /* Cursor for IPK b-tree */
152867 Parse *pParse = pWInfo->pParse; /* Parse context */
152868 Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
152871 assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
152873 pWInfo->bDeferredSeek = 1;
152875 if( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
152876 && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
152879 Table *pTab = pIdx->pTable;
152880 u32 *ai = (u32*)sqlite3DbMallocZero(pParse->db, sizeof(u32)*(pTab->nCol+1));
152882 ai[0] = pTab->nCol;
152883 for(i=0; i<pIdx->nColumn-1; i++){
152885 assert( pIdx->aiColumn[i]<pTab->nCol );
152886 x1 = pIdx->aiColumn[i];
152891 sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
152910 Vdbe *v = pParse->pVdbe;
152912 assert( p->op==TK_SELECT );
152914 sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
152921 pList = p->x.pList;
152922 assert( nReg<=pList->nExpr );
152924 sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
152928 assert( nReg==1 || pParse->nErr );
152947 while( pTruth->op==TK_AND ){
152948 whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC);
152949 pTruth = pTruth->pRight;
152951 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
152953 if( pTerm->wtFlags & TERM_CODED ) continue;
152954 pExpr = pTerm->pExpr;
152956 pTerm->wtFlags |= TERM_CODED;
152966 ** inner-loop Bloom filters, then evaluate those filters now, before the
152972 ** WhereLevel.regFilter set. If an inner-loop Bloom filter is checked,
152979 int iLevel, /* Which level of pWInfo->a[] should be coded */
152983 while( ++iLevel < pWInfo->nLevel ){
152984 WhereLevel *pLevel = &pWInfo->a[iLevel];
152985 WhereLoop *pLoop = pLevel->pWLoop;
152986 if( pLevel->regFilter==0 ) continue;
152987 if( pLevel->pWLoop->nSkip ) continue;
152988 /* ,--- Because sqlite3ConstructBloomFilter() has will not have set
152989 ** vvvvv--' pLevel->regFilter if this were true. */
152990 if( NEVER(pLoop->prereq & notReady) ) continue;
152991 assert( pLevel->addrBrk==0 );
152992 pLevel->addrBrk = addrNxt;
152993 if( pLoop->wsFlags & WHERE_IPK ){
152994 WhereTerm *pTerm = pLoop->aLTerm[0];
152997 assert( pTerm->pExpr!=0 );
152998 testcase( pTerm->wtFlags & TERM_VIRTUAL );
153001 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MustBeInt, regRowid, addrNxt);
153002 VdbeCoverage(pParse->pVdbe);
153003 sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
153005 VdbeCoverage(pParse->pVdbe);
153007 u16 nEq = pLoop->u.btree.nEq;
153011 assert( pLoop->wsFlags & WHERE_INDEXED );
153012 assert( (pLoop->wsFlags & WHERE_COLUMN_IN)==0 );
153015 sqlite3DbFree(pParse->db, zStartAff);
153016 sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
153018 VdbeCoverage(pParse->pVdbe);
153020 pLevel->regFilter = 0;
153021 pLevel->addrBrk = 0;
153026 ** Generate code for the start of the iLevel-th loop in the WHERE clause
153033 int iLevel, /* Which level of pWInfo->a[] should be coded */
153054 pWC = &pWInfo->sWC;
153055 db = pParse->db;
153056 pLoop = pLevel->pWLoop;
153057 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
153058 iCur = pTabItem->iCursor;
153059 pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
153060 bRev = (pWInfo->revMask>>iLevel)&1;
153061 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
153065 iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom);
153071 sqlite3TreeViewExpr(0, pWInfo->pWhere, 0);
153073 sqlite3DebugPrintf("All WHERE-clause terms before coding:\n");
153088 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
153089 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);
153095 assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
153096 || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
153098 if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
153099 pLevel->iLeftJoin = ++pParse->nMem;
153100 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
153101 VdbeComment((v, "init LEFT JOIN no-match flag"));
153106 for(j=iLevel; j>0; j--){
153107 if( pWInfo->a[j].iLeftJoin ) break;
153108 if( pWInfo->a[j].pRJ ) break;
153110 addrHalt = pWInfo->a[j].addrBrk;
153112 /* Special case of a FROM clause subquery implemented as a co-routine */
153113 if( pTabItem->fg.viaCoroutine ){
153114 int regYield = pTabItem->regReturn;
153115 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
153116 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
153118 VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
153119 pLevel->op = OP_Goto;
153123 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
153124 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
153129 int nConstraint = pLoop->nLTerm;
153132 addrNotFound = pLevel->addrBrk;
153135 pTerm = pLoop->aLTerm[j];
153137 if( pTerm->eOperator & WO_IN ){
153138 if( SMASKBIT32(j) & pLoop->u.vtab.mHandleIn ){
153139 int iTab = pParse->nTab++;
153140 int iCache = ++pParse->nMem;
153141 sqlite3CodeRhsOfIN(pParse, pTerm->pExpr, iTab);
153145 addrNotFound = pLevel->addrNxt;
153148 Expr *pRight = pTerm->pExpr->pRight;
153150 if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET
153151 && pLoop->u.vtab.bOmitOffset
153153 assert( pTerm->eOperator==WO_AUX );
153154 assert( pWInfo->pSelect!=0 );
153155 assert( pWInfo->pSelect->iOffset>0 );
153156 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWInfo->pSelect->iOffset);
153161 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
153164 pLoop->u.vtab.idxStr,
153165 pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
153167 pLoop->u.vtab.needFree = 0;
153169 ** the u.vtab.idxStr. NULL it out to prevent a use-after-free */
153170 if( db->mallocFailed ) pLoop->u.vtab.idxStr = 0;
153171 pLevel->p1 = iCur;
153172 pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
153173 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
153174 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
153177 pTerm = pLoop->aLTerm[j];
153178 if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
153182 if( (pTerm->eOperator & WO_IN)!=0
153183 && (SMASKBIT32(j) & pLoop->u.vtab.mHandleIn)==0
153184 && !db->mallocFailed
153189 int iIn; /* IN loop corresponding to the j-th constraint */
153196 for(iIn=0; ALWAYS(iIn<pLevel->u.in.nIn); iIn++){
153197 pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop);
153198 if( (pOp->opcode==OP_Column && pOp->p3==iReg+j+2)
153199 || (pOp->opcode==OP_Rowid && pOp->p2==iReg+j+2)
153201 testcase( pOp->opcode==OP_Rowid );
153202 sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
153211 if( !db->mallocFailed ){
153212 int iFld = pTerm->u.x.iField;
153213 Expr *pLeft = pTerm->pExpr->pLeft;
153216 assert( pLeft->op==TK_VECTOR );
153218 assert( iFld<=pLeft->x.pList->nExpr );
153219 pCompare->pLeft = pLeft->x.pList->a[iFld-1].pExpr;
153221 pCompare->pLeft = pLeft;
153223 pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
153225 pRight->iTable = iReg+j+2;
153227 pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL
153230 pCompare->pLeft = 0;
153238 ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
153246 if( (pLoop->wsFlags & WHERE_IPK)!=0
153247 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
153254 assert( pLoop->u.btree.nEq==1 );
153255 pTerm = pLoop->aLTerm[0];
153257 assert( pTerm->pExpr!=0 );
153258 testcase( pTerm->wtFlags & TERM_VIRTUAL );
153259 iReleaseReg = ++pParse->nMem;
153262 addrNxt = pLevel->addrNxt;
153263 if( pLevel->regFilter ){
153266 sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
153273 pLevel->op = OP_Noop;
153274 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
153275 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
153286 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
153287 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
153313 assert( (pStart->wtFlags & TERM_VNULL)==0 );
153314 testcase( pStart->wtFlags & TERM_VIRTUAL );
153315 pX = pStart->pExpr;
153317 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
153318 if( sqlite3ExprIsVector(pX->pRight) ){
153320 codeExprOrVector(pParse, pX->pRight, r1, 1);
153321 testcase( pX->op==TK_GT );
153322 testcase( pX->op==TK_GE );
153323 testcase( pX->op==TK_LT );
153324 testcase( pX->op==TK_LE );
153325 op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
153326 assert( pX->op!=TK_GT || op==OP_SeekGE );
153327 assert( pX->op!=TK_GE || op==OP_SeekGE );
153328 assert( pX->op!=TK_LT || op==OP_SeekLE );
153329 assert( pX->op!=TK_LE || op==OP_SeekLE );
153331 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
153333 op = aMoveOp[(pX->op - TK_GT)];
153337 VdbeCoverageIf(v, pX->op==TK_GT);
153338 VdbeCoverageIf(v, pX->op==TK_LE);
153339 VdbeCoverageIf(v, pX->op==TK_LT);
153340 VdbeCoverageIf(v, pX->op==TK_GE);
153349 pX = pEnd->pExpr;
153351 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
153352 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
153353 testcase( pEnd->wtFlags & TERM_VIRTUAL );
153354 memEndValue = ++pParse->nMem;
153355 codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
153356 if( 0==sqlite3ExprIsVector(pX->pRight)
153357 && (pX->op==TK_LT || pX->op==TK_GT)
153363 if( 0==sqlite3ExprIsVector(pX->pRight) ){
153368 pLevel->op = bRev ? OP_Prev : OP_Next;
153369 pLevel->p1 = iCur;
153370 pLevel->p2 = start;
153371 assert( pLevel->p5==0 );
153373 iRowidReg = ++pParse->nMem;
153382 }else if( pLoop->wsFlags & WHERE_INDEXED ){
153387 ** left-most columns of the index. It may also contain
153390 ** the right-most column can be an inequality - the rest must
153430 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
153431 u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
153432 u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
153448 int regBignull = 0; /* big-null flag register */
153451 pIdx = pLoop->u.btree.pIndex;
153452 iIdxCur = pLevel->iIdxCur;
153453 assert( nEq>=pLoop->nSkip );
153459 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
153460 pRangeStart = pLoop->aLTerm[j++];
153461 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
153463 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
153464 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
153466 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
153467 pRangeEnd = pLoop->aLTerm[j++];
153468 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
153470 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
153472 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
153473 pLevel->iLikeRepCntr = (u32)++pParse->nMem;
153474 sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
153476 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
153480 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
153482 pLevel->iLikeRepCntr <<=1;
153483 pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
153487 j = pIdx->aiColumn[nEq];
153488 if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
153493 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
153496 ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS
153499 ** it is not. For an ASC sort, the non-NULL entries are scanned first.
153502 if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0
153503 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0
153507 testcase( pLoop->nSkip>0 );
153510 pLevel->regBignull = regBignull = ++pParse->nMem;
153511 if( pLevel->iLeftJoin ){
153514 pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse);
153521 if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) ){
153527 if( iLevel>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 ){
153543 addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt);
153545 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
153546 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
153547 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
153548 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
153549 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
153550 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
153556 Expr *pRight = pRangeStart->pExpr->pRight;
153559 if( (pRangeStart->wtFlags & TERM_VNULL)==0
153569 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
153586 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
153587 if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
153588 /* The skip-scan logic inside the call to codeAllEqualityConstraints()
153594 VdbeComment((v, "NULL-scan pass ctr"));
153596 if( pLevel->regFilter ){
153597 sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
153605 if( (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 && op==OP_SeekGE ){
153616 (pIdx->aiRowLogEst[0]+9)/10);
153641 nConstraint-startEq);
153655 assert( pLevel->p2==0 );
153657 Expr *pRight = pRangeEnd->pExpr->pRight;
153659 /* For a seek-scan that has a range on the lowest term of the index,
153662 ** over that initialization, leaving the range-end value set to the
153663 ** range-start value, resulting in a wrong answer.
153664 ** See ticket 5981a8c041a3c2f3 (2021-11-02).
153666 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
153670 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
153680 assert( pParse->db->mallocFailed );
153683 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
153701 if( pLevel->p2==0 ) pLevel->p2 = sqlite3VdbeCurrentAddr(v);
153706 /* Except, skip the end-of-range check while doing the NULL-scan */
153708 VdbeComment((v, "If NULL-scan 2nd pass"));
153720 /* During a NULL-scan, check to see if we have reached the end of
153726 VdbeComment((v, "If NULL-scan 1st pass"));
153737 if( (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0 ){
153742 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
153743 && (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0;
153746 }else if( HasRowid(pIdx->pTable) ){
153749 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
153750 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
153751 for(j=0; j<pPk->nKeyCol; j++){
153752 k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
153756 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
153759 if( pLevel->iLeftJoin==0 ){
153764 ** 2019-11-02 ticket 623eff57e76d45f6: This optimization does not work
153767 if( pIdx->pPartIdxWhere ){
153768 whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
153771 testcase( pIdx->pPartIdxWhere );
153773 ** The OR-optimization doesn't work for the right hand table of
153775 assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0 );
153779 if( pLoop->wsFlags & WHERE_ONEROW ){
153780 pLevel->op = OP_Noop;
153782 pLevel->op = OP_Prev;
153784 pLevel->op = OP_Next;
153786 pLevel->p1 = iIdxCur;
153787 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
153788 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
153789 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
153791 assert( pLevel->p5==0 );
153797 if( pLoop->wsFlags & WHERE_MULTI_OR ){
153836 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
153841 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
153842 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
153844 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
153846 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
153854 Table *pTab = pTabItem->pTab;
153856 pTerm = pLoop->aLTerm[0];
153858 assert( pTerm->eOperator & WO_OR );
153859 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
153860 pOrWc = &pTerm->u.pOrInfo->wc;
153861 pLevel->op = OP_Return;
153862 pLevel->p1 = regReturn;
153868 if( pWInfo->nLevel>1 ){
153871 nNotReady = pWInfo->nLevel - iLevel - 1;
153873 sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
153875 pOrTab->nAlloc = (u8)(nNotReady + 1);
153876 pOrTab->nSrc = pOrTab->nAlloc;
153877 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
153878 origSrc = pWInfo->pTabList->a;
153880 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
153883 pOrTab = pWInfo->pTabList;
153894 ** correct response for the end-of-loop code (the OP_Return) is to
153898 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
153900 regRowset = ++pParse->nMem;
153904 regRowset = pParse->nTab++;
153905 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
153908 regRowid = ++pParse->nMem;
153918 ** the "interesting" terms of z - terms that did not originate in the
153926 ** 2022-02-04: Do not push down slices of a row-value comparison.
153928 ** the initialization of the right-hand operand of the vector comparison
153932 ** 2022-03-03: Do not push down expressions that involve subqueries.
153933 ** The subquery might get coded as a subroutine. Any table-references
153934 ** in the subquery might be resolved to index-references for the index on
153937 ** index-references will not work. tag-20220303a
153940 if( pWC->nTerm>1 ){
153942 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
153943 Expr *pExpr = pWC->a[iTerm].pExpr;
153944 if( &pWC->a[iTerm] == pTerm ) continue;
153945 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
153946 testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
153947 testcase( pWC->a[iTerm].wtFlags & TERM_SLICE );
153948 if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED|TERM_SLICE))!=0 ){
153951 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
153952 if( ExprHasProperty(pExpr, EP_Subquery) ) continue; /* tag-20220303a */
153960 ** prevents sqlite3PExpr() from applying the AND short-circuit
153968 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
153970 ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
153971 for(ii=0; ii<pOrWc->nTerm; ii++){
153972 WhereTerm *pOrTerm = &pOrWc->a[ii];
153973 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
153974 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
153975 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
153982 if( db->mallocFailed ){
153987 pAndExpr->pLeft = pOrExpr;
153992 WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
153995 assert( pSubWInfo || pParse->nErr );
153999 pParse, pOrTab, &pSubWInfo->a[0], 0
154001 sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
154003 /* This is the sub-WHERE clause body. First skip over
154004 ** duplicate rows from prior sub-WHERE clauses, and record the
154006 ** row will be skipped in subsequent sub-WHERE clauses.
154008 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
154009 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
154011 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
154017 int nPk = pPk->nKeyCol;
154024 int iCol = pPk->aiColumn[iPk];
154036 ** the temp table. And if iSet is -1, assume that there is no
154059 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
154062 /* The pSubWInfo->untestedTerms flag means that this OR term
154067 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
154069 /* If all of the OR-connected terms are optimized using the same
154075 ** uses an index, and this is either the first OR-connected term
154081 pSubLoop = pSubWInfo->a[0].pWLoop;
154082 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
154083 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
154084 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
154085 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
154087 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
154088 pCov = pSubLoop->u.btree.pIndex;
154093 pWInfo->bDeferredSeek = 1;
154104 assert( pLevel->pWLoop==pLoop );
154105 assert( (pLoop->wsFlags & WHERE_MULTI_OR)!=0 );
154106 assert( (pLoop->wsFlags & WHERE_IN_ABLE)==0 );
154107 pLevel->u.pCoveringIdx = pCov;
154108 if( pCov ) pLevel->iIdxCur = iCovCur;
154110 pAndExpr->pLeft = 0;
154114 sqlite3VdbeGoto(v, pLevel->addrBrk);
154119 ** loop. The byte-code formatter will use that P2 value as a hint to
154121 ** See tag-20220407a in vdbe.c and shell.c */
154122 assert( pLevel->op==OP_Return );
154123 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
154125 if( pWInfo->nLevel>1 ){ sqlite3DbFreeNN(db, pOrTab); }
154137 if( pTabItem->fg.isRecursive ){
154139 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
154140 pLevel->op = OP_Noop;
154143 pLevel->op = aStep[bRev];
154144 pLevel->p1 = iCur;
154145 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
154148 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
154153 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
154165 ** sub-queries.
154173 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
154176 testcase( pTerm->wtFlags & TERM_VIRTUAL );
154177 testcase( pTerm->wtFlags & TERM_CODED );
154178 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
154179 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
154180 testcase( pWInfo->untestedTerms==0
154181 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
154182 pWInfo->untestedTerms = 1;
154185 pE = pTerm->pExpr;
154187 if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ){
154190 ** join processing. tag-20220513a */
154192 }else if( (pTabItem->fg.jointype & JT_LEFT)==JT_LEFT
154196 Bitmask m = sqlite3WhereGetMask(&pWInfo->sMaskSet, pE->w.iJoin);
154197 if( m & pLevel->notReady ){
154203 if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
154207 if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
154212 if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
154221 u32 x = pLevel->iLikeRepCntr;
154232 pWC->nTerm-j, pTerm, iLoop));
154236 sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
154241 pTerm->wtFlags |= TERM_CODED;
154254 for(pTerm=pWC->a, j=pWC->nBase; j>0; j--, pTerm++){
154257 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
154258 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
154259 if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
154260 if( pTerm->leftCursor!=iCur ) continue;
154261 if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ) continue;
154262 pE = pTerm->pExpr;
154266 sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
154270 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
154271 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
154272 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
154275 if( pAlt->wtFlags & (TERM_CODED) ) continue;
154276 if( (pAlt->eOperator & WO_IN)
154277 && ExprUseXSelect(pAlt->pExpr)
154278 && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
154282 testcase( pAlt->eOperator & WO_EQ );
154283 testcase( pAlt->eOperator & WO_IS );
154284 testcase( pAlt->eOperator & WO_IN );
154286 sEAlt = *pAlt->pExpr;
154287 sEAlt.pLeft = pE->pLeft;
154289 pAlt->wtFlags |= TERM_CODED;
154295 if( pLevel->pRJ ){
154300 WhereRightJoin *pRJ = pLevel->pRJ;
154302 /* pTab is the right-hand table of the RIGHT JOIN. Generate code that
154307 pTab = pWInfo->pTabList->a[pLevel->iFrom].pTab;
154310 sqlite3ExprCodeGetColumnOfTable(v, pTab, pLevel->iTabCur, -1, r+1);
154315 nPk = pPk->nKeyCol;
154318 int iCol = pPk->aiColumn[iPk];
154322 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, 0, r+1, nPk);
154324 VdbeComment((v, "match against %s", pTab->zName));
154326 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r, r+1, nPk);
154327 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk);
154336 if( pLevel->iLeftJoin ){
154337 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
154338 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
154340 if( pLevel->pRJ==0 ){
154345 if( pLevel->pRJ ){
154348 ** be in-line with the rest of the code. But at the end, a separate
154352 WhereRightJoin *pRJ = pLevel->pRJ;
154353 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pRJ->regReturn);
154354 pRJ->addrSubrtn = sqlite3VdbeCurrentAddr(v);
154355 assert( pParse->withinRJSubrtn < 255 );
154356 pParse->withinRJSubrtn++;
154361 ** appropriate WHERE clause constraint checks. tag-20220513a.
154364 for(pTerm=pWC->a, j=0; j<pWC->nBase; j++, pTerm++){
154365 testcase( pTerm->wtFlags & TERM_VIRTUAL );
154366 testcase( pTerm->wtFlags & TERM_CODED );
154367 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
154368 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
154369 assert( pWInfo->untestedTerms );
154372 if( pTabItem->fg.jointype & JT_LTORJ ) continue;
154373 assert( pTerm->pExpr );
154374 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
154375 pTerm->wtFlags |= TERM_CODED;
154381 sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n",
154387 iLevel, (u64)pLevel->notReady);
154390 return pLevel->notReady;
154394 ** Generate the code for the loop that finds all non-matched terms
154402 Parse *pParse = pWInfo->pParse;
154403 Vdbe *v = pParse->pVdbe;
154404 WhereRightJoin *pRJ = pLevel->pRJ;
154406 WhereClause *pWC = &pWInfo->sWC;
154408 WhereLoop *pLoop = pLevel->pWLoop;
154409 SrcItem *pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
154414 ExplainQueryPlan((pParse, 1, "RIGHT-JOIN %s", pTabItem->pTab->zName));
154415 sqlite3VdbeNoJumpsOutsideSubrtn(v, pRJ->addrSubrtn, pRJ->endSubrtn,
154416 pRJ->regReturn);
154419 mAll |= pWInfo->a[k].pWLoop->maskSelf;
154420 sqlite3VdbeAddOp1(v, OP_NullRow, pWInfo->a[k].iTabCur);
154421 iIdxCur = pWInfo->a[k].iIdxCur;
154426 if( (pTabItem->fg.jointype & JT_LTORJ)==0 ){
154427 mAll |= pLoop->maskSelf;
154428 for(k=0; k<pWC->nTerm; k++){
154429 WhereTerm *pTerm = &pWC->a[k];
154430 if( (pTerm->wtFlags & (TERM_VIRTUAL|TERM_SLICE))!=0
154431 && pTerm->eOperator!=WO_ROWVAL
154435 if( pTerm->prereqAll & ~mAll ) continue;
154436 if( ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON) ) continue;
154438 sqlite3ExprDup(pParse->db, pTerm->pExpr, 0));
154445 assert( pParse->withinRJSubrtn < 100 );
154446 pParse->withinRJSubrtn++;
154450 int iCur = pLevel->iTabCur;
154451 int r = ++pParse->nMem;
154455 Table *pTab = pTabItem->pTab;
154457 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, r);
154462 nPk = pPk->nKeyCol;
154463 pParse->nMem += nPk - 1;
154465 int iCol = pPk->aiColumn[iPk];
154469 jmp = sqlite3VdbeAddOp4Int(v, OP_Filter, pRJ->regBloom, 0, r, nPk);
154471 sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, addrCont, r, nPk);
154474 sqlite3VdbeAddOp2(v, OP_Gosub, pRJ->regReturn, pRJ->addrSubrtn);
154477 sqlite3ExprDelete(pParse->db, pSubWhere);
154479 assert( pParse->withinRJSubrtn>0 );
154480 pParse->withinRJSubrtn--;
154486 ** 2015-06-08
154488 ** The author disclaims copyright to this source code. In place of
154513 sqlite3WhereClauseClear(&p->wc);
154521 sqlite3WhereClauseClear(&p->wc);
154528 ** The index in pWC->a[] of the new WhereTerm is returned on success.
154531 ** the db->mallocFailed flag so that higher-level functions can detect it.
154533 ** This routine will increase the size of the pWC->a[] array as necessary.
154542 ** the pWC->a[] array.
154548 if( pWC->nTerm>=pWC->nSlot ){
154549 WhereTerm *pOld = pWC->a;
154550 sqlite3 *db = pWC->pWInfo->pParse->db;
154551 pWC->a = sqlite3WhereMalloc(pWC->pWInfo, sizeof(pWC->a[0])*pWC->nSlot*2 );
154552 if( pWC->a==0 ){
154556 pWC->a = pOld;
154559 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
154560 pWC->nSlot = pWC->nSlot*2;
154562 pTerm = &pWC->a[idx = pWC->nTerm++];
154563 if( (wtFlags & TERM_VIRTUAL)==0 ) pWC->nBase = pWC->nTerm;
154565 pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
154567 pTerm->truthProb = 1;
154569 pTerm->pExpr = sqlite3ExprSkipCollateAndLikely(p);
154570 pTerm->wtFlags = wtFlags;
154571 pTerm->pWC = pWC;
154572 pTerm->iParent = -1;
154573 memset(&pTerm->eOperator, 0,
154574 sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
154596 if( pExpr->pLeft->op==TK_VECTOR
154597 || pExpr->pRight->op==TK_VECTOR
154598 || sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight) !=
154599 sqlite3BinaryCompareCollSeq(pParse, pExpr->pRight, pExpr->pLeft)
154601 pExpr->flags ^= EP_Commuted;
154603 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
154604 if( pExpr->op>=TK_GT ){
154609 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
154610 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
154628 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
154629 c = (u16)(WO_EQ<<(op-TK_EQ));
154667 int cnt; /* Number of non-wildcard prefix characters */
154669 sqlite3 *db = pParse->db; /* Database connection */
154681 pList = pExpr->x.pList;
154682 pLeft = pList->a[1].pExpr;
154684 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
154685 op = pRight->op;
154686 if( op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
154687 Vdbe *pReprepare = pParse->pReprepare;
154688 int iCol = pRight->iColumn;
154693 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
154694 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
154697 z = (u8*)pRight->u.zToken;
154709 ** with a wildcard and if (2) the non-wildcard prefix does not end with
154716 if( cnt!=0 && 255!=(u8)z[cnt-1] && (cnt>1 || z[0]!=wc[3]) ){
154728 zNew = pPrefix->u.zToken;
154742 ** Getting this right has been a persistent source of bugs in the
154744 ** 2018-09-10 https://sqlite.org/src/info/c94369cae9b561b1
154745 ** 2019-05-02 https://sqlite.org/src/info/b043a54c3de54b28
154746 ** 2019-06-10 https://sqlite.org/src/info/fd76310a5e843e07
154747 ** 2019-06-14 https://sqlite.org/src/info/ce8717f0885af975
154748 ** 2019-09-03 https://sqlite.org/src/info/0f0428096f17252a
154750 if( pLeft->op!=TK_COLUMN
154753 && ALWAYS(pLeft->y.pTab)
154754 && IsVirtual(pLeft->y.pTab)) /* Might be numeric */
154760 if( iTo==1 && zNew[0]=='-' ){
154763 zNew[iTo-1]++;
154765 zNew[iTo-1]--;
154780 Vdbe *v = pParse->pVdbe;
154781 sqlite3VdbeSetVarmask(v, pRight->iColumn);
154783 if( *pisComplete && pRight->u.zToken[1] ){
154792 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
154814 ** ----------------------- ---------------------------------
154842 if( pExpr->op==TK_FUNCTION ){
154857 pList = pExpr->x.pList;
154858 if( pList==0 || pList->nExpr!=2 ){
154862 /* Built-in operators MATCH, GLOB, LIKE, and REGEXP attach to a
154864 ** the left-hand side operand in their in-fix form.
154869 pCol = pList->a[1].pExpr;
154870 assert( pCol->op!=TK_COLUMN || (ExprUseYTab(pCol) && pCol->y.pTab!=0) );
154874 if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
154876 *ppRight = pList->a[0].pExpr;
154889 ** Historically, xFindFunction expected to see lower-case function
154893 pCol = pList->a[0].pExpr;
154894 assert( pCol->op!=TK_COLUMN || ExprUseYTab(pCol) );
154895 assert( pCol->op!=TK_COLUMN || (ExprUseYTab(pCol) && pCol->y.pTab!=0) );
154901 pVtab = sqlite3GetVTable(db, pCol->y.pTab)->pVtab;
154903 assert( pVtab->pModule!=0 );
154905 pMod = (sqlite3_module *)pVtab->pModule;
154906 if( pMod->xFindFunction!=0 ){
154907 i = pMod->xFindFunction(pVtab,2, pExpr->u.zToken, &xNotUsed, &pNotUsed);
154910 *ppRight = pList->a[1].pExpr;
154916 }else if( pExpr->op==TK_NE || pExpr->op==TK_ISNOT || pExpr->op==TK_NOTNULL ){
154918 Expr *pLeft = pExpr->pLeft;
154919 Expr *pRight = pExpr->pRight;
154920 assert( pLeft->op!=TK_COLUMN || (ExprUseYTab(pLeft) && pLeft->y.pTab!=0) );
154924 assert( pRight==0 || pRight->op!=TK_COLUMN
154925 || (ExprUseYTab(pRight) && pRight->y.pTab!=0) );
154932 if( pExpr->op==TK_NE ) *peOp2 = SQLITE_INDEX_CONSTRAINT_NE;
154933 if( pExpr->op==TK_ISNOT ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOT;
154934 if( pExpr->op==TK_NOTNULL ) *peOp2 = SQLITE_INDEX_CONSTRAINT_ISNOTNULL;
154947 pDerived->flags |= pBase->flags & (EP_OuterON|EP_InnerON);
154948 pDerived->w.iJoin = pBase->w.iJoin;
154956 pWC->a[iChild].iParent = iParent;
154957 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
154958 pWC->a[iParent].nChild++;
154962 ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
154967 if( pTerm->eOperator!=WO_AND ){
154970 if( N<pTerm->u.pAndInfo->wc.nTerm ){
154971 return &pTerm->u.pAndInfo->wc.a[N];
154978 ** two subterms are in disjunction - they are OR-ed together.
154988 ** x<y OR x=y --> x<=y
154989 ** x=y OR x=y --> x=y
154990 ** x<=y OR x<y --> x<=y
154994 ** x<y OR x>y --> x!=y
155002 u16 eOp = pOne->eOperator | pTwo->eOperator;
155008 if( (pOne->wtFlags | pTwo->wtFlags) & TERM_VNULL ) return;
155009 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
155010 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
155013 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
155014 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
155015 if( sqlite3ExprCompare(0,pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
155016 if( sqlite3ExprCompare(0,pOne->pExpr->pRight, pTwo->pExpr->pRight,-1) )return;
155018 if( (eOp & (eOp-1))!=0 ){
155026 db = pWC->pWInfo->pParse->db;
155027 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
155029 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
155030 pNew->op = op;
155037 ** Analyze a term that consists of two or more OR-connected
155050 ** The term being analyzed must have two or more of OR-connected subterms.
155051 ** A single subterm might be a set of AND-connected sub-subterms.
155089 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
155126 int idxTerm /* Index of the OR-term to be analyzed */
155128 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
155129 Parse *pParse = pWInfo->pParse; /* Parser context */
155130 sqlite3 *db = pParse->db; /* Database connection */
155131 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
155132 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
155135 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
155145 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
155146 assert( pExpr->op==TK_OR );
155147 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
155149 pTerm->wtFlags |= TERM_ORINFO;
155150 pOrWc = &pOrInfo->wc;
155151 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
155155 if( db->mallocFailed ) return;
155156 assert( pOrWc->nTerm>=2 );
155163 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
155164 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
155166 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
155174 pOrTerm->u.pAndInfo = pAndInfo;
155175 pOrTerm->wtFlags |= TERM_ANDINFO;
155176 pOrTerm->eOperator = WO_AND;
155177 pOrTerm->leftCursor = -1;
155178 pAndWC = &pAndInfo->wc;
155179 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
155180 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
155181 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
155183 pAndWC->pOuter = pWC;
155184 if( !db->mallocFailed ){
155185 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
155186 assert( pAndTerm->pExpr );
155187 if( allowedOp(pAndTerm->pExpr->op)
155188 || pAndTerm->eOperator==WO_AUX
155190 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
155196 }else if( pOrTerm->wtFlags & TERM_COPIED ){
155201 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
155202 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
155203 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
155204 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
155207 if( (pOrTerm->eOperator & WO_EQ)==0 ){
155219 pOrInfo->indexable = indexable;
155220 pTerm->eOperator = WO_OR;
155221 pTerm->leftCursor = -1;
155223 pWC->hasOr = 1;
155226 /* For a two-way OR, attempt to implementation case 2.
155228 if( indexable && pOrWc->nTerm==2 ){
155231 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
155234 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
155245 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
155248 ** something other than == on a column in the single table. The 1-bit
155252 ** sure the same column is used on all terms. The 2-bit case is when
155263 int iColumn = -1; /* Column index on lhs of IN operator */
155264 int iCursor = -1; /* Table cursor common to all terms */
155275 pOrTerm = pOrWc->a;
155276 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
155277 assert( pOrTerm->eOperator & WO_EQ );
155278 pOrTerm->wtFlags &= ~TERM_OK;
155279 if( pOrTerm->leftCursor==iCursor ){
155280 /* This is the 2-bit case and we are on the second iteration and
155285 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
155286 pOrTerm->leftCursor))==0 ){
155291 testcase( pOrTerm->wtFlags & TERM_COPIED );
155292 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
155293 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
155296 assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
155297 iColumn = pOrTerm->u.x.leftColumn;
155298 iCursor = pOrTerm->leftCursor;
155299 pLeft = pOrTerm->pExpr->pLeft;
155307 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
155315 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
155316 assert( pOrTerm->eOperator & WO_EQ );
155317 assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
155318 if( pOrTerm->leftCursor!=iCursor ){
155319 pOrTerm->wtFlags &= ~TERM_OK;
155320 }else if( pOrTerm->u.x.leftColumn!=iColumn || (iColumn==XN_EXPR
155321 && sqlite3ExprCompare(pParse, pOrTerm->pExpr->pLeft, pLeft, -1)
155326 /* If the right-hand side is also a column, then the affinities
155330 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
155331 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
155335 pOrTerm->wtFlags |= TERM_OK;
155351 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
155352 if( (pOrTerm->wtFlags & TERM_OK)==0 ) continue;
155353 assert( pOrTerm->eOperator & WO_EQ );
155354 assert( (pOrTerm->eOperator & (WO_OR|WO_AND))==0 );
155355 assert( pOrTerm->leftCursor==iCursor );
155356 assert( pOrTerm->u.x.leftColumn==iColumn );
155357 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
155358 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
155359 pLeft = pOrTerm->pExpr->pLeft;
155368 pNew->x.pList = pList;
155372 /* pTerm = &pWC->a[idxTerm]; // would be needed if pTerm where reused */
155400 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
155401 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
155403 aff1 = sqlite3ExprAffinity(pExpr->pLeft);
155404 aff2 = sqlite3ExprAffinity(pExpr->pRight);
155412 return sqlite3ExprCollSeqMatch(pParse, pExpr->pLeft, pExpr->pRight);
155423 SrcList *pSrc = pS->pSrc;
155424 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
155425 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
155426 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
155427 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
155428 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
155431 for(i=0; i<pSrc->nSrc; i++){
155432 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
155433 if( pSrc->a[i].fg.isUsing==0 ){
155434 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].u3.pOn);
155436 if( pSrc->a[i].fg.isTabFunc ){
155437 mask |= sqlite3WhereExprListUsage(pMaskSet, pSrc->a[i].u1.pFuncArg);
155441 pS = pS->pPrior;
155452 ** of the column that is indexed, or XN_EXPR (-2) if an expression is being
155469 iCur = pFrom->a[i].iCursor;
155470 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
155471 if( pIdx->aColExpr==0 ) continue;
155472 for(i=0; i<pIdx->nKeyCol; i++){
155473 if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
155474 assert( pIdx->bHasExpr );
155475 if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
155497 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
155499 pExpr = pExpr->x.pList->a[0].pExpr;
155503 if( pExpr->op==TK_COLUMN ){
155504 aiCurCol[0] = pExpr->iTable;
155505 aiCurCol[1] = pExpr->iColumn;
155509 if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
155537 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
155541 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
155547 int op; /* Top-level operator. pExpr->op */
155548 Parse *pParse = pWInfo->pParse; /* Parsing context */
155549 sqlite3 *db = pParse->db; /* Database connection */
155553 if( db->mallocFailed ){
155556 assert( pWC->nTerm > idxTerm );
155557 pTerm = &pWC->a[idxTerm];
155558 pMaskSet = &pWInfo->sMaskSet;
155559 pExpr = pTerm->pExpr;
155561 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
155562 pMaskSet->bVarSelect = 0;
155563 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
155564 op = pExpr->op;
155566 assert( pExpr->pRight==0 );
155569 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
155571 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
155573 prereqAll = prereqLeft | pTerm->prereqRight;
155575 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
155576 if( pExpr->pLeft==0
155578 || pExpr->x.pList!=0
155582 prereqAll = prereqLeft | pTerm->prereqRight;
155585 if( pMaskSet->bVarSelect ) pTerm->wtFlags |= TERM_VARSELECT;
155596 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->w.iJoin);
155599 extraRight = x-1; /* ON clause terms may not be used with an index
155612 if( ALWAYS(pSrc->nSrc>0) && (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
155619 pTerm->prereqAll = prereqAll;
155620 pTerm->leftCursor = -1;
155621 pTerm->iParent = -1;
155622 pTerm->eOperator = 0;
155625 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
155626 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
155627 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
155629 if( pTerm->u.x.iField>0 ){
155631 assert( pLeft->op==TK_VECTOR );
155633 pLeft = pLeft->x.pList->a[pTerm->u.x.iField-1].pExpr;
155637 pTerm->leftCursor = aiCurCol[0];
155638 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
155639 pTerm->u.x.leftColumn = aiCurCol[1];
155640 pTerm->eOperator = operatorMask(op) & opMask;
155642 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
155644 && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
155649 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
155650 assert( pTerm->u.x.iField==0 );
155651 if( pTerm->leftCursor>=0 ){
155654 if( db->mallocFailed ){
155660 pNew = &pWC->a[idxNew];
155662 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
155663 pTerm = &pWC->a[idxTerm];
155664 pTerm->wtFlags |= TERM_COPIED;
155667 pTerm->eOperator |= WO_EQUIV;
155674 pNew->wtFlags |= exprCommute(pParse, pDup);
155675 pNew->leftCursor = aiCurCol[0];
155676 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
155677 pNew->u.x.leftColumn = aiCurCol[1];
155679 pNew->prereqRight = prereqLeft | extraRight;
155680 pNew->prereqAll = prereqAll;
155681 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
155688 pExpr->op = TK_TRUEFALSE;
155689 pExpr->u.zToken = "false";
155691 pTerm->prereqAll = 0;
155692 pTerm->eOperator = 0;
155712 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
155717 pList = pExpr->x.pList;
155719 assert( pList->nExpr==2 );
155724 sqlite3ExprDup(db, pExpr->pLeft, 0),
155725 sqlite3ExprDup(db, pList->a[i].pExpr, 0));
155730 pTerm = &pWC->a[idxTerm];
155740 else if( pExpr->op==TK_OR ){
155741 assert( pWC->op==TK_AND );
155743 pTerm = &pWC->a[idxTerm];
155752 else if( pExpr->op==TK_NOTNULL ){
155753 if( pExpr->pLeft->op==TK_COLUMN
155754 && pExpr->pLeft->iColumn>=0
155758 Expr *pLeft = pExpr->pLeft;
155769 pNewTerm = &pWC->a[idxNew];
155770 pNewTerm->prereqRight = 0;
155771 pNewTerm->leftCursor = pLeft->iTable;
155772 pNewTerm->u.x.leftColumn = pLeft->iColumn;
155773 pNewTerm->eOperator = WO_GT;
155775 pTerm = &pWC->a[idxTerm];
155776 pTerm->wtFlags |= TERM_COPIED;
155777 pNewTerm->prereqAll = pTerm->prereqAll;
155793 ** for LIKE) then the lower-bound is made all uppercase and the upper-
155797 else if( pExpr->op==TK_FUNCTION
155798 && pWC->op==TK_AND
155802 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
155811 pLeft = pExpr->x.pList->a[1].pExpr;
155817 /* Convert the lower bound to upper-case and the upper bound to
155818 ** lower-case (upper-case is less than lower-case in ASCII) so that
155821 if( noCase && !pParse->db->mallocFailed ){
155824 pTerm->wtFlags |= TERM_LIKE;
155825 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
155826 pStr1->u.zToken[i] = sqlite3Toupper(c);
155827 pStr2->u.zToken[i] = sqlite3Tolower(c);
155831 if( !db->mallocFailed ){
155833 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
155842 if( c=='A'-1 ) isComplete = 0;
155864 pTerm = &pWC->a[idxTerm];
155872 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
155873 ** new terms for each component comparison - "a = ?" and "b = ?". The
155878 ** is not a sub-select.
155880 ** tag-20220128a
155882 if( (pExpr->op==TK_EQ || pExpr->op==TK_IS)
155883 && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
155884 && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
155885 && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
155886 || (pExpr->pRight->flags & EP_xIsSelect)==0)
155887 && pWC->op==TK_AND
155893 Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i, nLeft);
155894 Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i, nLeft);
155896 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
155901 pTerm = &pWC->a[idxTerm];
155902 pTerm->wtFlags |= TERM_CODED|TERM_VIRTUAL; /* Disable the original */
155903 pTerm->eOperator = WO_ROWVAL;
155906 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
155915 else if( pExpr->op==TK_IN
155916 && pTerm->u.x.iField==0
155917 && pExpr->pLeft->op==TK_VECTOR
155919 && pExpr->x.pSelect->pPrior==0
155921 && pExpr->x.pSelect->pWin==0
155923 && pWC->op==TK_AND
155926 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
155929 pWC->a[idxNew].u.x.iField = i+1;
155945 else if( pWC->op==TK_AND ){
155948 while( res-- > 0 ){
155961 pNewExpr->w.iJoin = pExpr->w.iJoin;
155965 pNewTerm = &pWC->a[idxNew];
155966 pNewTerm->prereqRight = prereqExpr;
155967 pNewTerm->leftCursor = pLeft->iTable;
155968 pNewTerm->u.x.leftColumn = pLeft->iColumn;
155969 pNewTerm->eOperator = WO_AUX;
155970 pNewTerm->eMatchOp = eOp2;
155972 pTerm = &pWC->a[idxTerm];
155973 pTerm->wtFlags |= TERM_COPIED;
155974 pNewTerm->prereqAll = pTerm->prereqAll;
155984 testcase( pTerm!=&pWC->a[idxTerm] );
155985 pTerm = &pWC->a[idxTerm];
155986 pTerm->prereqRight |= extraRight;
156013 pWC->op = op;
156016 if( pE2->op!=op ){
156019 sqlite3WhereSplit(pWC, pE2->pLeft, op);
156020 sqlite3WhereSplit(pWC, pE2->pRight, op);
156027 ** where-clause passed as the first argument. The value for the term
156042 Parse *pParse = pWC->pWInfo->pParse;
156043 sqlite3 *db = pParse->db;
156051 pVal->u.iValue = iVal;
156056 pVal->iTable = iReg;
156063 pTerm = &pWC->a[idx];
156064 pTerm->leftCursor = iCsr;
156065 pTerm->eOperator = WO_AUX;
156066 pTerm->eMatchOp = eMatchOp;
156089 assert( p!=0 && p->pLimit!=0 ); /* 1 -- checked by caller */
156090 if( p->pGroupBy==0
156091 && (p->selFlags & (SF_Distinct|SF_Aggregate))==0 /* 2 */
156092 && (p->pSrc->nSrc==1 && IsVirtual(p->pSrc->a[0].pTab)) /* 3 */
156094 ExprList *pOrderBy = p->pOrderBy;
156095 int iCsr = p->pSrc->a[0].iCursor;
156099 for(ii=0; ii<pWC->nTerm; ii++){
156100 if( pWC->a[ii].wtFlags & TERM_CODED ){
156102 ** other, subsequent terms. It can be ignored. See tag-20220128a */
156103 assert( pWC->a[ii].wtFlags & TERM_VIRTUAL );
156104 assert( pWC->a[ii].eOperator==WO_ROWVAL );
156107 if( pWC->a[ii].leftCursor!=iCsr ) return;
156112 for(ii=0; ii<pOrderBy->nExpr; ii++){
156113 Expr *pExpr = pOrderBy->a[ii].pExpr;
156114 if( pExpr->op!=TK_COLUMN ) return;
156115 if( pExpr->iTable!=iCsr ) return;
156116 if( pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) return;
156120 /* All conditions are met. Add the terms to the where-clause object. */
156121 assert( p->pLimit->op==TK_LIMIT );
156122 whereAddLimitExpr(pWC, p->iLimit, p->pLimit->pLeft,
156124 if( p->iOffset>0 ){
156125 whereAddLimitExpr(pWC, p->iOffset, p->pLimit->pRight,
156138 pWC->pWInfo = pWInfo;
156139 pWC->hasOr = 0;
156140 pWC->pOuter = 0;
156141 pWC->nTerm = 0;
156142 pWC->nBase = 0;
156143 pWC->nSlot = ArraySize(pWC->aStatic);
156144 pWC->a = pWC->aStatic;
156153 sqlite3 *db = pWC->pWInfo->pParse->db;
156154 assert( pWC->nTerm>=pWC->nBase );
156155 if( pWC->nTerm>0 ){
156156 WhereTerm *a = pWC->a;
156157 WhereTerm *aLast = &pWC->a[pWC->nTerm-1];
156160 /* Verify that every term past pWC->nBase is virtual */
156161 for(i=pWC->nBase; i<pWC->nTerm; i++){
156162 assert( (pWC->a[i].wtFlags & TERM_VIRTUAL)!=0 );
156166 assert( a->eMatchOp==0 || a->eOperator==WO_AUX );
156167 if( a->wtFlags & TERM_DYNAMIC ){
156168 sqlite3ExprDelete(db, a->pExpr);
156170 if( a->wtFlags & (TERM_ORINFO|TERM_ANDINFO) ){
156171 if( a->wtFlags & TERM_ORINFO ){
156172 assert( (a->wtFlags & TERM_ANDINFO)==0 );
156173 whereOrInfoDelete(db, a->u.pOrInfo);
156175 assert( (a->wtFlags & TERM_ANDINFO)!=0 );
156176 whereAndInfoDelete(db, a->u.pAndInfo);
156191 ** sqlite3WhereExprUsage(MaskSet, Expr) ->
156196 ** sqlite3WhereExprUsageNN(MaskSet, Expr) ->
156201 ** sqlite3WhereExprListUsage(MaskSet, ExprList) ->
156207 ** sqlite3WhereExprUsageFull(MaskSet, ExprList) ->
156214 ** "no-inline" function to avoid the stack push overhead in the
156222 mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
156223 if( p->pLeft ) mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pLeft);
156224 if( p->pRight ){
156225 mask |= sqlite3WhereExprUsageNN(pMaskSet, p->pRight);
156226 assert( p->x.pList==0 );
156228 if( ExprHasProperty(p, EP_VarSelect) ) pMaskSet->bVarSelect = 1;
156229 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
156230 }else if( p->x.pList ){
156231 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
156234 if( (p->op==TK_FUNCTION || p->op==TK_AGG_FUNCTION) && ExprUseYWin(p) ){
156235 assert( p->y.pWin!=0 );
156236 mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pPartition);
156237 mask |= sqlite3WhereExprListUsage(pMaskSet, p->y.pWin->pOrderBy);
156238 mask |= sqlite3WhereExprUsage(pMaskSet, p->y.pWin->pFilter);
156244 if( p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
156245 return sqlite3WhereGetMask(pMaskSet, p->iTable);
156247 assert( p->op!=TK_IF_NULL_ROW );
156259 for(i=0; i<pList->nExpr; i++){
156260 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
156280 for(i=pWC->nTerm-1; i>=0; i--){
156286 ** For table-valued-functions, transform the function arguments into
156302 if( pItem->fg.isTabFunc==0 ) return;
156303 pTab = pItem->pTab;
156305 pArgs = pItem->u1.pFuncArg;
156307 for(j=k=0; j<pArgs->nExpr; j++){
156310 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
156311 if( k>=pTab->nCol ){
156312 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
156313 pTab->zName, j);
156316 pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
156318 pColRef->iTable = pItem->iCursor;
156319 pColRef->iColumn = k++;
156321 pColRef->y.pTab = pTab;
156322 pItem->colUsed |= sqlite3ExprColUsed(pColRef);
156324 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
156326 if( pItem->fg.jointype & (JT_LEFT|JT_LTORJ) ){
156331 sqlite3SetJoinExpr(pTerm, pItem->iCursor, joinType);
156341 ** The author disclaims copyright to this source code. In place of
156387 return pWInfo->nRowOut;
156395 return pWInfo->eDistinct;
156407 return pWInfo->nOBSat<0 ? 0 : pWInfo->nOBSat;
156411 ** In the ORDER BY LIMIT optimization, if the inner-most loop is known
156413 ** inner-most loop did not fit within the sorter, then we can skip all
156416 ** loop - the loop immediately outside the inner-most.
156423 ** be the continuation for the second-inner-most loop. If the ORDER BY
156425 ** be the continuation for the inner-most loop.
156428 ** inner-most loop, in the sense that a correct answer will result.
156435 if( !pWInfo->bOrderedInnerLoop ){
156437 ** continuation of the inner-most loop. */
156438 return pWInfo->iContinue;
156440 pInner = &pWInfo->a[pWInfo->nLevel-1];
156441 assert( pInner->addrNxt!=0 );
156442 return pInner->pRJ ? pWInfo->iContinue : pInner->addrNxt;
156447 ** the aggregate-step call to min() or max(), check to see if any
156459 if( !pWInfo->bOrderedInnerLoop ) return;
156460 if( pWInfo->nOBSat==0 ) return;
156461 for(i=pWInfo->nLevel-1; i>=0; i--){
156462 pInner = &pWInfo->a[i];
156463 if( (pInner->pWLoop->wsFlags & WHERE_COLUMN_IN)!=0 ){
156464 sqlite3VdbeGoto(v, pInner->addrNxt);
156468 sqlite3VdbeGoto(v, pWInfo->iBreak);
156476 assert( pWInfo->iContinue!=0 );
156477 return pWInfo->iContinue;
156485 return pWInfo->iBreak;
156492 ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
156499 ** Either value may be -1, indicating that cursor is not used.
156502 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
156506 memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
156508 if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
156510 pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
156514 return pWInfo->eOnePass;
156522 return pWInfo->bDeferredSeek;
156529 pDest->n = pSrc->n;
156530 memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
156543 LogEst rRun, /* Run-cost of the new entry */
156548 for(i=pSet->n, p=pSet->a; i>0; i--, p++){
156549 if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
156552 if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
156556 if( pSet->n<N_OR_COST ){
156557 p = &pSet->a[pSet->n++];
156558 p->nOut = nOut;
156560 p = pSet->a;
156561 for(i=1; i<pSet->n; i++){
156562 if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
156564 if( p->rRun<=rRun ) return 0;
156567 p->prereq = prereq;
156568 p->rRun = rRun;
156569 if( p->nOut>nOut ) p->nOut = nOut;
156579 assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
156580 assert( pMaskSet->n>0 || pMaskSet->ix[0]<0 );
156581 assert( iCursor>=-1 );
156582 if( pMaskSet->ix[0]==iCursor ){
156585 for(i=1; i<pMaskSet->n; i++){
156586 if( pMaskSet->ix[i]==iCursor ){
156597 pBlock = sqlite3DbMallocRawNN(pWInfo->pParse->db, nByte+sizeof(*pBlock));
156599 pBlock->pNext = pWInfo->pMemToFree;
156600 pBlock->sz = nByte;
156601 pWInfo->pMemToFree = pBlock;
156610 pOldBlk--;
156611 assert( pOldBlk->sz<nByte );
156612 memcpy(pNew, pOld, pOldBlk->sz);
156622 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
156626 assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
156627 pMaskSet->ix[pMaskSet->n++] = iCursor;
156631 ** If the right-hand branch of the expression is a TK_COLUMN, then return
156632 ** a pointer to the right-hand branch. Otherwise, return NULL.
156635 p = sqlite3ExprSkipCollateAndLikely(p->pRight);
156636 if( ALWAYS(p!=0) && p->op==TK_COLUMN && !ExprHasProperty(p, EP_FixedCol) ){
156649 i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
156651 WhereClause *pWC; /* Shorthand for pScan->pWC */
156653 int k = pScan->k; /* Where to start scanning */
156655 assert( pScan->iEquiv<=pScan->nEquiv );
156656 pWC = pScan->pWC;
156658 iColumn = pScan->aiColumn[pScan->iEquiv-1];
156659 iCur = pScan->aiCur[pScan->iEquiv-1];
156663 for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
156664 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 || pTerm->leftCursor<0 );
156665 if( pTerm->leftCursor==iCur
156666 && pTerm->u.x.leftColumn==iColumn
156668 || sqlite3ExprCompareSkip(pTerm->pExpr->pLeft,
156669 pScan->pIdxExpr,iCur)==0)
156670 && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_OuterON))
156672 if( (pTerm->eOperator & WO_EQUIV)!=0
156673 && pScan->nEquiv<ArraySize(pScan->aiCur)
156674 && (pX = whereRightSubexprIsColumn(pTerm->pExpr))!=0
156677 for(j=0; j<pScan->nEquiv; j++){
156678 if( pScan->aiCur[j]==pX->iTable
156679 && pScan->aiColumn[j]==pX->iColumn ){
156683 if( j==pScan->nEquiv ){
156684 pScan->aiCur[j] = pX->iTable;
156685 pScan->aiColumn[j] = pX->iColumn;
156686 pScan->nEquiv++;
156689 if( (pTerm->eOperator & pScan->opMask)!=0 ){
156691 if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
156693 Parse *pParse = pWC->pWInfo->pParse;
156694 pX = pTerm->pExpr;
156695 if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
156698 assert(pX->pLeft);
156700 if( pColl==0 ) pColl = pParse->db->pDfltColl;
156701 if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
156705 if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
156706 && (pX = pTerm->pExpr->pRight, ALWAYS(pX!=0))
156707 && pX->op==TK_COLUMN
156708 && pX->iTable==pScan->aiCur[0]
156709 && pX->iColumn==pScan->aiColumn[0]
156711 testcase( pTerm->eOperator & WO_IS );
156714 pScan->pWC = pWC;
156715 pScan->k = k+1;
156719 sqlite3DebugPrintf("SCAN-TERM %p: nEquiv=%d",
156720 pTerm, pScan->nEquiv);
156721 for(ii=0; ii<pScan->nEquiv; ii++){
156723 pScan->aiCur[ii], pScan->aiColumn[ii]);
156732 pWC = pWC->pOuter;
156735 if( pScan->iEquiv>=pScan->nEquiv ) break;
156736 pWC = pScan->pOrigWC;
156738 pScan->iEquiv++;
156745 ** It is factored out into a separate tail-recursion subroutine so that
156746 ** the normal whereScanInit() routine, which is a high-runner, does not
156750 pScan->idxaff = sqlite3ExprAffinity(pScan->pIdxExpr);
156781 pScan->pOrigWC = pWC;
156782 pScan->pWC = pWC;
156783 pScan->pIdxExpr = 0;
156784 pScan->idxaff = 0;
156785 pScan->zCollName = 0;
156786 pScan->opMask = opMask;
156787 pScan->k = 0;
156788 pScan->aiCur[0] = iCur;
156789 pScan->nEquiv = 1;
156790 pScan->iEquiv = 1;
156793 iColumn = pIdx->aiColumn[j];
156794 if( iColumn==pIdx->pTable->iPKey ){
156797 pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
156798 pScan->zCollName = pIdx->azColl[j];
156800 pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
156801 pScan->zCollName = pIdx->azColl[j];
156802 pScan->aiColumn[0] = XN_EXPR;
156808 pScan->aiColumn[0] = iColumn;
156819 ** Search for terms matching the iColumn-th column of pIdx
156820 ** rather than the iColumn-th column of table iCur.
156824 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
156831 ** then try for the one with no dependencies on <expr> - in other words where
156834 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
156852 if( (p->prereqRight & notReady)==0 ){
156853 if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
156854 testcase( p->eOperator & WO_IS );
156865 ** This function searches pList for an entry that matches the iCol-th column
156868 ** If such an expression is found, its index in pList->a[] is returned. If
156869 ** no expression is found, -1 is returned.
156879 const char *zColl = pIdx->azColl[iCol];
156881 for(i=0; i<pList->nExpr; i++){
156882 Expr *p = sqlite3ExprSkipCollateAndLikely(pList->a[i].pExpr);
156884 && (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN)
156885 && p->iColumn==pIdx->aiColumn[iCol]
156886 && p->iTable==iBase
156888 CollSeq *pColl = sqlite3ExprNNCollSeq(pParse, pList->a[i].pExpr);
156889 if( 0==sqlite3StrICmp(pColl->zName, zColl) ){
156895 return -1;
156899 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
156904 assert( iCol>=0 && iCol<pIdx->nColumn );
156905 j = pIdx->aiColumn[iCol];
156907 return pIdx->pTable->aCol[j].notNull;
156908 }else if( j==(-1) ){
156911 assert( j==(-2) );
156918 ** Return true if the DISTINCT expression-list passed as the third argument
156922 ** DISTINCT list are collectively unique and individually non-null.
156935 /* If there is more than one table or sub-select in the FROM clause of
156938 if( pTabList->nSrc!=1 ) return 0;
156939 iBase = pTabList->a[0].iCursor;
156940 pTab = pTabList->a[0].pTab;
156943 ** true. Note: The (p->iTable==iBase) part of this test may be false if the
156944 ** current SELECT is a correlated sub-query.
156946 for(i=0; i<pDistinct->nExpr; i++){
156947 Expr *p = sqlite3ExprSkipCollateAndLikely(pDistinct->a[i].pExpr);
156949 if( p->op!=TK_COLUMN && p->op!=TK_AGG_COLUMN ) continue;
156950 if( p->iTable==iBase && p->iColumn<0 ) return 1;
156961 ** comparison and select-list expressions must match those of the index.
156966 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
156968 if( pIdx->pPartIdxWhere ) continue;
156969 for(i=0; i<pIdx->nKeyCol; i++){
156975 if( i==pIdx->nKeyCol ){
156989 return N<=10 ? 0 : sqlite3LogEst(N) - 33;
156996 ** opcodes into OP_Copy when the table is being accessed via co-routine
157009 int iAutoidxCur /* If non-zero, cursor of autoindex being generated */
157011 Vdbe *v = pParse->pVdbe;
157014 if( pParse->db->mallocFailed ) return;
157016 if( pOp->p1!=iTabCur ) continue;
157017 if( pOp->opcode==OP_Column ){
157018 pOp->opcode = OP_Copy;
157019 pOp->p1 = pOp->p2 + iRegister;
157020 pOp->p2 = pOp->p3;
157021 pOp->p3 = 0;
157022 pOp->p5 = 2; /* Cause the MEM_Subtype flag to be cleared */
157023 }else if( pOp->opcode==OP_Rowid ){
157024 pOp->opcode = OP_Sequence;
157025 pOp->p1 = iAutoidxCur;
157028 pOp->opcode = OP_Null;
157029 pOp->p3 = 0;
157040 ** are no-ops.
157046 for(i=0; i<p->nConstraint; i++){
157050 p->aConstraint[i].iColumn,
157051 p->aConstraint[i].iTermOffset,
157052 p->aConstraint[i].op,
157053 p->aConstraint[i].usable,
157056 for(i=0; i<p->nOrderBy; i++){
157059 p->aOrderBy[i].iColumn,
157060 p->aOrderBy[i].desc);
157066 for(i=0; i<p->nConstraint; i++){
157069 p->aConstraintUsage[i].argvIndex,
157070 p->aConstraintUsage[i].omit);
157072 sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
157073 sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
157074 sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
157075 sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
157076 sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
157094 ** not-NULL condition on the left table of the RIGHT JOIN.
157100 assert( (pSrc->fg.jointype&(JT_LEFT|JT_LTORJ|JT_RIGHT))!=0 ); /* By caller */
157101 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LEFT );
157102 testcase( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))==JT_LTORJ );
157103 testcase( ExprHasProperty(pTerm->pExpr, EP_OuterON) )
157104 testcase( ExprHasProperty(pTerm->pExpr, EP_InnerON) );
157105 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON|EP_InnerON)
157106 || pTerm->pExpr->w.iJoin != pSrc->iCursor
157110 if( (pSrc->fg.jointype & (JT_LEFT|JT_RIGHT))!=0
157111 && ExprHasProperty(pTerm->pExpr, EP_InnerON)
157132 if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
157133 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
157134 assert( (pSrc->fg.jointype & JT_RIGHT)==0 );
157135 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
157140 if( (pTerm->prereqRight & notReady)!=0 ) return 0;
157141 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
157142 if( pTerm->u.x.leftColumn<0 ) return 0;
157143 aff = pSrc->pTab->aCol[pTerm->u.x.leftColumn].affinity;
157144 if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
157145 testcase( pTerm->pExpr->op==TK_IS );
157166 WhereTerm *pWCEnd; /* End of pWC->a[] */
157175 int mxBitCol; /* Maximum column in pSrc->colUsed */
157190 v = pParse->pVdbe;
157197 pTable = pSrc->pTab;
157198 pWCEnd = &pWC->a[pWC->nTerm];
157199 pLoop = pLevel->pWLoop;
157201 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
157202 Expr *pExpr = pTerm->pExpr;
157206 if( (pTerm->wtFlags & TERM_VIRTUAL)==0
157210 sqlite3ExprDup(pParse->db, pExpr, 0));
157215 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
157216 iCol = pTerm->u.x.leftColumn;
157217 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
157219 testcase( iCol==BMS-1 );
157222 "automatic index on %s(%s)", pTable->zName,
157223 pTable->aCol[iCol].zCnName);
157227 if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
157230 pLoop->aLTerm[nKeyCol++] = pTerm;
157235 assert( nKeyCol>0 || pParse->db->mallocFailed );
157236 pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
157237 pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
157248 extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
157249 mxBitCol = MIN(BMS-1,pTable->nCol);
157250 testcase( pTable->nCol==BMS-1 );
157251 testcase( pTable->nCol==BMS-2 );
157255 if( pSrc->colUsed & MASKBIT(BMS-1) ){
157256 nKeyCol += pTable->nCol - BMS + 1;
157260 pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
157262 pLoop->u.btree.pIndex = pIdx;
157263 pIdx->zName = "auto-index";
157264 pIdx->pTable = pTable;
157267 for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
157271 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
157272 iCol = pTerm->u.x.leftColumn;
157273 cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
157274 testcase( iCol==BMS-1 );
157277 Expr *pX = pTerm->pExpr;
157279 pIdx->aiColumn[n] = pTerm->u.x.leftColumn;
157281 assert( pColl!=0 || pParse->nErr>0 ); /* TH3 collate01.800 */
157282 pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
157287 assert( (u32)n==pLoop->u.btree.nEq );
157293 pIdx->aiColumn[n] = i;
157294 pIdx->azColl[n] = sqlite3StrBINARY;
157298 if( pSrc->colUsed & MASKBIT(BMS-1) ){
157299 for(i=BMS-1; i<pTable->nCol; i++){
157300 pIdx->aiColumn[n] = i;
157301 pIdx->azColl[n] = sqlite3StrBINARY;
157306 pIdx->aiColumn[n] = XN_ROWID;
157307 pIdx->azColl[n] = sqlite3StrBINARY;
157310 assert( pLevel->iIdxCur>=0 );
157311 pLevel->iIdxCur = pParse->nTab++;
157312 sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
157314 VdbeComment((v, "for %s", pTable->zName));
157315 if( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) ){
157316 pLevel->regFilter = ++pParse->nMem;
157317 sqlite3VdbeAddOp2(v, OP_Blob, 10000, pLevel->regFilter);
157321 pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
157322 if( pTabItem->fg.viaCoroutine ){
157323 int regYield = pTabItem->regReturn;
157325 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
157328 VdbeComment((v, "next row of %s", pTabItem->pTab->zName));
157330 addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
157335 pLoop->wsFlags |= WHERE_PARTIALIDX;
157339 pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
157341 if( pLevel->regFilter ){
157342 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0,
157343 regBase, pLoop->u.btree.nEq);
157345 sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
157348 if( pTabItem->fg.viaCoroutine ){
157350 testcase( pParse->db->mallocFailed );
157351 assert( pLevel->iIdxCur>0 );
157352 translateColumnToCopy(pParse, addrTop, pLevel->iTabCur,
157353 pTabItem->regResult, pLevel->iIdxCur);
157355 pTabItem->fg.viaCoroutine = 0;
157357 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
157367 sqlite3ExprDelete(pParse->db, pPartial);
157384 ** and skip the subsequence B-Tree seek if the Bloom filter indicates that
157393 int iLevel, /* Index in pWInfo->a[] that is pLevel */
157402 Parse *pParse = pWInfo->pParse; /* Parsing context */
157403 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
157404 WhereLoop *pLoop = pLevel->pWLoop; /* The loop being coded */
157409 assert( pLoop->wsFlags & WHERE_BLOOMFILTER );
157418 iCur = pLevel->iTabCur;
157419 pLevel->regFilter = ++pParse->nMem;
157422 ** to zero-filled blob of at least 80K bits, but maybe more if the
157424 ** measure the size of the table at run-time using OP_Count with
157429 pItem = &pWInfo->pTabList->a[pLevel->iFrom];
157431 pTab = pItem->pTab;
157433 sz = sqlite3LogEstToInt(pTab->nRowLogEst);
157439 sqlite3VdbeAddOp2(v, OP_Blob, (int)sz, pLevel->regFilter);
157442 pWCEnd = &pWInfo->sWC.a[pWInfo->sWC.nTerm];
157443 for(pTerm=pWInfo->sWC.a; pTerm<pWCEnd; pTerm++){
157444 Expr *pExpr = pTerm->pExpr;
157445 if( (pTerm->wtFlags & TERM_VIRTUAL)==0
157448 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
157451 if( pLoop->wsFlags & WHERE_IPK ){
157454 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, 1);
157457 Index *pIdx = pLoop->u.btree.pIndex;
157458 int n = pLoop->u.btree.nEq;
157462 int iCol = pIdx->aiColumn[jj];
157463 assert( pIdx->pTable==pItem->pTab );
157464 sqlite3ExprCodeGetColumnOfTable(v, pIdx->pTable, iCur, iCol,r1+jj);
157466 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pLevel->regFilter, 0, r1, n);
157470 sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1);
157473 pLoop->wsFlags &= ~WHERE_BLOOMFILTER;
157474 if( OptimizationDisabled(pParse->db, SQLITE_BloomPulldown) ) break;
157475 while( ++iLevel < pWInfo->nLevel ){
157477 pLevel = &pWInfo->a[iLevel];
157478 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
157479 if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ) ) continue;
157480 pLoop = pLevel->pWLoop;
157482 if( pLoop->prereq & notReady ) continue;
157483 if( (pLoop->wsFlags & (WHERE_BLOOMFILTER|WHERE_COLUMN_IN))
157486 /* This is a candidate for bloom-filter pull-down (early evaluation).
157493 }while( iLevel < pWInfo->nLevel );
157513 Parse *pParse = pWInfo->pParse;
157524 ExprList *pOrderBy = pWInfo->pOrderBy;
157527 pTab = pSrc->pTab;
157535 for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
157536 pTerm->wtFlags &= ~TERM_OK;
157537 if( pTerm->leftCursor != pSrc->iCursor ) continue;
157538 if( pTerm->prereqRight & mUnusable ) continue;
157539 assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
157540 testcase( pTerm->eOperator & WO_IN );
157541 testcase( pTerm->eOperator & WO_ISNULL );
157542 testcase( pTerm->eOperator & WO_IS );
157543 testcase( pTerm->eOperator & WO_ALL );
157544 if( (pTerm->eOperator & ~(WO_EQUIV))==0 ) continue;
157545 if( pTerm->wtFlags & TERM_VNULL ) continue;
157547 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
157548 assert( pTerm->u.x.leftColumn>=XN_ROWID );
157549 assert( pTerm->u.x.leftColumn<pTab->nCol );
157550 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
157556 pTerm->wtFlags |= TERM_OK;
157565 int n = pOrderBy->nExpr;
157567 Expr *pExpr = pOrderBy->a[i].pExpr;
157576 if( pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL ) break;
157578 /* First case - a direct column references without a COLLATE operator */
157579 if( pExpr->op==TK_COLUMN && pExpr->iTable==pSrc->iCursor ){
157580 assert( pExpr->iColumn>=XN_ROWID && pExpr->iColumn<pTab->nCol );
157584 /* 2nd case - a column reference with a COLLATE operator. Only match
157586 if( pExpr->op==TK_COLLATE
157587 && (pE2 = pExpr->pLeft)->op==TK_COLUMN
157588 && pE2->iTable==pSrc->iCursor
157592 assert( pExpr->u.zToken!=0 );
157593 assert( pE2->iColumn>=XN_ROWID && pE2->iColumn<pTab->nCol );
157594 pExpr->iColumn = pE2->iColumn;
157595 if( pE2->iColumn<0 ) continue; /* Collseq does not matter for rowid */
157596 zColl = sqlite3ColumnColl(&pTab->aCol[pE2->iColumn]);
157598 if( sqlite3_stricmp(pExpr->u.zToken, zColl)==0 ) continue;
157606 if( (pWInfo->wctrlFlags & WHERE_DISTINCTBY) ){
157607 eDistinct = 2 + ((pWInfo->wctrlFlags & WHERE_SORTBYGROUP)!=0);
157608 }else if( pWInfo->wctrlFlags & WHERE_GROUPBY ){
157616 pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
157625 pIdxCons = (struct sqlite3_index_constraint*)&pHidden->aRhs[nTerm];
157628 pIdxInfo->aConstraint = pIdxCons;
157629 pIdxInfo->aOrderBy = pIdxOrderBy;
157630 pIdxInfo->aConstraintUsage = pUsage;
157631 pHidden->pWC = pWC;
157632 pHidden->pParse = pParse;
157633 pHidden->eDistinct = eDistinct;
157634 pHidden->mIn = 0;
157635 for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
157637 if( (pTerm->wtFlags & TERM_OK)==0 ) continue;
157638 pIdxCons[j].iColumn = pTerm->u.x.leftColumn;
157640 op = pTerm->eOperator & WO_ALL;
157642 if( (pTerm->wtFlags & TERM_SLICE)==0 ){
157643 pHidden->mIn |= SMASKBIT32(j);
157648 pIdxCons[j].op = pTerm->eMatchOp;
157665 assert( pTerm->eOperator&(WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_AUX) );
157668 && sqlite3ExprIsVector(pTerm->pExpr->pRight)
157680 pIdxInfo->nConstraint = j;
157682 Expr *pExpr = pOrderBy->a[i].pExpr;
157684 assert( pExpr->op==TK_COLUMN
157685 || (pExpr->op==TK_COLLATE && pExpr->pLeft->op==TK_COLUMN
157686 && pExpr->iColumn==pExpr->pLeft->iColumn) );
157687 pIdxOrderBy[j].iColumn = pExpr->iColumn;
157688 pIdxOrderBy[j].desc = pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC;
157691 pIdxInfo->nOrderBy = j;
157706 assert( pHidden->pParse!=0 );
157707 assert( pHidden->pParse->db==db );
157708 for(i=0; i<pIdxInfo->nConstraint; i++){
157709 sqlite3ValueFree(pHidden->aRhs[i]); /* IMP: R-14553-25174 */
157710 pHidden->aRhs[i] = 0;
157728 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
157732 sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
157736 pParse->db->nSchemaLock++;
157737 rc = pVtab->pModule->xBestIndex(pVtab, p);
157738 pParse->db->nSchemaLock--;
157743 sqlite3OomFault(pParse->db);
157744 }else if( !pVtab->zErrMsg ){
157747 sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
157750 sqlite3_free(pVtab->zErrMsg);
157751 pVtab->zErrMsg = 0;
157766 ** into the aSample[] array - it is an index into a virtual set of samples
157777 IndexSample *aSample = pIdx->aSample;
157791 assert( pIdx->nSample>0 );
157792 assert( pRec->nField>0 );
157838 nField = MIN(pRec->nField, pIdx->nSample);
157840 iSample = pIdx->nSample * nField;
157852 if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
157858 pRec->nField = n;
157861 iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
157864 iLower = aSample[iSamp].anLt[n-1];
157866 res = -1;
157869 iCol = n-1;
157878 if( pParse->db->mallocFailed==0 ){
157881 assert( i<pIdx->nSample );
157882 assert( iCol==nField-1 );
157883 pRec->nField = nField;
157885 || pParse->db->mallocFailed
157888 /* Unless i==pIdx->nSample, indicating that pRec is larger than
157891 assert( i<=pIdx->nSample && i>=0 );
157892 pRec->nField = iCol+1;
157893 assert( i==pIdx->nSample
157895 || pParse->db->mallocFailed );
157900 ** If (i>0), then pRec must also be greater than sample (i-1). */
157902 pRec->nField = iCol;
157904 || pParse->db->mallocFailed );
157907 pRec->nField = nField;
157908 assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
157909 || pParse->db->mallocFailed );
157917 assert( iCol==nField-1 );
157922 ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
157925 if( i>=pIdx->nSample ){
157926 iUpper = pIdx->nRowEst0;
157934 iGap = iUpper - iLower;
157942 aStat[1] = pIdx->aAvgEq[nField-1];
157945 /* Restore the pRec->nField value before returning. */
157946 pRec->nField = nField;
157965 if( pTerm->truthProb<=0 ){
157966 nRet += pTerm->truthProb;
157967 }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
157968 nRet -= 20; assert( 20==sqlite3LogEst(4) );
157980 assert( iCol>=0 && iCol<pIdx->nColumn );
157981 if( !pIdx->zColAff ){
157984 assert( pIdx->zColAff[iCol]!=0 );
157985 return pIdx->zColAff[iCol];
157993 ** range-scan on a skip-scan index. For example:
157998 ** Value pLoop->nOut is currently set to the estimated number of rows
158009 ** N is the total number of samples, the pLoop->nOut value is adjusted
158012 ** nOut = nOut * ( min(U - L, 1) / N )
158033 Index *p = pLoop->u.btree.pIndex;
158034 int nEq = pLoop->u.btree.nEq;
158035 sqlite3 *db = pParse->db;
158036 int nLower = -1;
158037 int nUpper = p->nSample+1;
158046 pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
158048 rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
158052 rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
158053 nUpper = p2 ? 0 : p->nSample;
158059 for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
158060 rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
158070 nDiff = (nUpper - nLower);
158079 int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
158080 pLoop->nOut -= nAdjust;
158082 WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
158083 nLower, nUpper, nAdjust*-1, pLoop->nOut));
158113 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
158121 ** left-most column of the index). Or, if the query is:
158146 int nOut = pLoop->nOut;
158150 Index *p = pLoop->u.btree.pIndex;
158151 int nEq = pLoop->u.btree.nEq;
158153 if( p->nSample>0 && ALWAYS(nEq<p->nSampleCol)
158154 && OptimizationEnabled(pParse->db, SQLITE_Stat4)
158156 if( nEq==pBuilder->nRecValid ){
158157 UnpackedRecord *pRec = pBuilder->pRec;
158159 int nBtm = pLoop->u.btree.nBtm;
158160 int nTop = pLoop->u.btree.nTop;
158165 ** key-prefix formed by the nEq values matched against the nEq left-most
158179 ** The number of rows between the two bounds is then just iUpper-iLower.
158183 int iLwrIdx = -2; /* aSample[] for the lower bound */
158184 int iUprIdx = -1; /* aSample[] for the upper bound */
158187 testcase( pRec->nField!=pBuilder->nRecValid );
158188 pRec->nField = pBuilder->nRecValid;
158193 iUpper = p->nRowEst0;
158195 /* Note: this call could be optimized away - since the same values must
158202 assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
158203 assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
158204 assert( p->aSortOrder!=0 );
158205 if( p->aSortOrder[nEq] ){
158214 Expr *pExpr = pLower->pExpr->pRight;
158221 iNew = a[0] + ((pLower->eOperator & mask) ? a[1] : 0);
158223 nOut--;
158231 Expr *pExpr = pUpper->pExpr->pRight;
158238 iNew = a[0] + ((pUpper->eOperator & mask) ? a[1] : 0);
158240 nOut--;
158245 pBuilder->pRec = pRec;
158248 nNew = sqlite3LogEst(iUpper - iLower);
158253 if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
158274 assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
158279 ** has an application-defined likelihood(), assume the range is
158280 ** reduced by an additional 75%. This means that, by default, an open-ended
158284 if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
158285 nNew -= 20;
158288 nOut -= (pLower!=0) + (pUpper!=0);
158292 if( pLoop->nOut>nOut ){
158294 pLoop->nOut, nOut));
158297 pLoop->nOut = (LogEst)nOut;
158305 ** the histogram data. This only works when x is the left-most
158312 ** non-zero.
158325 Index *p = pBuilder->pNew->u.btree.pIndex;
158326 int nEq = pBuilder->pNew->u.btree.nEq;
158327 UnpackedRecord *pRec = pBuilder->pRec;
158333 assert( nEq<=p->nColumn );
158334 assert( p->aSample!=0 );
158335 assert( p->nSample>0 );
158336 assert( pBuilder->nRecValid<nEq );
158340 if( pBuilder->nRecValid<(nEq-1) ){
158346 if( nEq>=p->nColumn ){
158351 rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, 1, nEq-1, &bOk);
158352 pBuilder->pRec = pRec;
158355 pBuilder->nRecValid = nEq;
158359 p->zName, nEq-1, (int)a[1]));
158369 ** an IN constraint where the right-hand side of the IN operator
158376 ** non-zero.
158389 Index *p = pBuilder->pNew->u.btree.pIndex;
158390 i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
158391 int nRecValid = pBuilder->nRecValid;
158397 assert( p->aSample!=0 );
158398 for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
158400 rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
158402 pBuilder->nRecValid = nRecValid;
158410 assert( pBuilder->nRecValid==nRecValid );
158422 sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
158427 if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
158428 if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
158429 if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) zType[2] = 'L';
158430 if( pTerm->wtFlags & TERM_CODED ) zType[3] = 'C';
158431 if( pTerm->eOperator & WO_SINGLE ){
158432 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
158434 pTerm->leftCursor, pTerm->u.x.leftColumn);
158435 }else if( (pTerm->eOperator & WO_OR)!=0 && pTerm->u.pOrInfo!=0 ){
158437 pTerm->u.pOrInfo->indexable);
158439 sqlite3_snprintf(sizeof(zLeft),zLeft,"left=%d", pTerm->leftCursor);
158442 "TERM-%-3d %p %s %-12s op=%03x wtFlags=%04x",
158443 iTerm, pTerm, zType, zLeft, pTerm->eOperator, pTerm->wtFlags);
158447 sqlite3DebugPrintf(" prob=%-3d prereq=%llx,%llx",
158448 pTerm->truthProb, (u64)pTerm->prereqAll, (u64)pTerm->prereqRight);
158450 if( (pTerm->eOperator & (WO_OR|WO_AND))==0 && pTerm->u.x.iField ){
158451 sqlite3DebugPrintf(" iField=%d", pTerm->u.x.iField);
158453 if( pTerm->iParent>=0 ){
158454 sqlite3DebugPrintf(" iParent=%d", pTerm->iParent);
158457 sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
158468 for(i=0; i<pWC->nTerm; i++){
158469 sqlite3WhereTermPrint(&pWC->a[i], i);
158479 WhereInfo *pWInfo = pWC->pWInfo;
158480 int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
158481 SrcItem *pItem = pWInfo->pTabList->a + p->iTab;
158482 Table *pTab = pItem->pTab;
158483 Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
158484 sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
158485 p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
158487 pItem->zAlias ? pItem->zAlias : pTab->zName);
158488 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
158490 if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
158492 int i = sqlite3Strlen30(zName) - 1;
158493 while( zName[i]!='_' ) i--;
158496 sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
158502 if( p->u.vtab.idxStr ){
158504 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
158506 z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
158508 sqlite3DebugPrintf(" %-19s", z);
158511 if( p->wsFlags & WHERE_SKIPSCAN ){
158512 sqlite3DebugPrintf(" f %06x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
158514 sqlite3DebugPrintf(" f %06x N %d", p->wsFlags, p->nLTerm);
158516 sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
158517 if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
158519 for(i=0; i<p->nLTerm; i++){
158520 sqlite3WhereTermPrint(p->aLTerm[i], i);
158531 p->aLTerm = p->aLTermSpace;
158532 p->nLTerm = 0;
158533 p->nLSlot = ArraySize(p->aLTermSpace);
158534 p->wsFlags = 0;
158541 if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
158542 if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
158543 sqlite3_free(p->u.vtab.idxStr);
158544 p->u.vtab.needFree = 0;
158545 p->u.vtab.idxStr = 0;
158546 }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
158547 sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
158548 sqlite3DbFreeNN(db, p->u.btree.pIndex);
158549 p->u.btree.pIndex = 0;
158559 if( p->aLTerm!=p->aLTermSpace ){
158560 sqlite3DbFreeNN(db, p->aLTerm);
158561 p->aLTerm = p->aLTermSpace;
158562 p->nLSlot = ArraySize(p->aLTermSpace);
158565 p->nLTerm = 0;
158566 p->wsFlags = 0;
158570 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
158574 if( p->nLSlot>=n ) return SQLITE_OK;
158576 paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
158578 memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
158579 if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFreeNN(db, p->aLTerm);
158580 p->aLTerm = paNew;
158581 p->nLSlot = n;
158590 if( pFrom->nLTerm > pTo->nLSlot
158591 && whereLoopResize(db, pTo, pFrom->nLTerm)
158597 memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
158598 if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
158599 pFrom->u.vtab.needFree = 0;
158600 }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
158601 pFrom->u.btree.pIndex = 0;
158621 sqlite3WhereClauseClear(&pWInfo->sWC);
158622 while( pWInfo->pLoops ){
158623 WhereLoop *p = pWInfo->pLoops;
158624 pWInfo->pLoops = p->pNextLoop;
158627 while( pWInfo->pMemToFree ){
158628 WhereMemBlock *pNext = pWInfo->pMemToFree->pNext;
158629 sqlite3DbNNFreeNN(db, pWInfo->pMemToFree);
158630 pWInfo->pMemToFree = pNext;
158649 ** was added because if X uses skip-scan less than Y it still might
158652 ** than a non-covering index even if it is a proper subset.
158659 if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
158662 if( pX->rRun>pY->rRun && pX->nOut>pY->nOut ) return 0;
158663 if( pY->nSkip > pX->nSkip ) return 0;
158664 for(i=pX->nLTerm-1; i>=0; i--){
158665 if( pX->aLTerm[i]==0 ) continue;
158666 for(j=pY->nLTerm-1; j>=0; j--){
158667 if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
158671 if( (pX->wsFlags&WHERE_IDX_ONLY)!=0
158672 && (pY->wsFlags&WHERE_IDX_ONLY)==0 ){
158693 if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
158694 for(; p; p=p->pNextLoop){
158695 if( p->iTab!=pTemplate->iTab ) continue;
158696 if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
158701 pTemplate->rRun, pTemplate->nOut,
158702 MIN(p->rRun, pTemplate->rRun),
158703 MIN(p->nOut - 1, pTemplate->nOut)));
158704 pTemplate->rRun = MIN(p->rRun, pTemplate->rRun);
158705 pTemplate->nOut = MIN(p->nOut - 1, pTemplate->nOut);
158710 pTemplate->rRun, pTemplate->nOut,
158711 MAX(p->rRun, pTemplate->rRun),
158712 MAX(p->nOut + 1, pTemplate->nOut)));
158713 pTemplate->rRun = MAX(p->rRun, pTemplate->rRun);
158714 pTemplate->nOut = MAX(p->nOut + 1, pTemplate->nOut);
158738 for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
158739 if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
158748 assert( p->rSetup==0 || pTemplate->rSetup==0
158749 || p->rSetup==pTemplate->rSetup );
158753 ** rSetup. Call this SETUP-INVARIANT */
158754 assert( p->rSetup>=pTemplate->rSetup );
158756 /* Any loop using an appliation-defined index (or PRIMARY KEY or
158758 ** than an automatic index. Unless it is a skip-scan. */
158759 if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
158760 && (pTemplate->nSkip)==0
158761 && (pTemplate->wsFlags & WHERE_INDEXED)!=0
158762 && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
158763 && (p->prereq & pTemplate->prereq)==pTemplate->prereq
158773 if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
158774 && p->rSetup<=pTemplate->rSetup /* (2a) */
158775 && p->rRun<=pTemplate->rRun /* (2b) */
158776 && p->nOut<=pTemplate->nOut /* (2c) */
158786 if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
158787 && p->rRun>=pTemplate->rRun /* (2a) */
158788 && p->nOut>=pTemplate->nOut /* (2b) */
158790 assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
158806 ** If pBuilder->pOrSet is not NULL then we care about only the
158808 ** information is gathered in the pBuilder->pOrSet object. This special
158811 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
158823 WhereInfo *pWInfo = pBuilder->pWInfo;
158824 sqlite3 *db = pWInfo->pParse->db;
158828 if( pBuilder->iPlanLimit==0 ){
158830 if( pBuilder->pOrSet ) pBuilder->pOrSet->n = 0;
158833 pBuilder->iPlanLimit--;
158835 whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
158837 /* If pBuilder->pOrSet is defined, then only keep track of the costs
158840 if( pBuilder->pOrSet!=0 ){
158841 if( pTemplate->nLTerm ){
158843 u16 n = pBuilder->pOrSet->n;
158846 whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
158847 pTemplate->nOut);
158850 sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
158851 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
158860 ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
158868 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
158884 sqlite3WhereLoopPrint(p, pBuilder->pWC);
158889 sqlite3WhereLoopPrint(pTemplate, pBuilder->pWC);
158897 p->pNextLoop = 0;
158902 WhereLoop **ppTail = &p->pNextLoop;
158909 *ppTail = pToDel->pNextLoop;
158913 sqlite3WhereLoopPrint(pToDel, pBuilder->pWC);
158920 if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
158921 Index *pIndex = p->u.btree.pIndex;
158922 if( pIndex && pIndex->idxType==SQLITE_IDXTYPE_IPK ){
158923 p->u.btree.pIndex = 0;
158942 ** TODO --> Perhaps this is something that could be improved by better
158946 ** value corresponds to -1 in LogEst notation, so this means decrement
158953 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
158954 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
158964 Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
158966 LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
158968 assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
158969 for(i=pWC->nBase, pTerm=pWC->a; i>0; i--, pTerm++){
158971 if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
158972 if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
158973 if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) continue;
158974 for(j=pLoop->nLTerm-1; j>=0; j--){
158975 pX = pLoop->aLTerm[j];
158978 if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
158981 if( pLoop->maskSelf==pTerm->prereqAll ){
158985 ** "self-culling".
158987 ** 2022-03-24: Self-culling only applies if either the extra terms
158988 ** are straight comparison operators that are non-true with NULL
158991 if( (pTerm->eOperator & 0x3f)!=0
158992 || (pWC->pWInfo->pTabList->a[pLoop->iTab].fg.jointype
158995 pLoop->wsFlags |= WHERE_SELFCULL;
158998 if( pTerm->truthProb<=0 ){
159001 pLoop->nOut += pTerm->truthProb;
159005 pLoop->nOut--;
159006 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0
159007 && (pTerm->wtFlags & TERM_HIGHTRUTH)==0 /* tag-20200224-1 */
159009 Expr *pRight = pTerm->pExpr->pRight;
159011 testcase( pTerm->pExpr->op==TK_IS );
159012 if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
159018 pTerm->wtFlags |= TERM_HEURTRUTH;
159025 if( pLoop->nOut > nRow-iReduce ){
159026 pLoop->nOut = nRow - iReduce;
159054 int nCmp = sqlite3ExprVectorSize(pTerm->pExpr->pLeft);
159057 nCmp = MIN(nCmp, (pIdx->nColumn - nEq));
159066 assert( ExprUseXList(pTerm->pExpr->pLeft) );
159067 pLhs = pTerm->pExpr->pLeft->x.pList->a[i].pExpr;
159068 pRhs = pTerm->pExpr->pRight;
159070 pRhs = pRhs->x.pSelect->pEList->a[i].pExpr;
159072 pRhs = pRhs->x.pList->a[i].pExpr;
159076 ** the right column of the right source table. And that the sort
159079 if( pLhs->op!=TK_COLUMN
159080 || pLhs->iTable!=iCur
159081 || pLhs->iColumn!=pIdx->aiColumn[i+nEq]
159082 || pIdx->aSortOrder[i+nEq]!=pIdx->aSortOrder[nEq]
159087 testcase( pLhs->iColumn==XN_ROWID );
159089 idxaff = sqlite3TableColumnAffinity(pIdx->pTable, pLhs->iColumn);
159094 if( sqlite3StrICmp(pColl->zName, pIdx->azColl[i+nEq]) ) break;
159101 ** compiled with -DSQLITE_ENABLE_COSTMULT
159110 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
159113 ** When this function is called, pBuilder->pNew->nOut contains the
159118 ** If pProbe->idxType==SQLITE_IDXTYPE_IPK, that means pIndex is
159127 WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
159128 Parse *pParse = pWInfo->pParse; /* Parsing context */
159129 sqlite3 *db = pParse->db; /* Database connection malloc context */
159134 Bitmask saved_prereq; /* Original value of pNew->prereq */
159135 u16 saved_nLTerm; /* Original value of pNew->nLTerm */
159136 u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
159137 u16 saved_nBtm; /* Original value of pNew->u.btree.nBtm */
159138 u16 saved_nTop; /* Original value of pNew->u.btree.nTop */
159139 u16 saved_nSkip; /* Original value of pNew->nSkip */
159140 u32 saved_wsFlags; /* Original value of pNew->wsFlags */
159141 LogEst saved_nOut; /* Original value of pNew->nOut */
159147 pNew = pBuilder->pNew;
159148 if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
159150 pProbe->pTable->zName,pProbe->zName,
159151 pNew->u.btree.nEq, pNew->nSkip, pNew->rRun));
159153 assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
159154 assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
159155 if( pNew->wsFlags & WHERE_BTM_LIMIT ){
159158 assert( pNew->u.btree.nBtm==0 );
159161 if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
159163 assert( pNew->u.btree.nEq<pProbe->nColumn );
159164 assert( pNew->u.btree.nEq<pProbe->nKeyCol
159165 || pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY );
159167 saved_nEq = pNew->u.btree.nEq;
159168 saved_nBtm = pNew->u.btree.nBtm;
159169 saved_nTop = pNew->u.btree.nTop;
159170 saved_nSkip = pNew->nSkip;
159171 saved_nLTerm = pNew->nLTerm;
159172 saved_wsFlags = pNew->wsFlags;
159173 saved_prereq = pNew->prereq;
159174 saved_nOut = pNew->nOut;
159175 pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
159177 pNew->rSetup = 0;
159178 rSize = pProbe->aiRowLogEst[0];
159181 u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
159186 int nRecValid = pBuilder->nRecValid;
159188 if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
159193 if( pTerm->prereqRight & pNew->maskSelf ) continue;
159196 ** to mix with a lower range bound from some other source */
159197 if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
159199 if( (pSrc->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0
159204 if( IsUniqueIndex(pProbe) && saved_nEq==pProbe->nKeyCol-1 ){
159205 pBuilder->bldFlags1 |= SQLITE_BLDF1_UNIQUE;
159207 pBuilder->bldFlags1 |= SQLITE_BLDF1_INDEXED;
159209 pNew->wsFlags = saved_wsFlags;
159210 pNew->u.btree.nEq = saved_nEq;
159211 pNew->u.btree.nBtm = saved_nBtm;
159212 pNew->u.btree.nTop = saved_nTop;
159213 pNew->nLTerm = saved_nLTerm;
159214 if( pNew->nLTerm>=pNew->nLSlot
159215 && whereLoopResize(db, pNew, pNew->nLTerm+1)
159217 break; /* OOM while trying to enlarge the pNew->aLTerm array */
159219 pNew->aLTerm[pNew->nLTerm++] = pTerm;
159220 pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
159223 || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
159224 || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
159225 || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
159229 Expr *pExpr = pTerm->pExpr;
159240 for(i=0; i<pNew->nLTerm-1; i++){
159241 if( pNew->aLTerm[i] && pNew->aLTerm[i]->pExpr==pExpr ) nIn = 0;
159243 }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
159245 nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
159247 if( pProbe->hasStat1 && rLogSize>=10 ){
159254 ** the left-most index column, M==N.
159264 ** with the index, as using an index has better worst-case behavior.
159269 M = pProbe->aiRowLogEst[saved_nEq];
159271 /* TUNING v----- 10 to bias toward indexed IN */
159272 x = M + logK + 10 - (nIn + rLogSize);
159281 " nInMul=%d) prefers skip-scan\n",
159283 pNew->wsFlags |= WHERE_IN_SEEKSCAN;
159292 pNew->wsFlags |= WHERE_COLUMN_IN;
159294 int iCol = pProbe->aiColumn[saved_nEq];
159295 pNew->wsFlags |= WHERE_COLUMN_EQ;
159296 assert( saved_nEq==pNew->u.btree.nEq );
159298 || (iCol>=0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
159300 if( iCol==XN_ROWID || pProbe->uniqNotNull
159301 || (pProbe->nKeyCol==1 && pProbe->onError && eOp==WO_EQ)
159303 pNew->wsFlags |= WHERE_ONEROW;
159305 pNew->wsFlags |= WHERE_UNQ_WANTED;
159308 if( scan.iEquiv>1 ) pNew->wsFlags |= WHERE_TRANSCONS;
159310 pNew->wsFlags |= WHERE_COLUMN_NULL;
159313 pParse, pSrc->iCursor, pProbe, saved_nEq, pTerm
159318 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
159319 pNew->u.btree.nBtm = nVecLen;
159322 if( pTerm->wtFlags & TERM_LIKEOPT ){
159326 assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
159327 assert( pTop->wtFlags & TERM_LIKEOPT );
159328 assert( pTop->eOperator==WO_LT );
159329 if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
159330 pNew->aLTerm[pNew->nLTerm++] = pTop;
159331 pNew->wsFlags |= WHERE_TOP_LIMIT;
159332 pNew->u.btree.nTop = 1;
159338 pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
159339 pNew->u.btree.nTop = nVecLen;
159341 pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
159342 pNew->aLTerm[pNew->nLTerm-2] : 0;
159346 /* At this point pNew->nOut is set to the number of rows expected to
159350 ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
159351 assert( pNew->nOut==saved_nOut );
159352 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
159357 int nEq = ++pNew->u.btree.nEq;
159360 assert( pNew->nOut==saved_nOut );
159361 if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
159364 pNew->nOut += pTerm->truthProb;
159365 pNew->nOut -= nIn;
159370 && pProbe->nSample
159371 && ALWAYS(pNew->u.btree.nEq<=pProbe->nSampleCol)
159372 && ((eOp & WO_IN)==0 || ExprUseXList(pTerm->pExpr))
159375 Expr *pExpr = pTerm->pExpr;
159380 rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
159382 rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
159387 pNew->nOut = sqlite3LogEst(nOut);
159391 ** See tag-202002240-1 */
159392 && pNew->nOut+10 > pProbe->aiRowLogEst[0]
159401 pTerm->wtFlags |= TERM_HIGHTRUTH;
159402 if( pTerm->wtFlags & TERM_HEURTRUTH ){
159406 pBuilder->bldFlags2 |= SQLITE_BLDF2_2NDPASS;
159409 if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
159410 pNew->nOut -= nIn;
159416 pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
159421 pNew->nOut += 10;
159428 ** it to pNew->rRun, which is currently set to the cost of the index
159429 ** seek only. Then, if this is a non-covering index, add the cost of
159431 assert( pSrc->pTab->szTabRow>0 );
159432 rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
159433 pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
159434 if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
159435 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
159437 ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
159439 nOutUnadjusted = pNew->nOut;
159440 pNew->rRun += nInMul + nIn;
159441 pNew->nOut += nInMul + nIn;
159442 whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
159445 if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
159446 pNew->nOut = saved_nOut;
159448 pNew->nOut = nOutUnadjusted;
159451 if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
159452 && pNew->u.btree.nEq<pProbe->nColumn
159453 && (pNew->u.btree.nEq<pProbe->nKeyCol ||
159454 pProbe->idxType!=SQLITE_IDXTYPE_PRIMARYKEY)
159458 pNew->nOut = saved_nOut;
159460 pBuilder->nRecValid = nRecValid;
159463 pNew->prereq = saved_prereq;
159464 pNew->u.btree.nEq = saved_nEq;
159465 pNew->u.btree.nBtm = saved_nBtm;
159466 pNew->u.btree.nTop = saved_nTop;
159467 pNew->nSkip = saved_nSkip;
159468 pNew->wsFlags = saved_wsFlags;
159469 pNew->nOut = saved_nOut;
159470 pNew->nLTerm = saved_nLTerm;
159472 /* Consider using a skip-scan if there are no WHERE clause constraints
159473 ** available for the left-most terms of the index, and if the average
159474 ** number of repeats in the left-most terms is at least 18.
159484 && saved_nEq+1<pProbe->nKeyCol
159485 && saved_nEq==pNew->nLTerm
159486 && pProbe->noSkipScan==0
159487 && pProbe->hasStat1!=0
159489 && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
159490 && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
159493 pNew->u.btree.nEq++;
159494 pNew->nSkip++;
159495 pNew->aLTerm[pNew->nLTerm++] = 0;
159496 pNew->wsFlags |= WHERE_SKIPSCAN;
159497 nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
159498 pNew->nOut -= nIter;
159499 /* TUNING: Because uncertainties in the estimates for skip-scan queries,
159500 ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
159503 pNew->nOut = saved_nOut;
159504 pNew->u.btree.nEq = saved_nEq;
159505 pNew->nSkip = saved_nSkip;
159506 pNew->wsFlags = saved_wsFlags;
159510 pProbe->pTable->zName, pProbe->zName, saved_nEq, rc));
159531 if( pIndex->bUnordered ) return 0;
159532 if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
159533 for(ii=0; ii<pOB->nExpr; ii++){
159534 Expr *pExpr = sqlite3ExprSkipCollateAndLikely(pOB->a[ii].pExpr);
159536 if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
159537 if( pExpr->iColumn<0 ) return 1;
159538 for(jj=0; jj<pIndex->nKeyCol; jj++){
159539 if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
159541 }else if( (aColExpr = pIndex->aColExpr)!=0 ){
159542 for(jj=0; jj<pIndex->nKeyCol; jj++){
159543 if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
159544 if( sqlite3ExprCompareSkip(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
159567 pParse = pWC->pWInfo->pParse;
159568 while( pWhere->op==TK_AND ){
159569 if( !whereUsablePartialIndex(iTab,jointype,pWC,pWhere->pLeft) ) return 0;
159570 pWhere = pWhere->pRight;
159572 if( pParse->db->flags & SQLITE_EnableQPSG ) pParse = 0;
159573 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
159575 pExpr = pTerm->pExpr;
159576 if( (!ExprHasProperty(pExpr, EP_OuterON) || pExpr->w.iJoin==iTab)
159579 && (pTerm->wtFlags & TERM_VNULL)==0
159596 ** Information passed in is pWalk->u.pCovIdxCk. Call is pCk.
159598 ** If the Expr node references the table with cursor pCk->iTabCur, then
159599 ** make sure that column is covered by the index pCk->pIdx. We know that
159600 ** all columns less than 63 (really BMS-1) are covered, so we don't need
159603 ** If the index does not cover the column, then set pWalk->eCode to
159604 ** non-zero and return WRC_Abort to stop the search.
159614 if( pExpr->op!=TK_COLUMN && pExpr->op!=TK_AGG_COLUMN ) return WRC_Continue;
159615 if( pExpr->iColumn<(BMS-1) ) return WRC_Continue;
159616 if( pExpr->iTable!=pWalk->u.pCovIdxCk->iTabCur ) return WRC_Continue;
159617 pIdx = pWalk->u.pCovIdxCk->pIdx;
159618 aiColumn = pIdx->aiColumn;
159619 nColumn = pIdx->nColumn;
159621 if( aiColumn[i]==pExpr->iColumn ) return WRC_Continue;
159623 pWalk->eCode = 1;
159629 ** pIdx is an index that covers all of the low-number columns used by
159630 ** pWInfo->pSelect (columns from 0 through 62). But there are columns
159631 ** in pWInfo->pSelect beyond 62. This routine tries to answer the question
159634 ** Return 0 if pIdx is a covering index. Return non-zero if pIdx is
159638 ** This routine is an optimization. It is always safe to return non-zero.
159639 ** But returning zero when non-zero should have been returned can lead to
159650 if( pWInfo->pSelect==0 ){
159655 for(i=0; i<pIdx->nColumn; i++){
159656 if( pIdx->aiColumn[i]>=BMS-1 ) break;
159658 if( i>=pIdx->nColumn ){
159671 sqlite3WalkSelect(&w, pWInfo->pSelect);
159677 ** is identified by pBuilder->pNew->iTab. That table is guaranteed to be
159678 ** a b-tree table, not a virtual table.
159680 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
159685 ** cost = nRow * 3.0 // full-table scan
159687 ** cost = nRow * (K+3.0) // scan of non-covering index
159694 ** the index b-tree:
159697 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
159701 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
159706 ** log(nRow) factor is omitted from a non-covering index scan in order to
159707 ** bias the scoring in favor of using an index, since the worst-case
159708 ** performance of using an index is far better than the worst-case performance
159719 i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
159730 pNew = pBuilder->pNew;
159731 pWInfo = pBuilder->pWInfo;
159732 pTabList = pWInfo->pTabList;
159733 pSrc = pTabList->a + pNew->iTab;
159734 pTab = pSrc->pTab;
159735 pWC = pBuilder->pWC;
159736 assert( !IsVirtual(pSrc->pTab) );
159738 if( pSrc->fg.isIndexedBy ){
159739 assert( pSrc->fg.isCte==0 );
159741 pProbe = pSrc->u2.pIBIndex;
159743 pProbe = pTab->pIndex;
159757 sPk.szIdxRow = pTab->szTabRow;
159759 aiRowEstPk[0] = pTab->nRowLogEst;
159761 pFirst = pSrc->pTab->pIndex;
159762 if( pSrc->fg.notIndexed==0 ){
159769 rSize = pTab->nRowLogEst;
159773 if( !pBuilder->pOrSet /* Not part of an OR optimization */
159774 && (pWInfo->wctrlFlags & (WHERE_RIGHT_JOIN|WHERE_OR_SUBCLAUSE))==0
159775 && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
159776 && !pSrc->fg.isIndexedBy /* Has no INDEXED BY clause */
159777 && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
159779 && !pSrc->fg.isCorrelated /* Not a correlated subquery */
159780 && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
159781 && (pSrc->fg.jointype & JT_RIGHT)==0 /* Not the right tab of a RIGHT JOIN */
159783 /* Generate auto-index WhereLoops */
159786 WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
159788 for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
159789 if( pTerm->prereqRight & pNew->maskSelf ) continue;
159791 pNew->u.btree.nEq = 1;
159792 pNew->nSkip = 0;
159793 pNew->u.btree.pIndex = 0;
159794 pNew->nLTerm = 1;
159795 pNew->aLTerm[0] = pTerm;
159796 /* TUNING: One-time cost for computing the automatic index is
159799 ** tables or 0.5 (LogEst=-10) for views and subqueries. The value
159804 pNew->rSetup = rLogSize + rSize;
159805 if( !IsView(pTab) && (pTab->tabFlags & TF_Ephemeral)==0 ){
159806 pNew->rSetup += 28;
159808 pNew->rSetup -= 10;
159810 ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
159811 if( pNew->rSetup<0 ) pNew->rSetup = 0;
159816 pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
159817 pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
159818 pNew->wsFlags = WHERE_AUTO_INDEX;
159819 pNew->prereq = mPrereq | pTerm->prereqRight;
159829 pProbe=(pSrc->fg.isIndexedBy ? 0 : pProbe->pNext), iSortIdx++
159831 if( pProbe->pPartIdxWhere!=0
159832 && !whereUsablePartialIndex(pSrc->iCursor, pSrc->fg.jointype, pWC,
159833 pProbe->pPartIdxWhere)
159835 testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
159838 if( pProbe->bNoQuery ) continue;
159839 rSize = pProbe->aiRowLogEst[0];
159840 pNew->u.btree.nEq = 0;
159841 pNew->u.btree.nBtm = 0;
159842 pNew->u.btree.nTop = 0;
159843 pNew->nSkip = 0;
159844 pNew->nLTerm = 0;
159845 pNew->iSortIdx = 0;
159846 pNew->rSetup = 0;
159847 pNew->prereq = mPrereq;
159848 pNew->nOut = rSize;
159849 pNew->u.btree.pIndex = pProbe;
159850 b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
159853 assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
159854 if( pProbe->idxType==SQLITE_IDXTYPE_IPK ){
159856 pNew->wsFlags = WHERE_IPK;
159859 pNew->iSortIdx = b ? iSortIdx : 0;
159862 ** since index lookups have better worst-case performance if our
159873 pNew->rRun = rSize + 16 - 2*((pTab->tabFlags & TF_HasStat4)!=0);
159875 pNew->rRun = rSize + 16;
159877 if( IsView(pTab) || (pTab->tabFlags & TF_Ephemeral)!=0 ){
159878 pNew->wsFlags |= WHERE_VIEWSCAN;
159880 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
159883 pNew->nOut = rSize;
159887 if( pProbe->isCovering ){
159888 pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
159891 m = pSrc->colUsed & pProbe->colNotIdxed;
159893 m = whereIsCoveringIndex(pWInfo, pProbe, pSrc->iCursor);
159895 pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
159901 || pProbe->pPartIdxWhere!=0
159902 || pSrc->fg.isIndexedBy
159904 && pProbe->bUnordered==0
159905 && (pProbe->szIdxRow<pTab->szTabRow)
159906 && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
159908 && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
159911 pNew->iSortIdx = b ? iSortIdx : 0;
159916 pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
159918 /* If this is a non-covering index scan, add in the cost of
159925 int iCur = pSrc->iCursor;
159926 WhereClause *pWC2 = &pWInfo->sWC;
159927 for(ii=0; ii<pWC2->nTerm; ii++){
159928 WhereTerm *pTerm = &pWC2->a[ii];
159929 if( !sqlite3ExprCoveredByIndex(pTerm->pExpr, iCur, pProbe) ){
159934 if( pTerm->truthProb<=0 ){
159935 nLookup += pTerm->truthProb;
159937 nLookup--;
159938 if( pTerm->eOperator & (WO_EQ|WO_IS) ) nLookup -= 19;
159942 pNew->rRun = sqlite3LogEstAdd(pNew->rRun, nLookup);
159944 ApplyCostMultiplier(pNew->rRun, pTab->costMult);
159946 if( (pSrc->fg.jointype & JT_RIGHT)!=0 && pProbe->aColExpr ){
159947 /* Do not do an SCAN of a index-on-expression in a RIGHT JOIN
159949 ** positioned to the correct row during the right-join no-match
159954 pNew->nOut = rSize;
159959 pBuilder->bldFlags1 = 0;
159961 if( pBuilder->bldFlags1==SQLITE_BLDF1_INDEXED ){
159962 /* If a non-unique index is used, or if a prefix of the key for
159963 ** unique index is used (making the index functionally non-unique)
159966 pTab->tabFlags |= TF_StatsUsed;
159969 sqlite3Stat4ProbeFree(pBuilder->pRec);
159970 pBuilder->nRecValid = 0;
159971 pBuilder->pRec = 0;
159983 assert( pTerm->eOperator==WO_AUX || pTerm->eMatchOp==0 );
159984 return pTerm->eMatchOp>=SQLITE_INDEX_CONSTRAINT_LIMIT
159985 && pTerm->eMatchOp<=SQLITE_INDEX_CONSTRAINT_OFFSET;
159990 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
160018 WhereClause *pWC = pBuilder->pWC;
160021 struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
160025 WhereLoop *pNew = pBuilder->pNew;
160026 Parse *pParse = pBuilder->pWInfo->pParse;
160027 SrcItem *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
160028 int nConstraint = pIdxInfo->nConstraint;
160032 pNew->prereq = mPrereq;
160036 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
160038 WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
160039 pIdxCons->usable = 0;
160040 if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
160041 && (pTerm->eOperator & mExclude)==0
160044 pIdxCons->usable = 1;
160050 assert( pIdxInfo->needToFreeIdxStr==0 );
160051 pIdxInfo->idxStr = 0;
160052 pIdxInfo->idxNum = 0;
160053 pIdxInfo->orderByConsumed = 0;
160054 pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
160055 pIdxInfo->estimatedRows = 25;
160056 pIdxInfo->idxFlags = 0;
160057 pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
160058 pHidden->mHandleIn = 0;
160061 rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
160068 WHERETRACE(0xffff, (" ^^^^--- non-viable plan rejected!\n"));
160074 mxTerm = -1;
160075 assert( pNew->nLSlot>=nConstraint );
160076 memset(pNew->aLTerm, 0, sizeof(pNew->aLTerm[0])*nConstraint );
160077 memset(&pNew->u.vtab, 0, sizeof(pNew->u.vtab));
160078 pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
160081 if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
160083 int j = pIdxCons->iTermOffset;
160086 || j>=pWC->nTerm
160087 || pNew->aLTerm[iTerm]!=0
160088 || pIdxCons->usable==0
160090 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
160091 testcase( pIdxInfo->needToFreeIdxStr );
160094 testcase( iTerm==nConstraint-1 );
160096 testcase( j==pWC->nTerm-1 );
160097 pTerm = &pWC->a[j];
160098 pNew->prereq |= pTerm->prereqRight;
160099 assert( iTerm<pNew->nLSlot );
160100 pNew->aLTerm[iTerm] = pTerm;
160107 pNew->u.vtab.omitMask |= 1<<iTerm;
160111 if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET ){
160112 pNew->u.vtab.bOmitOffset = 1;
160115 if( SMASKBIT32(i) & pHidden->mHandleIn ){
160116 pNew->u.vtab.mHandleIn |= MASKBIT32(iTerm);
160117 }else if( (pTerm->eOperator & WO_IN)!=0 ){
160123 pIdxInfo->orderByConsumed = 0;
160124 pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
160135 if( pIdxInfo->needToFreeIdxStr ){
160136 sqlite3_free(pIdxInfo->idxStr);
160137 pIdxInfo->idxStr = 0;
160138 pIdxInfo->needToFreeIdxStr = 0;
160146 pNew->nLTerm = mxTerm+1;
160148 if( pNew->aLTerm[i]==0 ){
160149 /* The non-zero argvIdx values must be contiguous. Raise an
160151 sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
160152 testcase( pIdxInfo->needToFreeIdxStr );
160156 assert( pNew->nLTerm<=pNew->nLSlot );
160157 pNew->u.vtab.idxNum = pIdxInfo->idxNum;
160158 pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
160159 pIdxInfo->needToFreeIdxStr = 0;
160160 pNew->u.vtab.idxStr = pIdxInfo->idxStr;
160161 pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
160162 pIdxInfo->nOrderBy : 0);
160163 pNew->rSetup = 0;
160164 pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
160165 pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
160169 if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
160170 pNew->wsFlags |= WHERE_ONEROW;
160172 pNew->wsFlags &= ~WHERE_ONEROW;
160175 if( pNew->u.vtab.needFree ){
160176 sqlite3_free(pNew->u.vtab.idxStr);
160177 pNew->u.vtab.needFree = 0;
160181 (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
160204 if( iCons>=0 && iCons<pIdxInfo->nConstraint ){
160206 int iTerm = pIdxInfo->aConstraint[iCons].iTermOffset;
160207 Expr *pX = pHidden->pWC->a[iTerm].pExpr;
160208 if( pX->pLeft ){
160209 pC = sqlite3ExprCompareCollSeq(pHidden->pParse, pX);
160211 zRet = (pC ? pC->zName : sqlite3StrBINARY);
160224 if( m & pHidden->mIn ){
160226 pHidden->mHandleIn &= ~m;
160228 pHidden->mHandleIn |= m;
160239 ** on the right-hand-side of constraint iCons.
160249 if( iCons<0 || iCons>=pIdxInfo->nConstraint ){
160250 rc = SQLITE_MISUSE; /* EV: R-30545-25046 */
160252 if( pH->aRhs[iCons]==0 ){
160253 WhereTerm *pTerm = &pH->pWC->a[pIdxInfo->aConstraint[iCons].iTermOffset];
160255 pH->pParse->db, pTerm->pExpr->pRight, ENC(pH->pParse->db),
160256 SQLITE_AFF_BLOB, &pH->aRhs[iCons]
160260 pVal = pH->aRhs[iCons];
160264 if( rc==SQLITE_OK && pVal==0 ){ /* IMP: R-19933-32160 */
160265 rc = SQLITE_NOTFOUND; /* IMP: R-36424-56542 */
160276 assert( pHidden->eDistinct>=0 && pHidden->eDistinct<=3 );
160277 return pHidden->eDistinct;
160285 ** prepared is read-only, then just start read transactions on all
160289 ** This is used by the (built-in) sqlite_dbpage virtual table.
160293 Parse *pParse = pHidden->pParse;
160294 int nDb = pParse->db->nDb;
160299 if( pParse->writeMask ){
160309 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
160330 ** mUnusable should always be configured as "not-usable" for xBestIndex.
160351 pWInfo = pBuilder->pWInfo;
160352 pParse = pWInfo->pParse;
160353 pWC = pBuilder->pWC;
160354 pNew = pBuilder->pNew;
160355 pSrc = &pWInfo->pTabList->a[pNew->iTab];
160356 assert( IsVirtual(pSrc->pTab) );
160359 pNew->rSetup = 0;
160360 pNew->wsFlags = WHERE_VIRTUALTABLE;
160361 pNew->nLTerm = 0;
160362 pNew->u.vtab.needFree = 0;
160363 nConstraint = p->nConstraint;
160364 if( whereLoopResize(pParse->db, pNew, nConstraint) ){
160365 freeIndexInfo(pParse->db, p);
160370 WHERETRACE(0x800, ("BEGIN %s.addVirtual()\n", pSrc->pTab->zName));
160383 ** that does not require any source tables (IOW: a plan with mBest==0)
160387 if( rc==SQLITE_OK && ((mBest = (pNew->prereq & ~mPrereq))!=0 || bIn) ){
160400 mBestNoIn = pNew->prereq & ~mPrereq;
160415 pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
160426 if( pNew->prereq==mPrereq ){
160433 ** that requires no source tables at all (i.e. one guaranteed to be
160434 ** usable), make a call here with all source tables disabled */
160443 ** that requires no source tables at all and does not use an IN(...)
160452 if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
160453 freeIndexInfo(pParse->db, p);
160454 WHERETRACE(0x800, ("END %s.addVirtual(), rc=%d\n", pSrc->pTab->zName, rc));
160468 WhereInfo *pWInfo = pBuilder->pWInfo;
160479 pWC = pBuilder->pWC;
160480 pWCEnd = pWC->a + pWC->nTerm;
160481 pNew = pBuilder->pNew;
160483 pItem = pWInfo->pTabList->a + pNew->iTab;
160484 iCur = pItem->iCursor;
160486 /* The multi-index OR optimization does not work for RIGHT and FULL JOIN */
160487 if( pItem->fg.jointype & JT_RIGHT ) return SQLITE_OK;
160489 for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
160490 if( (pTerm->eOperator & WO_OR)!=0
160491 && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
160493 WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
160494 WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
160502 WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
160503 for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
160504 if( (pOrTerm->eOperator & WO_AND)!=0 ){
160505 sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
160506 }else if( pOrTerm->leftCursor==iCur ){
160507 tempWC.pWInfo = pWC->pWInfo;
160519 WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
160520 (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
160526 if( IsVirtual(pItem->pTab) ){
160559 pNew->nLTerm = 1;
160560 pNew->aLTerm[0] = pTerm;
160561 pNew->wsFlags = WHERE_MULTI_OR;
160562 pNew->rSetup = 0;
160563 pNew->iSortIdx = 0;
160564 memset(&pNew->u, 0, sizeof(pNew->u));
160567 ** of all sub-scans required by the OR-scan. However, due to rounding
160568 ** errors, it may be that the cost of the OR-scan is equal to its
160569 ** most expensive sub-scan. Add the smallest possible penalty
160576 ** the planner may elect to "OR" together a full-table scan and an
160578 pNew->rRun = sSum.a[i].rRun + 1;
160579 pNew->nOut = sSum.a[i].nOut;
160580 pNew->prereq = sSum.a[i].prereq;
160583 WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
160593 WhereInfo *pWInfo = pBuilder->pWInfo;
160597 SrcList *pTabList = pWInfo->pTabList;
160599 SrcItem *pEnd = &pTabList->a[pWInfo->nLevel];
160600 sqlite3 *db = pWInfo->pParse->db;
160608 pNew = pBuilder->pNew;
160611 assert( pNew->nLTerm==0 );
160612 assert( pNew->wsFlags==0 );
160613 assert( pNew->nLSlot>=ArraySize(pNew->aLTermSpace) );
160614 assert( pNew->aLTerm!=0 );
160616 pBuilder->iPlanLimit = SQLITE_QUERY_PLANNER_LIMIT;
160617 for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
160619 pNew->iTab = iTab;
160620 pBuilder->iPlanLimit += SQLITE_QUERY_PLANNER_LIMIT_INCR;
160621 pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
160623 || (pItem->fg.jointype & (JT_OUTER|JT_CROSS|JT_LTORJ))!=0
160631 ** prevent FROM-clause terms from moving from the right side of
160635 if( pItem->fg.jointype & JT_LTORJ ) hasRightJoin = 1;
160637 bFirstPastRJ = (pItem->fg.jointype & JT_RIGHT)!=0;
160642 if( IsVirtual(pItem->pTab) ){
160645 if( mUnusable || (p->fg.jointype & (JT_OUTER|JT_CROSS)) ){
160646 mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
160655 if( rc==SQLITE_OK && pBuilder->pWC->hasOr ){
160658 mPrior |= pNew->maskSelf;
160659 if( rc || db->mallocFailed ){
160689 ** pOrderBy terms must be matched in strict left-to-right order.
160696 u16 nLoop, /* Number of entries in pPath->aLoop[] */
160697 WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
160703 u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
160719 sqlite3 *db = pWInfo->pParse->db; /* Database connection */
160722 Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
160726 ** We say the WhereLoop is "one-row" if it generates no more than one
160727 ** row of output. A WhereLoop is one-row if all of the following are true:
160730 ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
160731 ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
160733 ** We say the WhereLoop is "order-distinct" if the set of columns from
160735 ** row of the WhereLoop. Every one-row WhereLoop is automatically
160736 ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
160737 ** is not order-distinct. To be order-distinct is not quite the same as being
160739 ** are NULL and NULL values are equivalent for the purpose of order-distinct.
160740 ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
160744 ** automatically order-distinct.
160750 nOrderBy = pOrderBy->nExpr;
160751 testcase( nOrderBy==BMS-1 );
160752 if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
160754 obDone = MASKBIT(nOrderBy)-1;
160762 if( iLoop>0 ) ready |= pLoop->maskSelf;
160764 pLoop = pPath->aLoop[iLoop];
160769 if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
160770 if( pLoop->u.vtab.isOrdered
160777 pLoop->u.btree.nDistinctCol = 0;
160779 iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
160788 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
160790 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
160791 if( pOBExpr->iTable!=iCur ) continue;
160792 pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
160795 if( pTerm->eOperator==WO_IN ){
160801 for(j=0; j<pLoop->nLTerm && pTerm!=pLoop->aLTerm[j]; j++){}
160802 if( j>=pLoop->nLTerm ) continue;
160804 if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
160805 Parse *pParse = pWInfo->pParse;
160806 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[i].pExpr);
160807 CollSeq *pColl2 = sqlite3ExprCompareCollSeq(pParse, pTerm->pExpr);
160809 if( pColl2==0 || sqlite3StrICmp(pColl1->zName, pColl2->zName) ){
160812 testcase( pTerm->pExpr->op==TK_IS );
160817 if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
160818 if( pLoop->wsFlags & WHERE_IPK ){
160822 }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
160825 nKeyCol = pIndex->nKeyCol;
160826 nColumn = pIndex->nColumn;
160827 assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
160828 assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
160829 || !HasRowid(pIndex->pTable));
160830 /* All relevant terms of the index must also be non-NULL in order
160833 ** made at tag-20210426-1 below */
160835 && (pLoop->wsFlags & WHERE_SKIPSCAN)==0;
160846 assert( j>=pLoop->u.btree.nEq
160847 || (pLoop->aLTerm[j]==0)==(j<pLoop->nSkip)
160849 if( j<pLoop->u.btree.nEq && j>=pLoop->nSkip ){
160850 u16 eOp = pLoop->aLTerm[j]->eOperator;
160855 ** the loop need to be marked as not order-distinct because it can
160874 ** j<pLoop->u.btree.nEq constraint above. Any equality other
160877 Expr *pX = pLoop->aLTerm[j]->pExpr;
160878 for(i=j+1; i<pLoop->u.btree.nEq; i++){
160879 if( pLoop->aLTerm[i]->pExpr==pX ){
160880 assert( (pLoop->aLTerm[i]->eOperator & WO_IN) );
160889 ** (revIdx) for the j-th column of the index.
160892 iColumn = pIndex->aiColumn[j];
160893 revIdx = pIndex->aSortOrder[j] & KEYINFO_ORDER_DESC;
160894 if( iColumn==pIndex->pTable->iPKey ) iColumn = XN_ROWID;
160901 ** WhereLoop is not well-ordered. tag-20210426-1
160905 && j>=pLoop->u.btree.nEq
160906 && pIndex->pTable->aCol[iColumn].notNull==0
160915 /* Find the ORDER BY term that corresponds to the j-th column
160921 pOBExpr = sqlite3ExprSkipCollateAndLikely(pOrderBy->a[i].pExpr);
160927 if( pOBExpr->op!=TK_COLUMN && pOBExpr->op!=TK_AGG_COLUMN ) continue;
160928 if( pOBExpr->iTable!=iCur ) continue;
160929 if( pOBExpr->iColumn!=iColumn ) continue;
160931 Expr *pIdxExpr = pIndex->aColExpr->a[j].pExpr;
160937 pColl = sqlite3ExprNNCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
160938 if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
160941 pLoop->u.btree.nDistinctCol = j+1;
160951 != (pOrderBy->a[i].fg.sortFlags&KEYINFO_ORDER_DESC)
160956 rev = revIdx ^ (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_DESC);
160961 if( isMatch && (pOrderBy->a[i].fg.sortFlags & KEYINFO_ORDER_BIGNULL) ){
160962 if( j==pLoop->u.btree.nEq ){
160963 pLoop->wsFlags |= WHERE_BIGNULL_SORT;
160987 } /* end-if not one-row */
160991 orderDistinctMask |= pLoop->maskSelf;
160996 p = pOrderBy->a[i].pExpr;
160997 mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
161004 } /* End the loop over all WhereLoops from outer-most down to inner-most */
161007 for(i=nOrderBy-1; i>0; i--){
161008 Bitmask m = ALWAYS(i<BMS) ? MASKBIT(i) - 1 : 0;
161013 return -1;
161020 ** BY clause - and so any order that groups rows as required satisfies the
161037 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
161038 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
161041 assert( pWInfo->wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY) );
161042 assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
161043 return pWInfo->sorted;
161051 for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
161052 if( pLast ) zName[i++] = pLast->cId;
161074 ** Or, if the order-by clause has X terms but only the last Y
161075 ** terms are out of order, then block-sorting will reduce the
161085 rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
161093 if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
161094 nRow = pWInfo->iLimit;
161095 }else if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT) ){
161098 if( nRow>10 ){ nRow -= 10; assert( 10==sqlite3LogEst(2) ); }
161105 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
161107 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
161137 pParse = pWInfo->pParse;
161138 nLoop = pWInfo->nLevel;
161140 ** For 2-way joins, the 5 best paths are followed.
161143 assert( nLoop<=pWInfo->pTabList->nSrc );
161144 WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
161151 if( pWInfo->pOrderBy==0 || nRowEst==0 ){
161154 nOrderBy = pWInfo->pOrderBy->nExpr;
161160 pSpace = sqlite3StackAllocRawNN(pParse->db, nSpace);
161166 for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
161167 pFrom->aLoop = pX;
161172 ** is either zero - meaning it has not yet been initialized - or the
161187 aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
161195 ** -1, indicating that the result set may or may not be ordered,
161197 aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
161206 for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
161212 Bitmask revMask; /* Mask of rev-order loops for (..) */
161214 if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
161215 if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
161216 if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<3 ){
161227 rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
161228 rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
161229 nOut = pFrom->nRow + pWLoop->nOut;
161230 maskNew = pFrom->maskLoop | pWLoop->maskSelf;
161231 isOrdered = pFrom->isOrdered;
161235 pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
161238 revMask = pFrom->revLoop;
161253 ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
161254 aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
161258 rUnsorted -= 2; /* TUNING: Slight bias in favor of no-sort plans */
161261 /* TUNING: A full-scan of a VIEW or subquery in the outer loop
161263 if( iLoop==0 && (pWLoop->wsFlags & WHERE_VIEWSCAN)!=0 ){
161264 rCost += -10;
161265 nOut += -30;
161269 ** mxChoice best-so-far paths.
161271 ** First look for an existing path among best-so-far paths
161275 ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
161276 ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
161277 ** of legal values for isOrdered, -1..64.
161280 if( pTo->maskLoop==maskNew
161281 && ((pTo->isOrdered^isOrdered)&0x80)==0
161283 testcase( jj==nTo-1 );
161288 /* None of the existing best-so-far paths match the candidate. */
161293 ** paths currently in the best-so-far buffer. So discard
161297 sqlite3DebugPrintf("Skip %s cost=%-3d,%3d,%3d order=%c\n",
161305 ** needs to be added to the set of best-so-far paths. */
161316 sqlite3DebugPrintf("New %s cost=%-3d,%3d,%3d order=%c\n",
161322 /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
161328 ** (pTo->rCost,pTo->nRow,pTo->rUnsorted) <= (rCost,nOut,rUnsorted)
161330 if( pTo->rCost<rCost
161331 || (pTo->rCost==rCost
161332 && (pTo->nRow<nOut
161333 || (pTo->nRow==nOut && pTo->rUnsorted<=rUnsorted)
161340 "Skip %s cost=%-3d,%3d,%3d order=%c",
161343 sqlite3DebugPrintf(" vs %s cost=%-3d,%3d,%3d order=%c\n",
161344 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
161345 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
161349 testcase( pTo->rCost==rCost );
161352 testcase( pTo->rCost==rCost+1 );
161358 "Update %s cost=%-3d,%3d,%3d order=%c",
161361 sqlite3DebugPrintf(" was %s cost=%-3d,%3d,%3d order=%c\n",
161362 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
161363 pTo->rUnsorted, pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
161368 pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
161369 pTo->revLoop = revMask;
161370 pTo->nRow = nOut;
161371 pTo->rCost = rCost;
161372 pTo->rUnsorted = rUnsorted;
161373 pTo->isOrdered = isOrdered;
161374 memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
161375 pTo->aLoop[iLoop] = pWLoop;
161381 if( pTo->rCost>mxCost
161382 || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
161384 mxCost = pTo->rCost;
161385 mxUnsorted = pTo->rUnsorted;
161395 sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
161397 sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
161398 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
161399 pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
161400 if( pTo->isOrdered>0 ){
161401 sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
161418 sqlite3StackFreeNN(pParse->db, pSpace);
161425 if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
161427 assert( pWInfo->nLevel==nLoop );
161430 WhereLevel *pLevel = pWInfo->a + iLoop;
161431 pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
161432 pLevel->iFrom = pWLoop->iTab;
161433 pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
161435 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
161436 && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
161437 && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
161441 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
161442 WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
161443 if( rc==pWInfo->pResultSet->nExpr ){
161444 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
161447 pWInfo->bOrderedInnerLoop = 0;
161448 if( pWInfo->pOrderBy ){
161449 pWInfo->nOBSat = pFrom->isOrdered;
161450 if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
161451 if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
161452 pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
161455 pWInfo->revMask = pFrom->revLoop;
161456 if( pWInfo->nOBSat<=0 ){
161457 pWInfo->nOBSat = 0;
161459 u32 wsFlags = pFrom->aLoop[nLoop-1]->wsFlags;
161464 int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, pFrom,
161465 WHERE_ORDERBY_LIMIT, nLoop-1, pFrom->aLoop[nLoop-1], &m);
161468 if( rc==pWInfo->pOrderBy->nExpr ){
161469 pWInfo->bOrderedInnerLoop = 1;
161470 pWInfo->revMask = m;
161475 && pWInfo->nOBSat==1
161476 && (pWInfo->wctrlFlags & (WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX))!=0
161478 pWInfo->bOrderedInnerLoop = 1;
161481 if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
161482 && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
161485 int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
161486 pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
161488 assert( pWInfo->sorted==0 );
161489 if( nOrder==pWInfo->pOrderBy->nExpr ){
161490 pWInfo->sorted = 1;
161491 pWInfo->revMask = revMask;
161497 pWInfo->nRowOut = pFrom->nRow;
161500 sqlite3StackFreeNN(pParse->db, pSpace);
161508 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
161511 ** Return non-zero on success, if this query can be handled by this
161512 ** no-frills query planner. Return zero if this query needs the
161513 ** general-purpose query planner.
161527 pWInfo = pBuilder->pWInfo;
161528 if( pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE ) return 0;
161529 assert( pWInfo->pTabList->nSrc>=1 );
161530 pItem = pWInfo->pTabList->a;
161531 pTab = pItem->pTab;
161533 if( pItem->fg.isIndexedBy || pItem->fg.notIndexed ){
161534 testcase( pItem->fg.isIndexedBy );
161535 testcase( pItem->fg.notIndexed );
161538 iCur = pItem->iCursor;
161539 pWC = &pWInfo->sWC;
161540 pLoop = pBuilder->pNew;
161541 pLoop->wsFlags = 0;
161542 pLoop->nSkip = 0;
161543 pTerm = whereScanInit(&scan, pWC, iCur, -1, WO_EQ|WO_IS, 0);
161544 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
161546 testcase( pTerm->eOperator & WO_IS );
161547 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
161548 pLoop->aLTerm[0] = pTerm;
161549 pLoop->nLTerm = 1;
161550 pLoop->u.btree.nEq = 1;
161552 pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
161554 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
161556 assert( pLoop->aLTermSpace==pLoop->aLTerm );
161558 || pIdx->pPartIdxWhere!=0
161559 || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
161561 opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
161562 for(j=0; j<pIdx->nKeyCol; j++){
161564 while( pTerm && pTerm->prereqRight ) pTerm = whereScanNext(&scan);
161566 testcase( pTerm->eOperator & WO_IS );
161567 pLoop->aLTerm[j] = pTerm;
161569 if( j!=pIdx->nKeyCol ) continue;
161570 pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
161571 if( pIdx->isCovering || (pItem->colUsed & pIdx->colNotIdxed)==0 ){
161572 pLoop->wsFlags |= WHERE_IDX_ONLY;
161574 pLoop->nLTerm = j;
161575 pLoop->u.btree.nEq = j;
161576 pLoop->u.btree.pIndex = pIdx;
161578 pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
161582 if( pLoop->wsFlags ){
161583 pLoop->nOut = (LogEst)1;
161584 pWInfo->a[0].pWLoop = pLoop;
161585 assert( pWInfo->sMaskSet.n==1 && iCur==pWInfo->sMaskSet.ix[0] );
161586 pLoop->maskSelf = 1; /* sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur); */
161587 pWInfo->a[0].iTabCur = iCur;
161588 pWInfo->nRowOut = 1;
161589 if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
161590 if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
161591 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
161593 if( scan.iEquiv>1 ) pLoop->wsFlags |= WHERE_TRANSCONS;
161595 pLoop->cId = '0';
161611 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_ConstFunc)==0 ){
161612 pWalker->eCode = 0;
161619 ** Return true if the expression contains no non-deterministic SQL
161620 ** functions. Do not consider non-deterministic SQL functions that are
161621 ** part of sub-select statements.
161644 for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
161645 p->cId = zLabel[i%(sizeof(zLabel)-1)];
161692 assert( pWInfo->nLevel>=2 );
161693 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_OmitNoopJoin) );
161697 assert( pWInfo->pResultSet!=0 );
161698 assert( 0==(pWInfo->wctrlFlags & WHERE_AGG_DISTINCT) );
161700 tabUsed = sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pResultSet);
161701 if( pWInfo->pOrderBy ){
161702 tabUsed |= sqlite3WhereExprListUsage(&pWInfo->sMaskSet, pWInfo->pOrderBy);
161704 for(i=pWInfo->nLevel-1; i>=1; i--){
161708 pLoop = pWInfo->a[i].pWLoop;
161709 pItem = &pWInfo->pTabList->a[pLoop->iTab];
161710 if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ) continue;
161711 if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)==0
161712 && (pLoop->wsFlags & WHERE_ONEROW)==0
161716 if( (tabUsed & pLoop->maskSelf)!=0 ) continue;
161717 pEnd = pWInfo->sWC.a + pWInfo->sWC.nTerm;
161718 for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
161719 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
161720 if( !ExprHasProperty(pTerm->pExpr, EP_OuterON)
161721 || pTerm->pExpr->w.iJoin!=pItem->iCursor
161728 WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
161729 notReady &= ~pLoop->maskSelf;
161730 for(pTerm=pWInfo->sWC.a; pTerm<pEnd; pTerm++){
161731 if( (pTerm->prereqAll & pLoop->maskSelf)!=0 ){
161732 pTerm->wtFlags |= TERM_CODED;
161735 if( i!=pWInfo->nLevel-1 ){
161736 int nByte = (pWInfo->nLevel-1-i) * sizeof(WhereLevel);
161737 memmove(&pWInfo->a[i], &pWInfo->a[i+1], nByte);
161739 pWInfo->nLevel--;
161740 assert( pWInfo->nLevel>0 );
161754 ** (3) Bloom-filter processing is not disabled. (Checked by the
161769 assert( pWInfo->nLevel>=2 );
161770 assert( OptimizationEnabled(pWInfo->pParse->db, SQLITE_BloomFilter) );
161771 nSearch = pWInfo->a[0].pWLoop->nOut;
161772 for(i=1; i<pWInfo->nLevel; i++){
161773 WhereLoop *pLoop = pWInfo->a[i].pWLoop;
161775 if( (pLoop->wsFlags & reqFlags)==reqFlags
161776 /* vvvvvv--- Always the case if WHERE_COLUMN_EQ is defined */
161777 && ALWAYS((pLoop->wsFlags & (WHERE_IPK|WHERE_INDEXED))!=0)
161779 SrcItem *pItem = &pWInfo->pTabList->a[pLoop->iTab];
161780 Table *pTab = pItem->pTab;
161781 pTab->tabFlags |= TF_StatsUsed;
161782 if( nSearch > pTab->nRowLogEst
161783 && (pTab->tabFlags & TF_HasStat1)!=0
161785 testcase( pItem->fg.jointype & JT_LEFT );
161786 pLoop->wsFlags |= WHERE_BLOOMFILTER;
161787 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
161789 "-> use Bloom-filter on loop %c because there are ~%.1e "
161791 pLoop->cId, (double)sqlite3LogEstToInt(nSearch), pTab->zName,
161792 (double)sqlite3LogEstToInt(pTab->nRowLogEst)));
161795 nSearch += pLoop->nOut;
161801 ** free the Parse->pIdxExpr list when the Parse object is destroyed.
161805 while( pParse->pIdxExpr!=0 ){
161806 IndexedExpr *p = pParse->pIdxExpr;
161807 pParse->pIdxExpr = p->pIENext;
161808 sqlite3ExprDelete(db, p->pExpr);
161819 ** This routine adds IndexedExpr entries to the Parse->pIdxExpr field for
161825 Parse *pParse, /* Add IndexedExpr entries to pParse->pIdxExpr */
161826 Index *pIdx, /* The index-on-expression that contains the expressions */
161833 assert( pIdx->bHasExpr );
161834 pTab = pIdx->pTable;
161835 for(i=0; i<pIdx->nColumn; i++){
161837 int j = pIdx->aiColumn[i];
161840 pExpr = pIdx->aColExpr->a[i].pExpr;
161841 testcase( pTabItem->fg.jointype & JT_LEFT );
161842 testcase( pTabItem->fg.jointype & JT_RIGHT );
161843 testcase( pTabItem->fg.jointype & JT_LTORJ );
161844 bMaybeNullRow = (pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT))!=0;
161845 }else if( j>=0 && (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)!=0 ){
161846 pExpr = sqlite3ColumnExpr(pTab, &pTab->aCol[j]);
161852 p = sqlite3DbMallocRaw(pParse->db, sizeof(IndexedExpr));
161854 p->pIENext = pParse->pIdxExpr;
161855 p->pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
161856 p->iDataCur = pTabItem->iCursor;
161857 p->iIdxCur = iIdxCur;
161858 p->iIdxCol = i;
161859 p->bMaybeNullRow = bMaybeNullRow;
161861 p->zIdxName = pIdx->zName;
161863 pParse->pIdxExpr = p;
161864 if( p->pIENext==0 ){
161889 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
161893 ** end |-- by sqlite3WhereEnd()
161900 ** scanning through all values on the right-hand side of the IN.
161903 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
161913 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
161923 ** inner loops (or around the "..." if the test occurs within the inner-
161972 Vdbe *v = pParse->pVdbe; /* The virtual database engine */
161976 WhereLevel *pLevel; /* A single level in pWInfo->a[] */
161993 db = pParse->db;
161997 testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
161998 if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
162003 testcase( pTabList->nSrc==BMS );
162004 if( pTabList->nSrc>BMS ){
162014 nTabList = (wctrlFlags & WHERE_OR_SUBCLAUSE) ? 1 : pTabList->nSrc;
162019 ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
162020 ** field (type Bitmask) it must be aligned on an 8-byte boundary on
162023 nByteWInfo = ROUND8P(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
162025 if( db->mallocFailed ){
162030 pWInfo->pParse = pParse;
162031 pWInfo->pTabList = pTabList;
162032 pWInfo->pOrderBy = pOrderBy;
162034 pWInfo->pWhere = pWhere;
162036 pWInfo->pResultSet = pResultSet;
162037 pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
162038 pWInfo->nLevel = nTabList;
162039 pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(pParse);
162040 pWInfo->wctrlFlags = wctrlFlags;
162041 pWInfo->iLimit = iAuxArg;
162042 pWInfo->savedNQueryLoop = pParse->nQueryLoop;
162043 pWInfo->pSelect = pSelect;
162044 memset(&pWInfo->nOBSat, 0,
162045 offsetof(WhereInfo,sWC) - offsetof(WhereInfo,nOBSat));
162046 memset(&pWInfo->a[0], 0, sizeof(WhereLoop)+nTabList*sizeof(WhereLevel));
162047 assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
162048 pMaskSet = &pWInfo->sMaskSet;
162049 pMaskSet->n = 0;
162050 pMaskSet->ix[0] = -99; /* Initialize ix[0] to a value that can never be
162052 ** test for pMaskSet->n==0 in sqlite3WhereGetMask() */
162054 sWLB.pWC = &pWInfo->sWC;
162059 sWLB.pNew->cId = '*';
162065 sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
162066 sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
162071 if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
162075 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
162081 ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
162084 ** a table T, then X-1 is the bitmask for all other tables to the left of T.
162088 ** Note that bitmasks are created for all pTabList->nSrc tables in
162090 ** equal to pTabList->nSrc but might be shortened to 1 if the
162095 createMask(pMaskSet, pTabList->a[ii].iCursor);
162096 sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
162097 }while( (++ii)<pTabList->nSrc );
162101 for(ii=0; ii<pTabList->nSrc; ii++){
162102 Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
162111 sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
162112 if( pSelect && pSelect->pLimit ){
162113 sqlite3WhereAddLimit(&pWInfo->sWC, pSelect);
162115 if( pParse->nErr ) goto whereBeginError;
162121 ** Do not do this if the expression contains non-deterministic functions
162122 ** that are not within a sub-select. This is not strictly required, but
162125 ** FROM ... WHERE random()>0; -- eval random() once per row
162126 ** FROM ... WHERE (SELECT random())>0; -- eval random() once overall
162128 for(ii=0; ii<sWLB.pWC->nBase; ii++){
162129 WhereTerm *pT = &sWLB.pWC->a[ii];
162130 if( pT->wtFlags & TERM_VIRTUAL ) continue;
162131 if( pT->prereqAll==0 && (nTabList==0 || exprIsDeterministic(pT->pExpr)) ){
162132 sqlite3ExprIfFalse(pParse, pT->pExpr, pWInfo->iBreak, SQLITE_JUMPIFNULL);
162133 pT->wtFlags |= TERM_CODED;
162142 pWInfo->wctrlFlags &= ~WHERE_WANT_DISTINCT;
162143 }else if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
162145 pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
162148 pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
162149 pWInfo->pOrderBy = pResultSet;
162173 sqlite3DebugPrintf("---- WHERE clause at start of analysis:\n");
162193 while( pWInfo->pLoops ){
162194 WhereLoop *p = pWInfo->pLoops;
162195 pWInfo->pLoops = p->pNextLoop;
162205 if( db->mallocFailed ) goto whereBeginError;
162206 if( pWInfo->pOrderBy ){
162207 wherePathSolver(pWInfo, pWInfo->nRowOut+1);
162208 if( db->mallocFailed ) goto whereBeginError;
162211 if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
162212 pWInfo->revMask = ALLBITS;
162214 if( pParse->nErr ){
162217 assert( db->mallocFailed==0 );
162220 sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
162221 if( pWInfo->nOBSat>0 ){
162222 sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
162224 switch( pWInfo->eDistinct ){
162239 for(ii=0; ii<pWInfo->nLevel; ii++){
162240 sqlite3WhereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
162248 ** This query optimization is factored out into a separate "no-inline"
162251 ** some C-compiler optimizers from in-lining the
162253 ** in-line sqlite3WhereCodeOneLoopStart() for performance reasons.
162256 if( pWInfo->nLevel>=2
162262 nTabList = pWInfo->nLevel;
162269 if( pWInfo->nLevel>=2
162277 sqlite3DebugPrintf("---- WHERE clause at end of analysis:\n");
162282 pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
162285 ** to use a one-pass algorithm, determine if this is appropriate.
162287 ** A one-pass approach can be used if the caller has requested one
162291 ** * the caller has indicated that a one-pass approach can be used
162300 ** use a one-pass approach, and this is not set accurately for scans
162303 assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
162305 int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
162307 assert( !(wsFlags & WHERE_VIRTUALTABLE) || IsVirtual(pTabList->a[0].pTab) );
162310 && !IsVirtual(pTabList->a[0].pTab)
162313 pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
162314 if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
162318 pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
162326 for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
162331 pTabItem = &pTabList->a[pLevel->iFrom];
162332 pTab = pTabItem->pTab;
162333 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
162334 pLoop = pLevel->pWLoop;
162335 if( (pTab->tabFlags & TF_Ephemeral)!=0 || IsView(pTab) ){
162339 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
162341 int iCur = pTabItem->iCursor;
162347 if( ((pLoop->wsFlags & WHERE_IDX_ONLY)==0
162349 || (pTabItem->fg.jointype & (JT_LTORJ|JT_RIGHT))!=0
162352 if( pWInfo->eOnePass!=ONEPASS_OFF ){
162354 pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
162356 sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
162357 assert( pTabItem->iCursor==pLevel->iTabCur );
162358 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
162359 testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
162360 if( pWInfo->eOnePass==ONEPASS_OFF
162361 && pTab->nCol<BMS
162362 && (pTab->tabFlags & (TF_HasGenerated|TF_WithoutRowid))==0
162363 && (pLoop->wsFlags & (WHERE_AUTO_INDEX|WHERE_BLOOMFILTER))==0
162368 Bitmask b = pTabItem->colUsed;
162371 sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(n), P4_INT32);
162372 assert( n<=pTab->nCol );
162375 if( pLoop->u.btree.pIndex!=0 ){
162383 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
162384 (const u8*)&pTabItem->colUsed, P4_INT64);
162387 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
162389 if( pLoop->wsFlags & WHERE_INDEXED ){
162390 Index *pIx = pLoop->u.btree.pIndex;
162394 assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
162398 /* This is one term of an OR-optimization using the PRIMARY KEY of a
162400 iIndexCur = pLevel->iTabCur;
162402 }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
162403 Index *pJ = pTabItem->pTab->pIndex;
162408 pJ = pJ->pNext;
162411 pWInfo->aiCurOnePass[1] = iIndexCur;
162416 iIndexCur = pParse->nTab++;
162417 if( pIx->bHasExpr && OptimizationEnabled(db, SQLITE_IndexedExpr) ){
162421 pLevel->iIdxCur = iIndexCur;
162423 assert( pIx->pSchema==pTab->pSchema );
162426 sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
162428 if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
162429 && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
162430 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)==0
162431 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
162432 && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
162433 && pWInfo->eDistinct!=WHERE_DISTINCT_ORDERED
162437 VdbeComment((v, "%s", pIx->zName));
162442 for(ii=0; ii<pIx->nColumn; ii++){
162443 jj = pIx->aiColumn[ii];
162446 if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
162456 if( (pTabItem->fg.jointype & JT_RIGHT)!=0
162457 && (pLevel->pRJ = sqlite3WhereMalloc(pWInfo, sizeof(WhereRightJoin)))!=0
162459 WhereRightJoin *pRJ = pLevel->pRJ;
162460 pRJ->iMatch = pParse->nTab++;
162461 pRJ->regBloom = ++pParse->nMem;
162462 sqlite3VdbeAddOp2(v, OP_Blob, 65536, pRJ->regBloom);
162463 pRJ->regReturn = ++pParse->nMem;
162464 sqlite3VdbeAddOp2(v, OP_Null, 0, pRJ->regReturn);
162465 assert( pTab==pTabItem->pTab );
162468 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, 1);
162469 pInfo = sqlite3KeyInfoAlloc(pParse->db, 1, 0);
162471 pInfo->aColl[0] = 0;
162472 pInfo->aSortFlags[0] = 0;
162477 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRJ->iMatch, pPk->nKeyCol);
162480 pLoop->wsFlags &= ~WHERE_IDX_ONLY;
162484 pWInfo->nOBSat = 0;
162485 pWInfo->eDistinct = WHERE_DISTINCT_UNORDERED;
162488 pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
162489 if( db->mallocFailed ) goto whereBeginError;
162499 if( pParse->nErr ) goto whereBeginError;
162500 pLevel = &pWInfo->a[ii];
162501 wsFlags = pLevel->pWLoop->wsFlags;
162502 pSrc = &pTabList->a[pLevel->iFrom];
162503 if( pSrc->fg.isMaterialized ){
162504 if( pSrc->fg.isCorrelated ){
162505 sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
162508 sqlite3VdbeAddOp2(v, OP_Gosub, pSrc->regReturn, pSrc->addrFillSub);
162515 constructAutomaticIndex(pParse, &pWInfo->sWC,
162516 &pTabList->a[pLevel->iFrom], notReady, pLevel);
162521 if( db->mallocFailed ) goto whereBeginError;
162526 pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
162528 pWInfo->iContinue = pLevel->addrCont;
162535 VdbeModuleComment((v, "Begin WHERE-core"));
162536 pWInfo->iEndWhere = sqlite3VdbeCurrentAddr(v);
162542 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
162555 # define OpcodeRewriteTrace(D,K,P) /* no-op */
162563 if( (db->flags & SQLITE_VdbeAddopTrace)==0 ) return;
162575 VdbeOp *pOp = sqlite3VdbeGetOp(v,k--);
162576 if( pOp->p1!=iCur ) continue;
162577 if( pOp->opcode==OP_Close ) return 0;
162578 if( pOp->opcode==OP_OpenRead ) return 1;
162579 if( pOp->opcode==OP_OpenWrite ) return 1;
162580 if( pOp->opcode==OP_OpenDup ) return 1;
162581 if( pOp->opcode==OP_OpenAutoindex ) return 1;
162582 if( pOp->opcode==OP_OpenEphemeral ) return 1;
162593 Parse *pParse = pWInfo->pParse;
162594 Vdbe *v = pParse->pVdbe;
162598 SrcList *pTabList = pWInfo->pTabList;
162599 sqlite3 *db = pParse->db;
162605 VdbeModuleComment((v, "End WHERE-core"));
162606 for(i=pWInfo->nLevel-1; i>=0; i--){
162608 pLevel = &pWInfo->a[i];
162609 if( pLevel->pRJ ){
162612 WhereRightJoin *pRJ = pLevel->pRJ;
162613 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
162614 pLevel->addrCont = 0;
162615 pRJ->endSubrtn = sqlite3VdbeCurrentAddr(v);
162616 sqlite3VdbeAddOp3(v, OP_Return, pRJ->regReturn, pRJ->addrSubrtn, 1);
162620 pLoop = pLevel->pWLoop;
162621 if( pLevel->op!=OP_Noop ){
162626 if( pWInfo->eDistinct==WHERE_DISTINCT_ORDERED
162627 && i==pWInfo->nLevel-1 /* Ticket [ef9318757b152e3] 2017-10-21 */
162628 && (pLoop->wsFlags & WHERE_INDEXED)!=0
162629 && (pIdx = pLoop->u.btree.pIndex)->hasStat1
162630 && (n = pLoop->u.btree.nDistinctCol)>0
162631 && pIdx->aiRowLogEst[n]>=36
162633 int r1 = pParse->nMem+1;
162636 sqlite3VdbeAddOp3(v, OP_Column, pLevel->iIdxCur, j, r1+j);
162638 pParse->nMem += n+1;
162639 op = pLevel->op==OP_Prev ? OP_SeekLT : OP_SeekGT;
162640 addrSeek = sqlite3VdbeAddOp4Int(v, op, pLevel->iIdxCur, 0, r1, n);
162643 sqlite3VdbeAddOp2(v, OP_Goto, 1, pLevel->p2);
162647 if( pLevel->addrCont ) sqlite3VdbeResolveLabel(v, pLevel->addrCont);
162648 sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
162649 sqlite3VdbeChangeP5(v, pLevel->p5);
162651 VdbeCoverageIf(v, pLevel->op==OP_Next);
162652 VdbeCoverageIf(v, pLevel->op==OP_Prev);
162653 VdbeCoverageIf(v, pLevel->op==OP_VNext);
162654 if( pLevel->regBignull ){
162655 sqlite3VdbeResolveLabel(v, pLevel->addrBignull);
162656 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, pLevel->regBignull, pLevel->p2-1);
162662 }else if( pLevel->addrCont ){
162663 sqlite3VdbeResolveLabel(v, pLevel->addrCont);
162665 if( (pLoop->wsFlags & WHERE_IN_ABLE)!=0 && pLevel->u.in.nIn>0 ){
162668 sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
162669 for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
162670 assert( sqlite3VdbeGetOp(v, pIn->addrInTop+1)->opcode==OP_IsNull
162671 || pParse->db->mallocFailed );
162672 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
162673 if( pIn->eEndLoopOp!=OP_Noop ){
162674 if( pIn->nPrefix ){
162676 (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
162677 && (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0;
162678 if( pLevel->iLeftJoin ){
162679 /* For LEFT JOIN queries, cursor pIn->iCur may not have been
162684 ** return the null-row. So, if the cursor is not open yet,
162687 sqlite3VdbeAddOp2(v, OP_IfNotOpen, pIn->iCur,
162692 sqlite3VdbeAddOp4Int(v, OP_IfNoHope, pLevel->iIdxCur,
162694 pIn->iBase, pIn->nPrefix);
162700 sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
162703 sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
162705 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Prev);
162706 VdbeCoverageIf(v, pIn->eEndLoopOp==OP_Next);
162708 sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
162711 sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
162712 if( pLevel->pRJ ){
162713 sqlite3VdbeAddOp3(v, OP_Return, pLevel->pRJ->regReturn, 0, 1);
162716 if( pLevel->addrSkip ){
162717 sqlite3VdbeGoto(v, pLevel->addrSkip);
162718 VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
162719 sqlite3VdbeJumpHere(v, pLevel->addrSkip);
162720 sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
162723 if( pLevel->addrLikeRep ){
162724 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
162725 pLevel->addrLikeRep);
162729 if( pLevel->iLeftJoin ){
162730 int ws = pLoop->wsFlags;
162731 addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
162734 assert( pLevel->iTabCur==pTabList->a[pLevel->iFrom].iCursor );
162735 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iTabCur);
162738 || ((ws & WHERE_MULTI_OR) && pLevel->u.pCoveringIdx)
162741 Index *pIx = pLevel->u.pCoveringIdx;
162742 int iDb = sqlite3SchemaToIndex(db, pIx->pSchema);
162743 sqlite3VdbeAddOp3(v, OP_ReopenIdx, pLevel->iIdxCur, pIx->tnum, iDb);
162746 sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
162748 if( pLevel->op==OP_Return ){
162749 sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
162751 sqlite3VdbeGoto(v, pLevel->addrFirst);
162755 VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
162756 pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
162759 assert( pWInfo->nLevel<=pTabList->nSrc );
162760 for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
162764 SrcItem *pTabItem = &pTabList->a[pLevel->iFrom];
162765 Table *pTab = pTabItem->pTab;
162767 pLoop = pLevel->pWLoop;
162773 if( pLevel->pRJ ){
162778 /* For a co-routine, change all OP_Column references to the table of
162779 ** the co-routine into OP_Copy of result contained in a register.
162782 if( pTabItem->fg.viaCoroutine ){
162783 testcase( pParse->db->mallocFailed );
162784 translateColumnToCopy(pParse, pLevel->addrBody, pLevel->iTabCur,
162785 pTabItem->regResult, 0);
162800 if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
162801 pIdx = pLoop->u.btree.pIndex;
162802 }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
162803 pIdx = pLevel->u.pCoveringIdx;
162806 && !db->mallocFailed
162808 if( pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable) ){
162811 last = pWInfo->iEndWhere;
162813 if( pIdx->bHasExpr ){
162814 IndexedExpr *p = pParse->pIdxExpr;
162816 if( p->iIdxCur==pLevel->iIdxCur ){
162817 p->iDataCur = -1;
162818 p->iIdxCur = -1;
162820 p = p->pIENext;
162823 k = pLevel->addrBody + 1;
162825 if( db->flags & SQLITE_VdbeAddopTrace ){
162826 printf("TRANSLATE opcodes in range %d..%d\n", k, last-1);
162829 pOp = sqlite3VdbeGetOp(v, k - 1);
162830 assert( pOp->opcode!=OP_Column || pOp->p1!=pLevel->iTabCur );
162831 assert( pOp->opcode!=OP_Rowid || pOp->p1!=pLevel->iTabCur );
162832 assert( pOp->opcode!=OP_IfNullRow || pOp->p1!=pLevel->iTabCur );
162835 pLastOp = pOp + (last - k);
162838 if( pOp->p1!=pLevel->iTabCur ){
162839 /* no-op */
162840 }else if( pOp->opcode==OP_Column
162842 || pOp->opcode==OP_Offset
162845 int x = pOp->p2;
162846 assert( pIdx->pTable==pTab );
162848 if( pOp->opcode==OP_Offset ){
162854 x = pPk->aiColumn[x];
162862 pOp->p2 = x;
162863 pOp->p1 = pLevel->iIdxCur;
162867 ** reference. Verify that this is harmless - that the
162871 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
162872 || cursorIsOpen(v,pOp->p1,k)
162873 || pOp->opcode==OP_Offset
162876 assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
162877 || cursorIsOpen(v,pOp->p1,k)
162881 }else if( pOp->opcode==OP_Rowid ){
162882 pOp->p1 = pLevel->iIdxCur;
162883 pOp->opcode = OP_IdxRowid;
162885 }else if( pOp->opcode==OP_IfNullRow ){
162886 pOp->p1 = pLevel->iIdxCur;
162894 if( db->flags & SQLITE_VdbeAddopTrace ) printf("TRANSLATE complete\n");
162902 sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
162906 pParse->nQueryLoop = pWInfo->savedNQueryLoop;
162908 pParse->withinRJSubrtn -= nRJ;
162917 ** The author disclaims copyright to this source code. In place of
162957 ** the sub-query.
162962 ** select-list and ORDER BY expressions in the parent query are
162963 ** selected by the sub-query. For the purposes of the transformation,
162995 ** sub-query, which is always implemented as a co-routine. It then calls
163000 ** by the sub-query a sub-routine (OP_Gosub) coded by select.c is invoked.
163001 ** When the sub-routine is invoked:
163003 ** * The results of all window-functions for the row are stored
163015 ** BUILT-IN WINDOW FUNCTIONS
163017 ** This implementation features the following built-in window functions:
163031 ** These are the same built-in window functions supported by Postgres.
163034 ** be implemented using an API, built-in window functions are much more
163037 ** As such, some built-in window functions use the same API as aggregate
163048 ** As well as some of the built-in window functions, aggregate window
163055 ** Implementation of built-in window function row_number(). Assumes that the
163086 ** Implementation of built-in window function dense_rank(). Assumes that
163098 if( p ) p->nStep = 1;
163106 if( p->nStep ){
163107 p->nValue++;
163108 p->nStep = 0;
163110 sqlite3_result_int64(pCtx, p->nValue);
163115 ** Implementation of built-in window function nth_value(). This
163116 ** implementation is used in "slow mode" only - when the EXCLUDE clause
163147 p->nStep++;
163148 if( iVal==p->nStep ){
163149 p->pValue = sqlite3_value_dup(apArg[0]);
163150 if( !p->pValue ){
163161 pCtx, "second argument to nth_value must be a positive integer", -1
163167 if( p && p->pValue ){
163168 sqlite3_result_value(pCtx, p->pValue);
163169 sqlite3_value_free(p->pValue);
163170 p->pValue = 0;
163183 if( p && p->pValue==0 ){
163184 p->pValue = sqlite3_value_dup(apArg[0]);
163185 if( !p->pValue ){
163195 if( p && p->pValue ){
163196 sqlite3_result_value(pCtx, p->pValue);
163197 sqlite3_value_free(p->pValue);
163198 p->pValue = 0;
163205 ** Implementation of built-in window function rank(). Assumes that
163218 p->nStep++;
163219 if( p->nValue==0 ){
163220 p->nValue = p->nStep;
163230 sqlite3_result_int64(pCtx, p->nValue);
163231 p->nValue = 0;
163236 ** Implementation of built-in window function percent_rank(). Assumes that
163251 p->nTotal++;
163263 p->nStep++;
163269 p->nValue = p->nStep;
163270 if( p->nTotal>1 ){
163271 double r = (double)p->nValue / (double)(p->nTotal-1);
163281 ** Implementation of built-in window function cume_dist(). Assumes that
163296 p->nTotal++;
163308 p->nStep++;
163314 double r = (double)(p->nStep) / (double)(p->nTotal);
163344 if( p->nTotal==0 ){
163345 p->nParam = sqlite3_value_int64(apArg[0]);
163346 if( p->nParam<=0 ){
163348 pCtx, "argument of ntile must be a positive integer", -1
163352 p->nTotal++;
163364 p->iRow++;
163369 if( p && p->nParam>0 ){
163370 int nSize = (p->nTotal / p->nParam);
163372 sqlite3_result_int64(pCtx, p->iRow+1);
163374 i64 nLarge = p->nTotal - p->nParam*nSize;
163376 i64 iRow = p->iRow;
163378 assert( (nLarge*(nSize+1) + (p->nParam-nLarge)*nSize)==p->nTotal );
163383 sqlite3_result_int64(pCtx, 1 + nLarge + (iRow-iSmall)/nSize);
163410 sqlite3_value_free(p->pVal);
163411 p->pVal = sqlite3_value_dup(apArg[0]);
163412 if( p->pVal==0 ){
163415 p->nVal++;
163429 p->nVal--;
163430 if( p->nVal==0 ){
163431 sqlite3_value_free(p->pVal);
163432 p->pVal = 0;
163439 if( p && p->pVal ){
163440 sqlite3_result_value(pCtx, p->pVal);
163446 if( p && p->pVal ){
163447 sqlite3_result_value(pCtx, p->pVal);
163448 sqlite3_value_free(p->pVal);
163449 p->pVal = 0;
163454 ** Static names for the built-in window function names. These static
163459 ** if( pFuncDef->zName==row_valueName ){ ... }
163474 ** No-op implementations of xStep() and xFinalize(). Used as place-holders
163475 ** for built-in window functions that never call those interfaces.
163492 static void noopValueFunc(sqlite3_context *p){ UNUSED_PARAMETER(p); /*no-op*/ }
163503 ** no-op routines for their methods */
163521 ** Register those built-in window functions that are not also aggregates.
163546 for(p=pList; p; p=p->pNextWin){
163547 if( sqlite3StrICmp(p->zName, zName)==0 ) break;
163568 ** * If the function is a built-in window function that requires the
163569 ** window to be coerced (see "BUILT-IN WINDOW FUNCTIONS" at the top
163578 if( pWin->zName && pWin->eFrmType==0 ){
163579 Window *p = windowFind(pParse, pList, pWin->zName);
163581 pWin->pPartition = sqlite3ExprListDup(pParse->db, p->pPartition, 0);
163582 pWin->pOrderBy = sqlite3ExprListDup(pParse->db, p->pOrderBy, 0);
163583 pWin->pStart = sqlite3ExprDup(pParse->db, p->pStart, 0);
163584 pWin->pEnd = sqlite3ExprDup(pParse->db, p->pEnd, 0);
163585 pWin->eStart = p->eStart;
163586 pWin->eEnd = p->eEnd;
163587 pWin->eFrmType = p->eFrmType;
163588 pWin->eExclude = p->eExclude;
163592 if( (pWin->eFrmType==TK_RANGE)
163593 && (pWin->pStart || pWin->pEnd)
163594 && (pWin->pOrderBy==0 || pWin->pOrderBy->nExpr!=1)
163600 if( pFunc->funcFlags & SQLITE_FUNC_WINDOW ){
163601 sqlite3 *db = pParse->db;
163602 if( pWin->pFilter ){
163624 if( pFunc->zName==aUp[i].zFunc ){
163625 sqlite3ExprDelete(db, pWin->pStart);
163626 sqlite3ExprDelete(db, pWin->pEnd);
163627 pWin->pEnd = pWin->pStart = 0;
163628 pWin->eFrmType = aUp[i].eFrmType;
163629 pWin->eStart = aUp[i].eStart;
163630 pWin->eEnd = aUp[i].eEnd;
163631 pWin->eExclude = 0;
163632 if( pWin->eStart==TK_FOLLOWING ){
163633 pWin->pStart = sqlite3Expr(db, TK_INTEGER, "1");
163640 pWin->pWFunc = pFunc;
163653 Select *pSubSelect; /* Current sub-select, if any */
163658 ** this function appends to the output expression-list and updates
163662 struct WindowRewrite *p = pWalker->u.pRewrite;
163663 Parse *pParse = pWalker->pParse;
163665 assert( p->pWin!=0 );
163667 /* If this function is being called from within a scalar sub-select
163671 ** to the scalar sub-select. */
163672 if( p->pSubSelect ){
163673 if( pExpr->op!=TK_COLUMN ){
163676 int nSrc = p->pSrc->nSrc;
163679 if( pExpr->iTable==p->pSrc->a[i].iCursor ) break;
163685 switch( pExpr->op ){
163692 for(pWin=p->pWin; pWin; pWin=pWin->pNextWin){
163693 if( pExpr->y.pWin==pWin ){
163694 assert( pWin->pOwner==pExpr );
163703 int iCol = -1;
163704 if( pParse->db->mallocFailed ) return WRC_Abort;
163705 if( p->pSub ){
163707 for(i=0; i<p->pSub->nExpr; i++){
163708 if( 0==sqlite3ExprCompare(0, p->pSub->a[i].pExpr, pExpr, -1) ){
163715 Expr *pDup = sqlite3ExprDup(pParse->db, pExpr, 0);
163716 if( pDup && pDup->op==TK_AGG_FUNCTION ) pDup->op = TK_FUNCTION;
163717 p->pSub = sqlite3ExprListAppend(pParse, p->pSub, pDup);
163719 if( p->pSub ){
163720 int f = pExpr->flags & EP_Collate;
163723 sqlite3ExprDelete(pParse->db, pExpr);
163727 pExpr->op = TK_COLUMN;
163728 pExpr->iColumn = (iCol<0 ? p->pSub->nExpr-1: iCol);
163729 pExpr->iTable = p->pWin->iEphCsr;
163730 pExpr->y.pTab = p->pTab;
163731 pExpr->flags = f;
163733 if( pParse->db->mallocFailed ) return WRC_Abort;
163737 default: /* no-op */
163744 struct WindowRewrite *p = pWalker->u.pRewrite;
163745 Select *pSave = p->pSubSelect;
163749 p->pSubSelect = pSelect;
163751 p->pSubSelect = pSave;
163758 ** Iterate through each expression in expression-list pEList. For each:
163765 ** Append the node to output expression-list (*ppSub). And replace it
163766 ** with a TK_COLUMN that reads the (N-1)th element of table
163767 ** pWin->iEphCsr, where N is the number of elements in (*ppSub) after
163776 ExprList **ppSub /* IN/OUT: Sub-select expression-list */
163801 ** Append a copy of each expression in expression-list pAppend to
163812 int nInit = pList ? pList->nExpr : 0;
163813 for(i=0; i<pAppend->nExpr; i++){
163814 sqlite3 *db = pParse->db;
163815 Expr *pDup = sqlite3ExprDup(db, pAppend->a[i].pExpr, 0);
163816 if( db->mallocFailed ){
163825 pSub->op = TK_NULL;
163826 pSub->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
163827 pSub->u.zToken = 0;
163831 if( pList ) pList->a[nInit+i].fg.sortFlags = pAppend->a[i].fg.sortFlags;
163840 ** then we have to increase the Expr->op2 values of those nodes
163846 if( pExpr->op==TK_AGG_FUNCTION
163847 && pExpr->op2>=pWalker->walkerDepth
163849 pExpr->op2++;
163855 if( pExpr->op==TK_AGG_FUNCTION && pExpr->pAggInfo==0 ){
163857 sqlite3ErrorMsg(pWalker->pParse,
163858 "misuse of aggregate: %s()", pExpr->u.zToken);
163865 ** any SQL window functions, this function is a no-op. Otherwise, it
163872 if( p->pWin
163873 && p->pPrior==0
163874 && ALWAYS((p->selFlags & SF_WinRewrite)==0)
163878 sqlite3 *db = pParse->db;
163880 SrcList *pSrc = p->pSrc;
163881 Expr *pWhere = p->pWhere;
163882 ExprList *pGroupBy = p->pGroupBy;
163883 Expr *pHaving = p->pHaving;
163886 ExprList *pSublist = 0; /* Expression list for sub-query */
163887 Window *pMWin = p->pWin; /* Main window object */
163892 u32 selFlags = p->selFlags;
163900 if( (p->selFlags & SF_Aggregate)==0 ){
163903 sqlite3WalkExprList(&w, p->pOrderBy);
163906 p->pSrc = 0;
163907 p->pWhere = 0;
163908 p->pGroupBy = 0;
163909 p->pHaving = 0;
163910 p->selFlags &= ~SF_Aggregate;
163911 p->selFlags |= SF_WinRewrite;
163913 /* Create the ORDER BY clause for the sub-select. This is the concatenation
163916 pSort = exprListAppendList(pParse, 0, pMWin->pPartition, 1);
163917 pSort = exprListAppendList(pParse, pSort, pMWin->pOrderBy, 1);
163918 if( pSort && p->pOrderBy && p->pOrderBy->nExpr<=pSort->nExpr ){
163919 int nSave = pSort->nExpr;
163920 pSort->nExpr = p->pOrderBy->nExpr;
163921 if( sqlite3ExprListCompare(pSort, p->pOrderBy, -1)==0 ){
163922 sqlite3ExprListDelete(db, p->pOrderBy);
163923 p->pOrderBy = 0;
163925 pSort->nExpr = nSave;
163931 pMWin->iEphCsr = pParse->nTab++;
163932 pParse->nTab += 3;
163934 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pEList, pTab, &pSublist);
163935 selectWindowRewriteEList(pParse, pMWin, pSrc, p->pOrderBy, pTab, &pSublist);
163936 pMWin->nBufferCol = (pSublist ? pSublist->nExpr : 0);
163939 ** sub-select expression list. They are required to figure out where
163941 pSublist = exprListAppendList(pParse, pSublist, pMWin->pPartition, 0);
163942 pSublist = exprListAppendList(pParse, pSublist, pMWin->pOrderBy, 0);
163945 ** sub-select expression list. Also allocate two registers for each
163946 ** window function - one for the accumulator, another for interim
163948 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
163950 assert( ExprUseXList(pWin->pOwner) );
163951 assert( pWin->pWFunc!=0 );
163952 pArgs = pWin->pOwner->x.pList;
163953 if( pWin->pWFunc->funcFlags & SQLITE_FUNC_SUBTYPE ){
163955 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
163956 pWin->bExprArgs = 1;
163958 pWin->iArgCol = (pSublist ? pSublist->nExpr : 0);
163961 if( pWin->pFilter ){
163962 Expr *pFilter = sqlite3ExprDup(db, pWin->pFilter, 0);
163965 pWin->regAccum = ++pParse->nMem;
163966 pWin->regResult = ++pParse->nMem;
163967 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
163986 ("New window-function subquery in FROM clause of (%u/%p)\n",
163987 p->selId, p));
163988 p->pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
163989 assert( pSub!=0 || p->pSrc==0 ); /* Due to db->mallocFailed test inside
163992 if( p->pSrc ){
163994 p->pSrc->a[0].pSelect = pSub;
163995 sqlite3SrcListAssignCursors(pParse, p->pSrc);
163996 pSub->selFlags |= SF_Expanded|SF_OrderByReqd;
163998 pSub->selFlags |= (selFlags & SF_Aggregate);
164001 ** pParse->nErr will be set, so if SQLITE_NOMEM is set, we will get
164006 pTab->tabFlags |= TF_Ephemeral;
164007 p->pSrc->a[0].pTab = pTab;
164018 if( db->mallocFailed ) rc = SQLITE_NOMEM;
164022 ** result-set or ORDER BY clause of the SELECT statement p. */
164026 assert( rc==SQLITE_OK || pParse->nErr!=0 );
164035 if( p->ppThis ){
164036 *p->ppThis = p->pNextWin;
164037 if( p->pNextWin ) p->pNextWin->ppThis = p->ppThis;
164038 p->ppThis = 0;
164048 sqlite3ExprDelete(db, p->pFilter);
164049 sqlite3ExprListDelete(db, p->pPartition);
164050 sqlite3ExprListDelete(db, p->pOrderBy);
164051 sqlite3ExprDelete(db, p->pEnd);
164052 sqlite3ExprDelete(db, p->pStart);
164053 sqlite3DbFree(db, p->zName);
164054 sqlite3DbFree(db, p->zBase);
164064 Window *pNext = p->pNextWin;
164072 ** value should be a non-negative integer. If the value is not a
164073 ** constant, change it to NULL. The fact that it is then a non-negative
164080 sqlite3ExprDelete(pParse->db, pExpr);
164081 pExpr = sqlite3ExprAlloc(pParse->db, TK_NULL, 0, 0);
164136 pWin = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
164138 pWin->eFrmType = eType;
164139 pWin->eStart = eStart;
164140 pWin->eEnd = eEnd;
164141 if( eExclude==0 && OptimizationDisabled(pParse->db, SQLITE_WindowFunc) ){
164144 pWin->eExclude = eExclude;
164145 pWin->bImplicitFrame = bImplicitFrame;
164146 pWin->pEnd = sqlite3WindowOffsetExpr(pParse, pEnd);
164147 pWin->pStart = sqlite3WindowOffsetExpr(pParse, pStart);
164151 sqlite3ExprDelete(pParse->db, pEnd);
164152 sqlite3ExprDelete(pParse->db, pStart);
164158 ** pWin. Also, if parameter pBase is not NULL, set pWin->zBase to the
164159 ** equivalent nul-terminated string.
164169 pWin->pPartition = pPartition;
164170 pWin->pOrderBy = pOrderBy;
164172 pWin->zBase = sqlite3DbStrNDup(pParse->db, pBase->z, pBase->n);
164175 sqlite3ExprListDelete(pParse->db, pPartition);
164176 sqlite3ExprListDelete(pParse->db, pOrderBy);
164184 ** stored in the linked list starting at pWin->pNextWin. This function
164189 if( pWin->zBase ){
164190 sqlite3 *db = pParse->db;
164191 Window *pExist = windowFind(pParse, pList, pWin->zBase);
164195 if( pWin->pPartition ){
164197 }else if( pExist->pOrderBy && pWin->pOrderBy ){
164199 }else if( pExist->bImplicitFrame==0 ){
164204 "cannot override %s of window: %s", zErr, pWin->zBase
164207 pWin->pPartition = sqlite3ExprListDup(db, pExist->pPartition, 0);
164208 if( pExist->pOrderBy ){
164209 assert( pWin->pOrderBy==0 );
164210 pWin->pOrderBy = sqlite3ExprListDup(db, pExist->pOrderBy, 0);
164212 sqlite3DbFree(db, pWin->zBase);
164213 pWin->zBase = 0;
164224 assert( p->op==TK_FUNCTION );
164226 p->y.pWin = pWin;
164228 pWin->pOwner = p;
164229 if( (p->flags & EP_Distinct) && pWin->eFrmType!=TK_FILTER ){
164235 sqlite3WindowDelete(pParse->db, pWin);
164240 ** Possibly link window pWin into the list at pSel->pWin (window functions
164247 if( 0==pSel->pWin || 0==sqlite3WindowCompare(0, pSel->pWin, pWin, 0) ){
164248 pWin->pNextWin = pSel->pWin;
164249 if( pSel->pWin ){
164250 pSel->pWin->ppThis = &pWin->pNextWin;
164252 pSel->pWin = pWin;
164253 pWin->ppThis = &pSel->pWin;
164255 if( sqlite3ExprListCompare(pWin->pPartition, pSel->pWin->pPartition,-1) ){
164256 pSel->selFlags |= SF_MultiPart;
164275 if( p1->eFrmType!=p2->eFrmType ) return 1;
164276 if( p1->eStart!=p2->eStart ) return 1;
164277 if( p1->eEnd!=p2->eEnd ) return 1;
164278 if( p1->eExclude!=p2->eExclude ) return 1;
164279 if( sqlite3ExprCompare(pParse, p1->pStart, p2->pStart, -1) ) return 1;
164280 if( sqlite3ExprCompare(pParse, p1->pEnd, p2->pEnd, -1) ) return 1;
164281 if( (res = sqlite3ExprListCompare(p1->pPartition, p2->pPartition, -1)) ){
164284 if( (res = sqlite3ExprListCompare(p1->pOrderBy, p2->pOrderBy, -1)) ){
164288 if( (res = sqlite3ExprCompare(pParse, p1->pFilter, p2->pFilter, -1)) ){
164298 ** to begin iterating through the sub-query results. It is used to allocate
164302 int nEphExpr = pSelect->pSrc->a[0].pSelect->pEList->nExpr;
164303 Window *pMWin = pSelect->pWin;
164307 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pMWin->iEphCsr, nEphExpr);
164308 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+1, pMWin->iEphCsr);
164309 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+2, pMWin->iEphCsr);
164310 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->iEphCsr+3, pMWin->iEphCsr);
164314 if( pMWin->pPartition ){
164315 int nExpr = pMWin->pPartition->nExpr;
164316 pMWin->regPart = pParse->nMem+1;
164317 pParse->nMem += nExpr;
164318 sqlite3VdbeAddOp3(v, OP_Null, 0, pMWin->regPart, pMWin->regPart+nExpr-1);
164321 pMWin->regOne = ++pParse->nMem;
164322 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regOne);
164324 if( pMWin->eExclude ){
164325 pMWin->regStartRowid = ++pParse->nMem;
164326 pMWin->regEndRowid = ++pParse->nMem;
164327 pMWin->csrApp = pParse->nTab++;
164328 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
164329 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
164330 sqlite3VdbeAddOp2(v, OP_OpenDup, pMWin->csrApp, pMWin->iEphCsr);
164334 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
164335 FuncDef *p = pWin->pWFunc;
164336 if( (p->funcFlags & SQLITE_FUNC_MINMAX) && pWin->eStart!=TK_UNBOUNDED ){
164346 assert( ExprUseXList(pWin->pOwner) );
164347 pList = pWin->pOwner->x.pList;
164349 pWin->csrApp = pParse->nTab++;
164350 pWin->regApp = pParse->nMem+1;
164351 pParse->nMem += 3;
164352 if( pKeyInfo && pWin->pWFunc->zName[1]=='i' ){
164353 assert( pKeyInfo->aSortFlags[0]==0 );
164354 pKeyInfo->aSortFlags[0] = KEYINFO_ORDER_DESC;
164356 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pWin->csrApp, 2);
164358 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
164360 else if( p->zName==nth_valueName || p->zName==first_valueName ){
164361 /* Allocate two registers at pWin->regApp. These will be used to
164363 pWin->regApp = pParse->nMem+1;
164364 pWin->csrApp = pParse->nTab++;
164365 pParse->nMem += 2;
164366 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
164368 else if( p->zName==leadName || p->zName==lagName ){
164369 pWin->csrApp = pParse->nTab++;
164370 sqlite3VdbeAddOp2(v, OP_OpenDup, pWin->csrApp, pMWin->iEphCsr);
164385 ** code to check that the value is a non-negative integer and throws an
164390 "frame starting offset must be a non-negative integer",
164391 "frame ending offset must be a non-negative integer",
164393 "frame starting offset must be a non-negative number",
164394 "frame ending offset must be a non-negative number",
164432 ** Return the number of arguments passed to the window-function associated
164437 assert( ExprUseXList(pWin->pOwner) );
164438 pList = pWin->pOwner->x.pList;
164439 return (pList ? pList->nExpr : 0);
164462 ** in an array of accumulator registers - one for each window function
164469 ** order to reduce memory requirements - it would always be safe just
164484 ** Consider a window-frame similar to the following:
164504 ** Depending on the window-frame in question, all three cursors may not
164532 Window *pMWin = p->pMWin;
164533 ExprList *pOrderBy = pMWin->pOrderBy;
164535 Vdbe *v = sqlite3GetVdbe(p->pParse);
164536 ExprList *pPart = pMWin->pPartition;
164537 int iColOff = pMWin->nBufferCol + (pPart ? pPart->nExpr : 0);
164539 for(i=0; i<pOrderBy->nExpr; i++){
164547 ** xInverse (if bInverse is non-zero) for each window function in the
164548 ** linked list starting at pMWin. Or, for built-in window functions
164559 ** already populated with all columns from the current row of the sub-query.
164561 ** If argument regPartSize is non-zero, then it is a register containing the
164571 Parse *pParse = p->pParse;
164574 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
164575 FuncDef *pFunc = pWin->pWFunc;
164577 int nArg = pWin->bExprArgs ? 0 : windowArgCount(pWin);
164580 assert( bInverse==0 || pWin->eStart!=TK_UNBOUNDED );
164587 if( i!=1 || pFunc->zName!=nth_valueName ){
164588 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+i, reg+i);
164590 sqlite3VdbeAddOp3(v, OP_Column, pMWin->iEphCsr, pWin->iArgCol+i, reg+i);
164595 if( pMWin->regStartRowid==0
164596 && (pFunc->funcFlags & SQLITE_FUNC_MINMAX)
164597 && (pWin->eStart!=TK_UNBOUNDED)
164602 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1, 1);
164603 sqlite3VdbeAddOp2(v, OP_SCopy, regArg, pWin->regApp);
164604 sqlite3VdbeAddOp3(v, OP_MakeRecord, pWin->regApp, 2, pWin->regApp+2);
164605 sqlite3VdbeAddOp2(v, OP_IdxInsert, pWin->csrApp, pWin->regApp+2);
164607 sqlite3VdbeAddOp4Int(v, OP_SeekGE, pWin->csrApp, 0, regArg, 1);
164609 sqlite3VdbeAddOp1(v, OP_Delete, pWin->csrApp);
164610 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
164613 }else if( pWin->regApp ){
164614 assert( pFunc->zName==nth_valueName
164615 || pFunc->zName==first_valueName
164618 sqlite3VdbeAddOp2(v, OP_AddImm, pWin->regApp+1-bInverse, 1);
164619 }else if( pFunc->xSFunc!=noopStepFunc ){
164621 if( pWin->pFilter ){
164623 assert( ExprUseXList(pWin->pOwner) );
164624 assert( pWin->bExprArgs || !nArg ||nArg==pWin->pOwner->x.pList->nExpr );
164625 assert( pWin->bExprArgs || nArg ||pWin->pOwner->x.pList==0 );
164627 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol+nArg,regTmp);
164633 if( pWin->bExprArgs ){
164637 assert( ExprUseXList(pWin->pOwner) );
164638 nArg = pWin->pOwner->x.pList->nExpr;
164640 sqlite3ExprCodeExprList(pParse, pWin->pOwner->x.pList, regArg, 0, 0);
164644 if( pOp->opcode==OP_Column && pOp->p1==pMWin->iEphCsr ){
164645 pOp->p1 = csr;
164649 if( pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
164652 assert( ExprUseXList(pWin->pOwner) );
164653 pColl = sqlite3ExprNNCollSeq(pParse, pWin->pOwner->x.pList->a[0].pExpr);
164657 bInverse, regArg, pWin->regAccum);
164660 if( pWin->bExprArgs ){
164678 ** pMWin. Or, for built-in window-functions that do not use the standard
164682 Parse *pParse = p->pParse;
164683 Window *pMWin = p->pMWin;
164687 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
164688 if( pMWin->regStartRowid==0
164689 && (pWin->pWFunc->funcFlags & SQLITE_FUNC_MINMAX)
164690 && (pWin->eStart!=TK_UNBOUNDED)
164692 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
164693 sqlite3VdbeAddOp1(v, OP_Last, pWin->csrApp);
164695 sqlite3VdbeAddOp3(v, OP_Column, pWin->csrApp, 0, pWin->regResult);
164696 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
164697 }else if( pWin->regApp ){
164698 assert( pMWin->regStartRowid==0 );
164702 sqlite3VdbeAddOp2(v, OP_AggFinal, pWin->regAccum, nArg);
164703 sqlite3VdbeAppendP4(v, pWin->pWFunc, P4_FUNCDEF);
164704 sqlite3VdbeAddOp2(v, OP_Copy, pWin->regAccum, pWin->regResult);
164705 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
164707 sqlite3VdbeAddOp3(v, OP_AggValue,pWin->regAccum,nArg,pWin->regResult);
164708 sqlite3VdbeAppendP4(v, pWin->pWFunc, P4_FUNCDEF);
164716 ** p->pMWin list by doing a full scan of the current window frame. Store the
164722 Parse *pParse = p->pParse;
164723 Window *pMWin = p->pMWin;
164724 Vdbe *v = p->pVdbe;
164740 csr = pMWin->csrApp;
164741 nPeer = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
164753 sqlite3VdbeAddOp2(v, OP_Rowid, pMWin->iEphCsr, regCRowid);
164754 windowReadPeerValues(p, pMWin->iEphCsr, regCPeer);
164756 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
164757 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
164760 sqlite3VdbeAddOp3(v, OP_SeekGE, csr, lblBrk, pMWin->regStartRowid);
164764 sqlite3VdbeAddOp3(v, OP_Gt, pMWin->regEndRowid, lblBrk, regRowid);
164767 if( pMWin->eExclude==TK_CURRENT ){
164770 }else if( pMWin->eExclude!=TK_NO ){
164775 if( pMWin->pOrderBy ){
164776 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pMWin->pOrderBy, 0, 0);
164778 if( pMWin->eExclude==TK_TIES ){
164795 windowAggStep(p, pMWin, csr, 0, p->regArg);
164800 sqlite3VdbeJumpHere(v, addrNext-1);
164814 ** Invoke the sub-routine at regGosub (generated by code in select.c) to
164818 ** for per-row processing is only generated for the following built-in window
164827 Window *pMWin = p->pMWin;
164828 Vdbe *v = p->pVdbe;
164830 if( pMWin->regStartRowid ){
164833 Parse *pParse = p->pParse;
164836 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
164837 FuncDef *pFunc = pWin->pWFunc;
164838 assert( ExprUseXList(pWin->pOwner) );
164839 if( pFunc->zName==nth_valueName
164840 || pFunc->zName==first_valueName
164842 int csr = pWin->csrApp;
164845 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
164847 if( pFunc->zName==nth_valueName ){
164848 sqlite3VdbeAddOp3(v, OP_Column,pMWin->iEphCsr,pWin->iArgCol+1,tmpReg);
164853 sqlite3VdbeAddOp3(v, OP_Add, tmpReg, pWin->regApp, tmpReg);
164854 sqlite3VdbeAddOp3(v, OP_Gt, pWin->regApp+1, lbl, tmpReg);
164858 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
164862 else if( pFunc->zName==leadName || pFunc->zName==lagName ){
164863 int nArg = pWin->pOwner->x.pList->nExpr;
164864 int csr = pWin->csrApp;
164867 int iEph = pMWin->iEphCsr;
164870 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regResult);
164872 sqlite3VdbeAddOp3(v, OP_Column, iEph,pWin->iArgCol+2,pWin->regResult);
164876 int val = (pFunc->zName==leadName ? 1 : -1);
164879 int op = (pFunc->zName==leadName ? OP_Add : OP_Subtract);
164881 sqlite3VdbeAddOp3(v, OP_Column, iEph, pWin->iArgCol+1, tmpReg2);
164888 sqlite3VdbeAddOp3(v, OP_Column, csr, pWin->iArgCol, pWin->regResult);
164894 sqlite3VdbeAddOp2(v, OP_Gosub, p->regGosub, p->addrGosub);
164900 ** any equivalent initialization required by any built-in window functions
164908 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
164909 FuncDef *pFunc = pWin->pWFunc;
164910 assert( pWin->regAccum );
164911 sqlite3VdbeAddOp2(v, OP_Null, 0, pWin->regAccum);
164913 if( pMWin->regStartRowid==0 ){
164914 if( pFunc->zName==nth_valueName || pFunc->zName==first_valueName ){
164915 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp);
164916 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
164919 if( (pFunc->funcFlags & SQLITE_FUNC_MINMAX) && pWin->csrApp ){
164920 assert( pWin->eStart!=TK_UNBOUNDED );
164921 sqlite3VdbeAddOp1(v, OP_ResetSorter, pWin->csrApp);
164922 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWin->regApp+1);
164926 regArg = pParse->nMem+1;
164927 pParse->nMem += nArg;
164937 if( pMWin->regStartRowid ) return 1;
164938 for(pWin=pMWin; pWin; pWin=pWin->pNextWin){
164939 FuncDef *pFunc = pWin->pWFunc;
164940 if( (pFunc->zName==nth_valueName)
164941 || (pFunc->zName==first_valueName)
164942 || (pFunc->zName==leadName)
164943 || (pFunc->zName==lagName)
164953 ** pOrderBy->nExpr. This function generates code to compare the two
164970 int nVal = pOrderBy->nExpr;
164978 sqlite3VdbeAddOp3(v, OP_Copy, regNew, regOld, nVal-1);
164993 ** operator in the above pseudo-code is replaced with ">" or "<=", respectively.
164995 ** If the sort-order for the ORDER BY term in the window is DESC, then the
164997 ** subtracted. And the comparison operator is inverted to - ">=" becomes "<=",
165001 ** if( csr1.peerVal - regVal <= csr2.peerVal ) goto lbl;
165011 int regVal, /* Register containing non-negative number */
165015 Parse *pParse = p->pParse;
165017 ExprList *pOrderBy = p->pMWin->pOrderBy; /* ORDER BY clause for window */
165020 int regString = ++pParse->nMem; /* Reg. for constant value '' */
165026 /* Read the peer-value from each cursor into a register */
165031 assert( pOrderBy && pOrderBy->nExpr==1 );
165032 if( pOrderBy->a[0].fg.sortFlags & KEYINFO_ORDER_DESC ){
165042 reg1, (arith==OP_Add ? "+" : "-"), regVal,
165065 if( pOrderBy->a[0].fg.sortFlags & KEYINFO_ORDER_BIGNULL ){
165080 default: assert( op==OP_Lt ); /* no-op */ break;
165091 /* Register reg1 currently contains csr1.peerVal (the peer-value from csr1).
165094 ** then leave reg1 as it is. In pseudo-code, this is implemented as:
165097 ** reg1 = reg1 +/- regVal
165100 ** Since all strings and blobs are greater-than-or-equal-to an empty string,
165117 pColl = sqlite3ExprNNCollSeq(pParse, pOrderBy->a[0].pExpr);
165146 Parse *pParse = p->pParse;
165147 Window *pMWin = p->pMWin;
165149 Vdbe *v = p->pVdbe;
165151 int bPeer = (pMWin->eFrmType!=TK_ROWS);
165156 /* Special case - WINDOW_AGGINVERSE is always a no-op if the frame
165158 if( op==WINDOW_AGGINVERSE && pMWin->eStart==TK_UNBOUNDED ){
165164 if( pMWin->eFrmType==TK_RANGE ){
165168 if( pMWin->eStart==TK_FOLLOWING ){
165170 p, OP_Le, p->current.csr, regCountdown, p->start.csr, lblDone
165174 p, OP_Ge, p->start.csr, regCountdown, p->current.csr, lblDone
165179 p, OP_Gt, p->end.csr, regCountdown, p->current.csr, lblDone
165188 if( op==WINDOW_RETURN_ROW && pMWin->regStartRowid==0 ){
165199 if( pMWin->eStart==pMWin->eEnd && regCountdown
165200 && pMWin->eFrmType==TK_RANGE
165205 sqlite3VdbeAddOp2(v, OP_Rowid, p->start.csr, regRowid1);
165206 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid2);
165209 }else if( p->regRowid ){
165210 sqlite3VdbeAddOp2(v, OP_Rowid, p->end.csr, regRowid1);
165211 sqlite3VdbeAddOp3(v, OP_Ge, p->regRowid, lblDone, regRowid1);
165216 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING );
165221 csr = p->current.csr;
165222 reg = p->current.reg;
165227 csr = p->start.csr;
165228 reg = p->start.reg;
165229 if( pMWin->regStartRowid ){
165230 assert( pMWin->regEndRowid );
165231 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regStartRowid, 1);
165233 windowAggStep(p, pMWin, csr, 1, p->regArg);
165239 csr = p->end.csr;
165240 reg = p->end.reg;
165241 if( pMWin->regStartRowid ){
165242 assert( pMWin->regEndRowid );
165243 sqlite3VdbeAddOp2(v, OP_AddImm, pMWin->regEndRowid, 1);
165245 windowAggStep(p, pMWin, csr, 0, p->regArg);
165250 if( op==p->eDelete ){
165268 int nReg = (pMWin->pOrderBy ? pMWin->pOrderBy->nExpr : 0);
165271 windowIfNewPeer(pParse, pMWin->pOrderBy, regTmp, reg, addrContinue);
165293 pNew->zName = sqlite3DbStrDup(db, p->zName);
165294 pNew->zBase = sqlite3DbStrDup(db, p->zBase);
165295 pNew->pFilter = sqlite3ExprDup(db, p->pFilter, 0);
165296 pNew->pWFunc = p->pWFunc;
165297 pNew->pPartition = sqlite3ExprListDup(db, p->pPartition, 0);
165298 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, 0);
165299 pNew->eFrmType = p->eFrmType;
165300 pNew->eEnd = p->eEnd;
165301 pNew->eStart = p->eStart;
165302 pNew->eExclude = p->eExclude;
165303 pNew->regResult = p->regResult;
165304 pNew->regAccum = p->regAccum;
165305 pNew->iArgCol = p->iArgCol;
165306 pNew->iEphCsr = p->iEphCsr;
165307 pNew->bExprArgs = p->bExprArgs;
165308 pNew->pStart = sqlite3ExprDup(db, p->pStart, 0);
165309 pNew->pEnd = sqlite3ExprDup(db, p->pEnd, 0);
165310 pNew->pOwner = pOwner;
165311 pNew->bImplicitFrame = p->bImplicitFrame;
165326 for(pWin=p; pWin; pWin=pWin->pNextWin){
165329 pp = &((*pp)->pNextWin);
165345 sqlite3 *db = pParse->db;
165347 sqlite3ValueFromExpr(db, pExpr, db->enc, SQLITE_AFF_NUMERIC, &pVal);
165359 ** and invoke the sub-routine at instruction addrGosub once for each row.
165389 ** if( (regEnd--)<=0 ){
165391 ** if( (regStart--)<=0 ){
165402 ** if( (regStart--)<=0 ){
165408 ** The pseudo-code above uses the following shorthand:
165423 ** differently from the above - "BETWEEN <expr> PRECEDING AND <expr> PRECEDING"
165442 ** if( (regEnd--)<=0 ){
165446 ** if( (regStart--)<=0 ){
165452 ** if( (regEnd--)<=0 ){
165468 ** regStart = regEnd - <expr1>
165471 ** if( (regEnd--)<=0 ){
165474 ** if( (regStart--)<=0 ){
165482 ** if( (regEnd--)<=0 ){
165486 ** if( (regStart--)<=0 ){
165498 ** This is optimized of course - branches that will never be taken and
165519 ** if( (regStart--)<=0 ){
165535 ** To handle this case, the pseudo-code programs depicted above are modified
165555 ** of the outer loop - the one started by sqlite3WhereBegin().
165697 Window *pMWin = p->pWin;
165698 ExprList *pOrderBy = pMWin->pOrderBy;
165701 int csrInput = p->pSrc->a[0].iCursor; /* Cursor of sub-select */
165702 int nInput = p->pSrc->a[0].pTab->nCol; /* Number of cols returned by sub */
165713 WindowCodeArg s; /* Context object for sub-routines */
165718 assert( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_CURRENT
165719 || pMWin->eStart==TK_FOLLOWING || pMWin->eStart==TK_UNBOUNDED
165721 assert( pMWin->eEnd==TK_FOLLOWING || pMWin->eEnd==TK_CURRENT
165722 || pMWin->eEnd==TK_UNBOUNDED || pMWin->eEnd==TK_PRECEDING
165724 assert( pMWin->eExclude==0 || pMWin->eExclude==TK_CURRENT
165725 || pMWin->eExclude==TK_GROUP || pMWin->eExclude==TK_TIES
165726 || pMWin->eExclude==TK_NO
165738 s.current.csr = pMWin->iEphCsr;
165744 ** are four options - they may never be deleted (eDelete==0), they may
165749 switch( pMWin->eStart ){
165751 if( pMWin->eFrmType!=TK_RANGE
165752 && windowExprGtZero(pParse, pMWin->pStart)
165759 if( pMWin->eEnd==TK_PRECEDING ){
165760 if( pMWin->eFrmType!=TK_RANGE
165761 && windowExprGtZero(pParse, pMWin->pEnd)
165775 /* Allocate registers for the array of values from the sub-query, the
165778 regNew = pParse->nMem+1;
165779 pParse->nMem += nInput;
165780 regRecord = ++pParse->nMem;
165781 s.regRowid = ++pParse->nMem;
165786 if( pMWin->eStart==TK_PRECEDING || pMWin->eStart==TK_FOLLOWING ){
165787 regStart = ++pParse->nMem;
165789 if( pMWin->eEnd==TK_PRECEDING || pMWin->eEnd==TK_FOLLOWING ){
165790 regEnd = ++pParse->nMem;
165796 if( pMWin->eFrmType!=TK_ROWS ){
165797 int nPeer = (pOrderBy ? pOrderBy->nExpr : 0);
165798 regNewPeer = regNew + pMWin->nBufferCol;
165799 if( pMWin->pPartition ) regNewPeer += pMWin->pPartition->nExpr;
165800 regPeer = pParse->nMem+1; pParse->nMem += nPeer;
165801 s.start.reg = pParse->nMem+1; pParse->nMem += nPeer;
165802 s.current.reg = pParse->nMem+1; pParse->nMem += nPeer;
165803 s.end.reg = pParse->nMem+1; pParse->nMem += nPeer;
165806 /* Load the column values for the row returned by the sub-select
165819 if( pMWin->pPartition ){
165821 ExprList *pPart = pMWin->pPartition;
165822 int nPart = pPart->nExpr;
165823 int regNewPart = regNew + pMWin->nBufferCol;
165826 regFlushPart = ++pParse->nMem;
165827 addr = sqlite3VdbeAddOp3(v, OP_Compare, regNewPart, pMWin->regPart, nPart);
165833 sqlite3VdbeAddOp3(v, OP_Copy, regNewPart, pMWin->regPart, nPart-1);
165839 addrNe = sqlite3VdbeAddOp3(v, OP_Ne, pMWin->regOne, 0, s.regRowid);
165846 sqlite3ExprCode(pParse, pMWin->pStart, regStart);
165847 windowCheckValue(pParse, regStart, 0 + (pMWin->eFrmType==TK_RANGE?3:0));
165850 sqlite3ExprCode(pParse, pMWin->pEnd, regEnd);
165851 windowCheckValue(pParse, regEnd, 1 + (pMWin->eFrmType==TK_RANGE?3:0));
165854 if( pMWin->eFrmType!=TK_RANGE && pMWin->eStart==pMWin->eEnd && regStart ){
165855 int op = ((pMWin->eStart==TK_FOLLOWING) ? OP_Ge : OP_Le);
165867 if( pMWin->eStart==TK_FOLLOWING && pMWin->eFrmType!=TK_RANGE && regEnd ){
165868 assert( pMWin->eEnd==TK_FOLLOWING );
165872 if( pMWin->eStart!=TK_UNBOUNDED ){
165881 sqlite3VdbeAddOp3(v, OP_Copy, regNewPeer, regPeer, pOrderBy->nExpr-1);
165882 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.start.reg, pOrderBy->nExpr-1);
165883 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.current.reg, pOrderBy->nExpr-1);
165884 sqlite3VdbeAddOp3(v, OP_Copy, regPeer, s.end.reg, pOrderBy->nExpr-1);
165895 if( pMWin->eStart==TK_FOLLOWING ){
165897 if( pMWin->eEnd!=TK_UNBOUNDED ){
165898 if( pMWin->eFrmType==TK_RANGE ){
165912 if( pMWin->eEnd==TK_PRECEDING ){
165913 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
165921 if( pMWin->eEnd!=TK_UNBOUNDED ){
165922 if( pMWin->eFrmType==TK_RANGE ){
165952 if( pMWin->pPartition ){
165960 if( pMWin->eEnd==TK_PRECEDING ){
165961 int bRPS = (pMWin->eStart==TK_PRECEDING && pMWin->eFrmType==TK_RANGE);
165965 }else if( pMWin->eStart==TK_FOLLOWING ){
165971 if( pMWin->eFrmType==TK_RANGE ){
165976 if( pMWin->eEnd==TK_UNBOUNDED ){
165981 assert( pMWin->eEnd==TK_FOLLOWING );
166006 if( pMWin->pPartition ){
166007 if( pMWin->regStartRowid ){
166008 sqlite3VdbeAddOp2(v, OP_Integer, 1, pMWin->regStartRowid);
166009 sqlite3VdbeAddOp2(v, OP_Integer, 0, pMWin->regEndRowid);
166021 ** source file "parse.y". */
166023 ** 2001-09-15
166025 ** The author disclaims copyright to this source code. In place of
166035 ** The canonical source code to this file ("parse.y") is a Lemon grammar
166037 ** That input file is processed by Lemon to generate a C-language
166039 ** this comment as part of the translated C-code. Edits should be made
166046 ** Disable all error recovery processing in the parser push-down
166099 sqlite3 *db = pParse->db;
166100 pParse->disableLookaside++;
166120 sqlite3ExprListDelete(pParse->db, pOrderBy);
166121 sqlite3ExprDelete(pParse->db, pLimit);
166127 ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
166133 if( p->pPrior ){
166137 pLoop->pNext = pNext;
166138 pLoop->selFlags |= SF_Compound;
166140 pLoop = pLoop->pPrior;
166143 if( pLoop->pOrderBy || pLoop->pLimit ){
166145 pLoop->pOrderBy!=0 ? "ORDER BY" : "LIMIT",
166146 sqlite3SelectOpName(pNext->op));
166150 if( (p->selFlags & SF_MultiValue)==0 &&
166151 (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
166164 pSelect->pWith = pWith;
166167 sqlite3WithDelete(pParse->db, pWith);
166175 Expr *p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr)+t.n+1);
166178 p->op = (u8)op;
166179 p->affExpr = 0;
166180 p->flags = EP_Leaf;
166182 /* p->iAgg = -1; // Not required */
166183 p->pLeft = p->pRight = 0;
166184 p->pAggInfo = 0;
166185 memset(&p->x, 0, sizeof(p->x));
166186 memset(&p->y, 0, sizeof(p->y));
166187 p->op2 = 0;
166188 p->iTable = 0;
166189 p->iColumn = 0;
166190 p->u.zToken = (char*)&p[1];
166191 memcpy(p->u.zToken, t.z, t.n);
166192 p->u.zToken[t.n] = 0;
166193 p->w.iOfst = (int)(t.z - pParse->zTail);
166194 if( sqlite3Isquote(p->u.zToken[0]) ){
166198 p->nHeight = 1;
166211 sqlite3 *db = pParse->db;
166212 if( pA && pY && pY->op==TK_NULL && !IN_RENAME_OBJECT ){
166213 pA->op = (u8)op;
166214 sqlite3ExprDelete(db, pA->pRight);
166215 pA->pRight = 0;
166233 && pParse->db->init.busy==0
166236 pIdToken->n, pIdToken->z);
166439 ** that represent terminal and non-terminal symbols.
166445 ** (also known as: "terminal symbols") have fall-back
166449 ** YYACTIONTYPE is the data type used for "action codes" - numbers
166454 ** value associated with a terminal or non-terminal
166457 ** Each non-terminal can have a different minor type.
166479 ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
166480 ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
166483 ** YY_NO_ACTION The yy_action[] code for no-op
166529 #define sqlite3ParserCTX_FETCH Parse *pParse=yypParser->pParse;
166530 #define sqlite3ParserCTX_STORE yypParser->pParse=pParse;
166547 /* Define the yytestcase() macro to be a no-op if is not already defined
166572 ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
166581 ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
166594 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
166606 ** shifting non-terminals after a reduce.
167118 #define YY_REDUCE_MIN (-271)
167121 /* 0 */ -125, 733, 789, 241, 293, -123, -193, -191, -183, -187,
167122 /* 10 */ 166, 238, 133, -207, -199, -267, -176, -6, 204, 489,
167123 /* 20 */ 576, -175, 598, 686, 615, 725, 860, 778, 781, 857,
167124 /* 30 */ 616, 887, 87, 240, -192, 408, 626, 796, 843, 854,
167125 /* 40 */ 1003, -271, -271, -271, -271, -271, -271, -271, -271, -271,
167126 /* 50 */ -271, -271, -271, -271, -271, -271, -271, -271, -271, -271,
167127 /* 60 */ -271, -271, -271, -271, -271, -271, -271, -271, -271, -271,
167128 /* 70 */ -271, -271, -271, -271, -271, -271, -271, -271, 80, 83,
167134 /* 130 */ -271, -271, -271, -271, -271, -271, -271, -271, -271, -271,
167135 /* 140 */ -271, 138, 459, 396, -158, 470, 302, -212, 521, 201,
167136 /* 150 */ -195, -92, 559, 630, 632, 630, -271, 632, 901, 63,
167137 /* 160 */ 407, -271, -271, -271, -271, 161, 161, 161, 251, 335,
167138 /* 170 */ 847, 960, 980, 537, 588, 618, 628, 688, 688, -166,
167139 /* 180 */ -161, 674, 790, 794, 799, 851, 852, -122, 680, -120,
167142 /* 210 */ 362, 994, 1139, 1005, 1037, 1202, 1205, 1195, 1210, -194,
167143 /* 220 */ 56, 185, -135, 232, 522, 560, 601, 617, 669, 683,
167223 /********** End of lemon-generated parsing tables *****************************/
167446 YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
167449 YYMINORTYPE minor; /* The user-supplied minor token value. This
167459 int yyhwm; /* High-water mark of the stack */
168259 newSize = p->yystksz*2 + 100;
168260 idx = p->yytos ? (int)(p->yytos - p->yystack) : 0;
168261 if( p->yystack==&p->yystk0 ){
168263 if( pNew ) pNew[0] = p->yystk0;
168265 pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
168268 p->yystack = pNew;
168269 p->yytos = &p->yystack[idx];
168273 yyTracePrompt, p->yystksz, newSize);
168276 p->yystksz = newSize;
168297 yypParser->yyhwm = 0;
168300 yypParser->yytos = NULL;
168301 yypParser->yystack = NULL;
168302 yypParser->yystksz = 0;
168304 yypParser->yystack = &yypParser->yystk0;
168305 yypParser->yystksz = 1;
168309 yypParser->yyerrcnt = -1;
168311 yypParser->yytos = yypParser->yystack;
168312 yypParser->yystack[0].stateno = 0;
168313 yypParser->yystack[0].major = 0;
168315 yypParser->yystackEnd = &yypParser->yystack[YYSTACKDEPTH-1];
168360 ** terminal or non-terminal is destroyed. This can happen
168375 sqlite3SelectDelete(pParse->db, (yypminor->yy47));
168390 sqlite3ExprDelete(pParse->db, (yypminor->yy528));
168407 sqlite3ExprListDelete(pParse->db, (yypminor->yy322));
168416 sqlite3SrcListDelete(pParse->db, (yypminor->yy131));
168421 sqlite3WithDelete(pParse->db, (yypminor->yy521));
168427 sqlite3WindowListDelete(pParse->db, (yypminor->yy41));
168433 sqlite3IdListDelete(pParse->db, (yypminor->yy254));
168442 sqlite3WindowDelete(pParse->db, (yypminor->yy41));
168448 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy33));
168453 sqlite3IdListDelete(pParse->db, (yypminor->yy180).b);
168460 sqlite3ExprDelete(pParse->db, (yypminor->yy595).pExpr);
168476 assert( pParser->yytos!=0 );
168477 assert( pParser->yytos > pParser->yystack );
168478 yytos = pParser->yytos--;
168483 yyTokenName[yytos->major]);
168486 yy_destructor(pParser, yytos->major, &yytos->minor);
168494 while( pParser->yytos>pParser->yystack ) yy_pop_parser_stack(pParser);
168496 if( pParser->yystack!=&pParser->yystk0 ) free(pParser->yystack);
168527 return pParser->yyhwm;
168533 ** is in state X and has a lookahead token Y. In a well-tested
168570 ** look-ahead token iLookAhead.
168573 YYCODETYPE iLookAhead, /* The look-ahead token */
168611 int j = i - iLookAhead + YYWILDCARD;
168634 ** Find the appropriate action for a parser given the non-terminal
168635 ** look-ahead token iLookAhead.
168639 YYCODETYPE iLookAhead /* The look-ahead token */
168674 while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
168693 yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
168697 yyTracePrompt, zTag, yyTokenName[yypParser->yytos->major],
168698 yyNewState - YY_MIN_REDUCE);
168716 yypParser->yytos++;
168718 if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
168719 yypParser->yyhwm++;
168720 assert( yypParser->yyhwm == (int)(yypParser->yytos - yypParser->yystack) );
168724 if( yypParser->yytos>yypParser->yystackEnd ){
168725 yypParser->yytos--;
168730 if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz] ){
168732 yypParser->yytos--;
168739 yyNewState += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
168741 yytos = yypParser->yytos;
168742 yytos->stateno = yyNewState;
168743 yytos->major = yyMajor;
168744 yytos->minor.yy0 = yyMinor;
168748 /* For rule J, yyRuleInfoLhs[J] contains the symbol on the left-hand side
169159 ** of symbols on the right-hand side of that rule. */
169161 -1, /* (0) explain ::= EXPLAIN */
169162 -3, /* (1) explain ::= EXPLAIN QUERY PLAN */
169163 -1, /* (2) cmdx ::= cmd */
169164 -3, /* (3) cmd ::= BEGIN transtype trans_opt */
169166 -1, /* (5) transtype ::= DEFERRED */
169167 -1, /* (6) transtype ::= IMMEDIATE */
169168 -1, /* (7) transtype ::= EXCLUSIVE */
169169 -2, /* (8) cmd ::= COMMIT|END trans_opt */
169170 -2, /* (9) cmd ::= ROLLBACK trans_opt */
169171 -2, /* (10) cmd ::= SAVEPOINT nm */
169172 -3, /* (11) cmd ::= RELEASE savepoint_opt nm */
169173 -5, /* (12) cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
169174 -6, /* (13) create_table ::= createkw temp TABLE ifnotexists nm dbnm */
169175 -1, /* (14) createkw ::= CREATE */
169177 -3, /* (16) ifnotexists ::= IF NOT EXISTS */
169178 -1, /* (17) temp ::= TEMP */
169180 -5, /* (19) create_table_args ::= LP columnlist conslist_opt RP table_option_set */
169181 -2, /* (20) create_table_args ::= AS select */
169183 -3, /* (22) table_option_set ::= table_option_set COMMA table_option */
169184 -2, /* (23) table_option ::= WITHOUT nm */
169185 -1, /* (24) table_option ::= nm */
169186 -2, /* (25) columnname ::= nm typetoken */
169188 -4, /* (27) typetoken ::= typename LP signed RP */
169189 -6, /* (28) typetoken ::= typename LP signed COMMA signed RP */
169190 -2, /* (29) typename ::= typename ID|STRING */
169193 -2, /* (32) ccons ::= CONSTRAINT nm */
169194 -3, /* (33) ccons ::= DEFAULT scantok term */
169195 -4, /* (34) ccons ::= DEFAULT LP expr RP */
169196 -4, /* (35) ccons ::= DEFAULT PLUS scantok term */
169197 -4, /* (36) ccons ::= DEFAULT MINUS scantok term */
169198 -3, /* (37) ccons ::= DEFAULT scantok ID|INDEXED */
169199 -3, /* (38) ccons ::= NOT NULL onconf */
169200 -5, /* (39) ccons ::= PRIMARY KEY sortorder onconf autoinc */
169201 -2, /* (40) ccons ::= UNIQUE onconf */
169202 -4, /* (41) ccons ::= CHECK LP expr RP */
169203 -4, /* (42) ccons ::= REFERENCES nm eidlist_opt refargs */
169204 -1, /* (43) ccons ::= defer_subclause */
169205 -2, /* (44) ccons ::= COLLATE ID|STRING */
169206 -3, /* (45) generated ::= LP expr RP */
169207 -4, /* (46) generated ::= LP expr RP ID */
169209 -1, /* (48) autoinc ::= AUTOINCR */
169211 -2, /* (50) refargs ::= refargs refarg */
169212 -2, /* (51) refarg ::= MATCH nm */
169213 -3, /* (52) refarg ::= ON INSERT refact */
169214 -3, /* (53) refarg ::= ON DELETE refact */
169215 -3, /* (54) refarg ::= ON UPDATE refact */
169216 -2, /* (55) refact ::= SET NULL */
169217 -2, /* (56) refact ::= SET DEFAULT */
169218 -1, /* (57) refact ::= CASCADE */
169219 -1, /* (58) refact ::= RESTRICT */
169220 -2, /* (59) refact ::= NO ACTION */
169221 -3, /* (60) defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
169222 -2, /* (61) defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
169224 -2, /* (63) init_deferred_pred_opt ::= INITIALLY DEFERRED */
169225 -2, /* (64) init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
169227 -1, /* (66) tconscomma ::= COMMA */
169228 -2, /* (67) tcons ::= CONSTRAINT nm */
169229 -7, /* (68) tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
169230 -5, /* (69) tcons ::= UNIQUE LP sortlist RP onconf */
169231 -5, /* (70) tcons ::= CHECK LP expr RP onconf */
169232-10, /* (71) tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclaus…
169235 -3, /* (74) onconf ::= ON CONFLICT resolvetype */
169237 -2, /* (76) orconf ::= OR resolvetype */
169238 -1, /* (77) resolvetype ::= IGNORE */
169239 -1, /* (78) resolvetype ::= REPLACE */
169240 -4, /* (79) cmd ::= DROP TABLE ifexists fullname */
169241 -2, /* (80) ifexists ::= IF EXISTS */
169243 -9, /* (82) cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
169244 -4, /* (83) cmd ::= DROP VIEW ifexists fullname */
169245 -1, /* (84) cmd ::= select */
169246 -3, /* (85) select ::= WITH wqlist selectnowith */
169247 -4, /* (86) select ::= WITH RECURSIVE wqlist selectnowith */
169248 -1, /* (87) select ::= selectnowith */
169249 -3, /* (88) selectnowith ::= selectnowith multiselect_op oneselect */
169250 -1, /* (89) multiselect_op ::= UNION */
169251 -2, /* (90) multiselect_op ::= UNION ALL */
169252 -1, /* (91) multiselect_op ::= EXCEPT|INTERSECT */
169253-9, /* (92) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderb…
169254-10, /* (93) oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt windo…
169255 -4, /* (94) values ::= VALUES LP nexprlist RP */
169256 -5, /* (95) values ::= values COMMA LP nexprlist RP */
169257 -1, /* (96) distinct ::= DISTINCT */
169258 -1, /* (97) distinct ::= ALL */
169261 -5, /* (100) selcollist ::= sclp scanpt expr scanpt as */
169262 -3, /* (101) selcollist ::= sclp scanpt STAR */
169263 -5, /* (102) selcollist ::= sclp scanpt nm DOT STAR */
169264 -2, /* (103) as ::= AS nm */
169267 -2, /* (106) from ::= FROM seltablist */
169268 -2, /* (107) stl_prefix ::= seltablist joinop */
169270 -5, /* (109) seltablist ::= stl_prefix nm dbnm as on_using */
169271 -6, /* (110) seltablist ::= stl_prefix nm dbnm as indexed_by on_using */
169272 -8, /* (111) seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_using */
169273 -6, /* (112) seltablist ::= stl_prefix LP select RP as on_using */
169274 -6, /* (113) seltablist ::= stl_prefix LP seltablist RP as on_using */
169276 -2, /* (115) dbnm ::= DOT nm */
169277 -1, /* (116) fullname ::= nm */
169278 -3, /* (117) fullname ::= nm DOT nm */
169279 -1, /* (118) xfullname ::= nm */
169280 -3, /* (119) xfullname ::= nm DOT nm */
169281 -5, /* (120) xfullname ::= nm DOT nm AS nm */
169282 -3, /* (121) xfullname ::= nm AS nm */
169283 -1, /* (122) joinop ::= COMMA|JOIN */
169284 -2, /* (123) joinop ::= JOIN_KW JOIN */
169285 -3, /* (124) joinop ::= JOIN_KW nm JOIN */
169286 -4, /* (125) joinop ::= JOIN_KW nm nm JOIN */
169287 -2, /* (126) on_using ::= ON expr */
169288 -4, /* (127) on_using ::= USING LP idlist RP */
169291 -3, /* (130) indexed_by ::= INDEXED BY nm */
169292 -2, /* (131) indexed_by ::= NOT INDEXED */
169294 -3, /* (133) orderby_opt ::= ORDER BY sortlist */
169295 -5, /* (134) sortlist ::= sortlist COMMA expr sortorder nulls */
169296 -3, /* (135) sortlist ::= expr sortorder nulls */
169297 -1, /* (136) sortorder ::= ASC */
169298 -1, /* (137) sortorder ::= DESC */
169300 -2, /* (139) nulls ::= NULLS FIRST */
169301 -2, /* (140) nulls ::= NULLS LAST */
169304 -3, /* (143) groupby_opt ::= GROUP BY nexprlist */
169306 -2, /* (145) having_opt ::= HAVING expr */
169308 -2, /* (147) limit_opt ::= LIMIT expr */
169309 -4, /* (148) limit_opt ::= LIMIT expr OFFSET expr */
169310 -4, /* (149) limit_opt ::= LIMIT expr COMMA expr */
169311 -6, /* (150) cmd ::= with DELETE FROM xfullname indexed_opt where_opt_ret */
169313 -2, /* (152) where_opt ::= WHERE expr */
169315 -2, /* (154) where_opt_ret ::= WHERE expr */
169316 -2, /* (155) where_opt_ret ::= RETURNING selcollist */
169317 -4, /* (156) where_opt_ret ::= WHERE expr RETURNING selcollist */
169318 -9, /* (157) cmd ::= with UPDATE orconf xfullname indexed_opt SET setlist from where_opt_ret */
169319 -5, /* (158) setlist ::= setlist COMMA nm EQ expr */
169320 -7, /* (159) setlist ::= setlist COMMA LP idlist RP EQ expr */
169321 -3, /* (160) setlist ::= nm EQ expr */
169322 -5, /* (161) setlist ::= LP idlist RP EQ expr */
169323 -7, /* (162) cmd ::= with insert_cmd INTO xfullname idlist_opt select upsert */
169324 -8, /* (163) cmd ::= with insert_cmd INTO xfullname idlist_opt DEFAULT VALUES returning */
169326 -2, /* (165) upsert ::= RETURNING selcollist */
169327-12, /* (166) upsert ::= ON CONFLICT LP sortlist RP where_opt DO UPDATE SET setlist where_opt ups…
169328 -9, /* (167) upsert ::= ON CONFLICT LP sortlist RP where_opt DO NOTHING upsert */
169329 -5, /* (168) upsert ::= ON CONFLICT DO NOTHING returning */
169330 -8, /* (169) upsert ::= ON CONFLICT DO UPDATE SET setlist where_opt returning */
169331 -2, /* (170) returning ::= RETURNING selcollist */
169332 -2, /* (171) insert_cmd ::= INSERT orconf */
169333 -1, /* (172) insert_cmd ::= REPLACE */
169335 -3, /* (174) idlist_opt ::= LP idlist RP */
169336 -3, /* (175) idlist ::= idlist COMMA nm */
169337 -1, /* (176) idlist ::= nm */
169338 -3, /* (177) expr ::= LP expr RP */
169339 -1, /* (178) expr ::= ID|INDEXED */
169340 -1, /* (179) expr ::= JOIN_KW */
169341 -3, /* (180) expr ::= nm DOT nm */
169342 -5, /* (181) expr ::= nm DOT nm DOT nm */
169343 -1, /* (182) term ::= NULL|FLOAT|BLOB */
169344 -1, /* (183) term ::= STRING */
169345 -1, /* (184) term ::= INTEGER */
169346 -1, /* (185) expr ::= VARIABLE */
169347 -3, /* (186) expr ::= expr COLLATE ID|STRING */
169348 -6, /* (187) expr ::= CAST LP expr AS typetoken RP */
169349 -5, /* (188) expr ::= ID|INDEXED LP distinct exprlist RP */
169350 -4, /* (189) expr ::= ID|INDEXED LP STAR RP */
169351 -6, /* (190) expr ::= ID|INDEXED LP distinct exprlist RP filter_over */
169352 -5, /* (191) expr ::= ID|INDEXED LP STAR RP filter_over */
169353 -1, /* (192) term ::= CTIME_KW */
169354 -5, /* (193) expr ::= LP nexprlist COMMA expr RP */
169355 -3, /* (194) expr ::= expr AND expr */
169356 -3, /* (195) expr ::= expr OR expr */
169357 -3, /* (196) expr ::= expr LT|GT|GE|LE expr */
169358 -3, /* (197) expr ::= expr EQ|NE expr */
169359 -3, /* (198) expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */
169360 -3, /* (199) expr ::= expr PLUS|MINUS expr */
169361 -3, /* (200) expr ::= expr STAR|SLASH|REM expr */
169362 -3, /* (201) expr ::= expr CONCAT expr */
169363 -2, /* (202) likeop ::= NOT LIKE_KW|MATCH */
169364 -3, /* (203) expr ::= expr likeop expr */
169365 -5, /* (204) expr ::= expr likeop expr ESCAPE expr */
169366 -2, /* (205) expr ::= expr ISNULL|NOTNULL */
169367 -3, /* (206) expr ::= expr NOT NULL */
169368 -3, /* (207) expr ::= expr IS expr */
169369 -4, /* (208) expr ::= expr IS NOT expr */
169370 -6, /* (209) expr ::= expr IS NOT DISTINCT FROM expr */
169371 -5, /* (210) expr ::= expr IS DISTINCT FROM expr */
169372 -2, /* (211) expr ::= NOT expr */
169373 -2, /* (212) expr ::= BITNOT expr */
169374 -2, /* (213) expr ::= PLUS|MINUS expr */
169375 -3, /* (214) expr ::= expr PTR expr */
169376 -1, /* (215) between_op ::= BETWEEN */
169377 -2, /* (216) between_op ::= NOT BETWEEN */
169378 -5, /* (217) expr ::= expr between_op expr AND expr */
169379 -1, /* (218) in_op ::= IN */
169380 -2, /* (219) in_op ::= NOT IN */
169381 -5, /* (220) expr ::= expr in_op LP exprlist RP */
169382 -3, /* (221) expr ::= LP select RP */
169383 -5, /* (222) expr ::= expr in_op LP select RP */
169384 -5, /* (223) expr ::= expr in_op nm dbnm paren_exprlist */
169385 -4, /* (224) expr ::= EXISTS LP select RP */
169386 -5, /* (225) expr ::= CASE case_operand case_exprlist case_else END */
169387 -5, /* (226) case_exprlist ::= case_exprlist WHEN expr THEN expr */
169388 -4, /* (227) case_exprlist ::= WHEN expr THEN expr */
169389 -2, /* (228) case_else ::= ELSE expr */
169391 -1, /* (230) case_operand ::= expr */
169394 -3, /* (233) nexprlist ::= nexprlist COMMA expr */
169395 -1, /* (234) nexprlist ::= expr */
169397 -3, /* (236) paren_exprlist ::= LP exprlist RP */
169398-12, /* (237) cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_op…
169399 -1, /* (238) uniqueflag ::= UNIQUE */
169402 -3, /* (241) eidlist_opt ::= LP eidlist RP */
169403 -5, /* (242) eidlist ::= eidlist COMMA nm collate sortorder */
169404 -3, /* (243) eidlist ::= nm collate sortorder */
169406 -2, /* (245) collate ::= COLLATE ID|STRING */
169407 -4, /* (246) cmd ::= DROP INDEX ifexists fullname */
169408 -2, /* (247) cmd ::= VACUUM vinto */
169409 -3, /* (248) cmd ::= VACUUM nm vinto */
169410 -2, /* (249) vinto ::= INTO expr */
169412 -3, /* (251) cmd ::= PRAGMA nm dbnm */
169413 -5, /* (252) cmd ::= PRAGMA nm dbnm EQ nmnum */
169414 -6, /* (253) cmd ::= PRAGMA nm dbnm LP nmnum RP */
169415 -5, /* (254) cmd ::= PRAGMA nm dbnm EQ minus_num */
169416 -6, /* (255) cmd ::= PRAGMA nm dbnm LP minus_num RP */
169417 -2, /* (256) plus_num ::= PLUS INTEGER|FLOAT */
169418 -2, /* (257) minus_num ::= MINUS INTEGER|FLOAT */
169419 -5, /* (258) cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
169420-11, /* (259) trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON ful…
169421 -1, /* (260) trigger_time ::= BEFORE|AFTER */
169422 -2, /* (261) trigger_time ::= INSTEAD OF */
169424 -1, /* (263) trigger_event ::= DELETE|INSERT */
169425 -1, /* (264) trigger_event ::= UPDATE */
169426 -3, /* (265) trigger_event ::= UPDATE OF idlist */
169428 -2, /* (267) when_clause ::= WHEN expr */
169429 -3, /* (268) trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
169430 -2, /* (269) trigger_cmd_list ::= trigger_cmd SEMI */
169431 -3, /* (270) trnm ::= nm DOT nm */
169432 -3, /* (271) tridxby ::= INDEXED BY nm */
169433 -2, /* (272) tridxby ::= NOT INDEXED */
169434 -9, /* (273) trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist from where_opt scanpt */
169435 -8, /* (274) trigger_cmd ::= scanpt insert_cmd INTO trnm idlist_opt select upsert scanpt */
169436 -6, /* (275) trigger_cmd ::= DELETE FROM trnm tridxby where_opt scanpt */
169437 -3, /* (276) trigger_cmd ::= scanpt select scanpt */
169438 -4, /* (277) expr ::= RAISE LP IGNORE RP */
169439 -6, /* (278) expr ::= RAISE LP raisetype COMMA nm RP */
169440 -1, /* (279) raisetype ::= ROLLBACK */
169441 -1, /* (280) raisetype ::= ABORT */
169442 -1, /* (281) raisetype ::= FAIL */
169443 -4, /* (282) cmd ::= DROP TRIGGER ifexists fullname */
169444 -6, /* (283) cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
169445 -3, /* (284) cmd ::= DETACH database_kw_opt expr */
169447 -2, /* (286) key_opt ::= KEY expr */
169448 -1, /* (287) cmd ::= REINDEX */
169449 -3, /* (288) cmd ::= REINDEX nm dbnm */
169450 -1, /* (289) cmd ::= ANALYZE */
169451 -3, /* (290) cmd ::= ANALYZE nm dbnm */
169452 -6, /* (291) cmd ::= ALTER TABLE fullname RENAME TO nm */
169453 -7, /* (292) cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
169454 -6, /* (293) cmd ::= ALTER TABLE fullname DROP kwcolumn_opt nm */
169455 -1, /* (294) add_column_fullname ::= fullname */
169456 -8, /* (295) cmd ::= ALTER TABLE fullname RENAME kwcolumn_opt nm TO nm */
169457 -1, /* (296) cmd ::= create_vtab */
169458 -4, /* (297) cmd ::= create_vtab LP vtabarglist RP */
169459 -8, /* (298) create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
169461 -1, /* (300) vtabargtoken ::= ANY */
169462 -3, /* (301) vtabargtoken ::= lp anylist RP */
169463 -1, /* (302) lp ::= LP */
169464 -2, /* (303) with ::= WITH wqlist */
169465 -3, /* (304) with ::= WITH RECURSIVE wqlist */
169466 -1, /* (305) wqas ::= AS */
169467 -2, /* (306) wqas ::= AS MATERIALIZED */
169468 -3, /* (307) wqas ::= AS NOT MATERIALIZED */
169469 -6, /* (308) wqitem ::= nm eidlist_opt wqas LP select RP */
169470 -1, /* (309) wqlist ::= wqitem */
169471 -3, /* (310) wqlist ::= wqlist COMMA wqitem */
169472 -1, /* (311) windowdefn_list ::= windowdefn */
169473 -3, /* (312) windowdefn_list ::= windowdefn_list COMMA windowdefn */
169474 -5, /* (313) windowdefn ::= nm AS LP window RP */
169475 -5, /* (314) window ::= PARTITION BY nexprlist orderby_opt frame_opt */
169476 -6, /* (315) window ::= nm PARTITION BY nexprlist orderby_opt frame_opt */
169477 -4, /* (316) window ::= ORDER BY sortlist frame_opt */
169478 -5, /* (317) window ::= nm ORDER BY sortlist frame_opt */
169479 -1, /* (318) window ::= frame_opt */
169480 -2, /* (319) window ::= nm frame_opt */
169482 -3, /* (321) frame_opt ::= range_or_rows frame_bound_s frame_exclude_opt */
169483-6, /* (322) frame_opt ::= range_or_rows BETWEEN frame_bound_s AND frame_bound_e frame_exclude_op…
169484 -1, /* (323) range_or_rows ::= RANGE|ROWS|GROUPS */
169485 -1, /* (324) frame_bound_s ::= frame_bound */
169486 -2, /* (325) frame_bound_s ::= UNBOUNDED PRECEDING */
169487 -1, /* (326) frame_bound_e ::= frame_bound */
169488 -2, /* (327) frame_bound_e ::= UNBOUNDED FOLLOWING */
169489 -2, /* (328) frame_bound ::= expr PRECEDING|FOLLOWING */
169490 -2, /* (329) frame_bound ::= CURRENT ROW */
169492 -2, /* (331) frame_exclude_opt ::= EXCLUDE frame_exclude */
169493 -2, /* (332) frame_exclude ::= NO OTHERS */
169494 -2, /* (333) frame_exclude ::= CURRENT ROW */
169495 -1, /* (334) frame_exclude ::= GROUP|TIES */
169496 -2, /* (335) window_clause ::= WINDOW windowdefn_list */
169497 -2, /* (336) filter_over ::= filter_clause over_clause */
169498 -1, /* (337) filter_over ::= over_clause */
169499 -1, /* (338) filter_over ::= filter_clause */
169500 -4, /* (339) over_clause ::= OVER LP window RP */
169501 -2, /* (340) over_clause ::= OVER nm */
169502 -5, /* (341) filter_clause ::= FILTER LP WHERE expr RP */
169503 -1, /* (342) input ::= cmdlist */
169504 -2, /* (343) cmdlist ::= cmdlist ecmd */
169505 -1, /* (344) cmdlist ::= ecmd */
169506 -1, /* (345) ecmd ::= SEMI */
169507 -2, /* (346) ecmd ::= cmdx SEMI */
169508 -3, /* (347) ecmd ::= explain cmdx SEMI */
169510 -1, /* (349) trans_opt ::= TRANSACTION */
169511 -2, /* (350) trans_opt ::= TRANSACTION nm */
169512 -1, /* (351) savepoint_opt ::= SAVEPOINT */
169514 -2, /* (353) cmd ::= create_table create_table_args */
169515 -1, /* (354) table_option_set ::= table_option */
169516 -4, /* (355) columnlist ::= columnlist COMMA columnname carglist */
169517 -2, /* (356) columnlist ::= columnname carglist */
169518 -1, /* (357) nm ::= ID|INDEXED */
169519 -1, /* (358) nm ::= STRING */
169520 -1, /* (359) nm ::= JOIN_KW */
169521 -1, /* (360) typetoken ::= typename */
169522 -1, /* (361) typename ::= ID|STRING */
169523 -1, /* (362) signed ::= plus_num */
169524 -1, /* (363) signed ::= minus_num */
169525 -2, /* (364) carglist ::= carglist ccons */
169527 -2, /* (366) ccons ::= NULL onconf */
169528 -4, /* (367) ccons ::= GENERATED ALWAYS AS generated */
169529 -2, /* (368) ccons ::= AS generated */
169530 -2, /* (369) conslist_opt ::= COMMA conslist */
169531 -3, /* (370) conslist ::= conslist tconscomma tcons */
169532 -1, /* (371) conslist ::= tcons */
169534 -1, /* (373) defer_subclause_opt ::= defer_subclause */
169535 -1, /* (374) resolvetype ::= raisetype */
169536 -1, /* (375) selectnowith ::= oneselect */
169537 -1, /* (376) oneselect ::= values */
169538 -2, /* (377) sclp ::= selcollist COMMA */
169539 -1, /* (378) as ::= ID|STRING */
169540 -1, /* (379) indexed_opt ::= indexed_by */
169542 -1, /* (381) expr ::= term */
169543 -1, /* (382) likeop ::= LIKE_KW|MATCH */
169544 -1, /* (383) exprlist ::= nexprlist */
169545 -1, /* (384) nmnum ::= plus_num */
169546 -1, /* (385) nmnum ::= nm */
169547 -1, /* (386) nmnum ::= ON */
169548 -1, /* (387) nmnum ::= DELETE */
169549 -1, /* (388) nmnum ::= DEFAULT */
169550 -1, /* (389) plus_num ::= INTEGER|FLOAT */
169552 -3, /* (391) foreach_clause ::= FOR EACH ROW */
169553 -1, /* (392) trnm ::= nm */
169555 -1, /* (394) database_kw_opt ::= DATABASE */
169558 -1, /* (397) kwcolumn_opt ::= COLUMNKW */
169559 -1, /* (398) vtabarglist ::= vtabarg */
169560 -3, /* (399) vtabarglist ::= vtabarglist COMMA vtabarg */
169561 -2, /* (400) vtabarg ::= vtabarg vtabargtoken */
169563 -4, /* (402) anylist ::= anylist LP anylist RP */
169564 -2, /* (403) anylist ::= anylist ANY */
169577 ** only called from one place, optimizing compilers will in-line it, which
169594 yymsp = yypParser->yytos;
169608 { pParse->explain = 1; }
169611 { pParse->explain = 2; }
169617 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy394);}
169626 {yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-X*/}
169630 {sqlite3EndTransaction(pParse,yymsp[-1].major);}
169649 …sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy394,0,0,yymsp[
169666 {yymsp[-2].minor.yy394 = 1;}
169669 {yymsp[0].minor.yy394 = pParse->db->init.busy==0;}
169673 sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy285,0);
169679 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy47);
169686 {yylhsminor.yy285 = yymsp[-2].minor.yy285|yymsp[0].minor.yy285;}
169687 yymsp[-2].minor.yy285 = yylhsminor.yy285;
169692 yymsp[-1].minor.yy285 = TF_WithoutRowid | TF_NoVisibleRowid;
169694 yymsp[-1].minor.yy285 = 0;
169711 {sqlite3AddColumn(pParse,yymsp[-1].minor.yy0,yymsp[0].minor.yy0);}
169720 …yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
169725 …yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
169729 {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
169745 {pParse->constraintName = yymsp[0].minor.yy0;}
169748 …te3AddDefaultValue(pParse,yymsp[0].minor.yy528,yymsp[-1].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[
169751 {sqlite3AddDefaultValue(pParse,yymsp[-1].minor.yy528,yymsp[-2].minor.yy0.z+1,yymsp[0].minor.yy0.z);}
169754 …te3AddDefaultValue(pParse,yymsp[0].minor.yy528,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[
169759 …sqlite3AddDefaultValue(pParse,p,yymsp[-2].minor.yy0.z,&yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n…
169767 testcase( p->op==TK_TRUEFALSE && sqlite3ExprTruthValue(p) );
169776 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy394,yymsp[0].minor.yy394,yymsp[-2].minor.yy394);}
169783 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy528,yymsp[-2].minor.yy0.z,yymsp[0].minor.yy0.z)…
169786 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy322,yymsp[0].minor.yy394);}
169795 {sqlite3AddGenerated(pParse,yymsp[-1].minor.yy528,0);}
169798 {sqlite3AddGenerated(pParse,yymsp[-2].minor.yy528,&yymsp[0].minor.yy0);}
169804 { yymsp[1].minor.yy394 = OE_None*0x0101; /* EV: R-19803-45884 */}
169807 { yymsp[-1].minor.yy394 = (yymsp[-1].minor.yy394 & ~yymsp[0].minor.yy231.mask) | yymsp[0].minor.yy2…
169810 { yymsp[-1].minor.yy231.value = 0; yymsp[-1].minor.yy231.mask = 0x000000; }
169813 { yymsp[-2].minor.yy231.value = 0; yymsp[-2].minor.yy231.mask = 0x000000; }
169816 { yymsp[-2].minor.yy231.value = yymsp[0].minor.yy394; yymsp[-2].minor.yy231.mask = 0x0000ff; }
169819 { yymsp[-2].minor.yy231.value = yymsp[0].minor.yy394<<8; yymsp[-2].minor.yy231.mask = 0x00ff00; }
169822 { yymsp[-1].minor.yy394 = OE_SetNull; /* EV: R-33326-45252 */}
169825 { yymsp[-1].minor.yy394 = OE_SetDflt; /* EV: R-33326-45252 */}
169828 { yymsp[0].minor.yy394 = OE_Cascade; /* EV: R-33326-45252 */}
169831 { yymsp[0].minor.yy394 = OE_Restrict; /* EV: R-33326-45252 */}
169834 { yymsp[-1].minor.yy394 = OE_None; /* EV: R-33326-45252 */}
169837 {yymsp[-2].minor.yy394 = 0;}
169842 {yymsp[-1].minor.yy394 = yymsp[0].minor.yy394;}
169849 {yymsp[-1].minor.yy394 = 1;}
169852 {yymsp[-1].minor.yy394 = 0;}
169855 {pParse->constraintName.n = 0;}
169858 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy322,yymsp[0].minor.yy394,yymsp[-2].minor.yy394,0);}
169861 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy322,yymsp[0].minor.yy394,0,0,0,0,
169865 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy528,yymsp[-3].minor.yy0.z,yymsp[-1].minor.yy0.z…
169869 …sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy322, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322…
169878 {yymsp[-2].minor.yy394 = yymsp[0].minor.yy394;}
169889 sqlite3DropTable(pParse, yymsp[0].minor.yy131, 0, yymsp[-1].minor.yy394);
169894 …e, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy322, yymsp[…
169899 sqlite3DropTable(pParse, yymsp[0].minor.yy131, 1, yymsp[-1].minor.yy394);
169906 sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy47);
169910 {yymsp[-2].minor.yy47 = attachWithToSelect(pParse,yymsp[0].minor.yy47,yymsp[-1].minor.yy521);}
169913 {yymsp[-3].minor.yy47 = attachWithToSelect(pParse,yymsp[0].minor.yy47,yymsp[-1].minor.yy521);}
169921 yymsp[0].minor.yy47 = p; /*A-overwrites-X*/
169927 Select *pLhs = yymsp[-2].minor.yy47;
169928 if( pRhs && pRhs->pPrior ){
169937 pRhs->op = (u8)yymsp[-1].minor.yy394;
169938 pRhs->pPrior = pLhs;
169939 if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
169940 pRhs->selFlags &= ~SF_MultiValue;
169941 if( yymsp[-1].minor.yy394!=TK_ALL ) pParse->hasCompound = 1;
169943 sqlite3SelectDelete(pParse->db, pLhs);
169945 yymsp[-2].minor.yy47 = pRhs;
169950 {yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-OP*/}
169953 {yymsp[-1].minor.yy394 = TK_ALL;}
169957-8].minor.yy47 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy322,yymsp[-5].minor.yy131,yymsp[-4].min…
169962-9].minor.yy47 = sqlite3SelectNew(pParse,yymsp[-7].minor.yy322,yymsp[-6].minor.yy131,yymsp[-5].min…
169963 if( yymsp[-9].minor.yy47 ){
169964 yymsp[-9].minor.yy47->pWinDefn = yymsp[-2].minor.yy41;
169966 sqlite3WindowListDelete(pParse->db, yymsp[-2].minor.yy41);
169972 yymsp[-3].minor.yy47 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values,0);
169977 Select *pRight, *pLeft = yymsp[-4].minor.yy47;
169978 pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy322,0,0,0,0,0,SF_Values|SF_MultiValue,0);
169979 if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
169981 pRight->op = TK_ALL;
169982 pRight->pPrior = pLeft;
169983 yymsp[-4].minor.yy47 = pRight;
169985 yymsp[-4].minor.yy47 = pLeft;
170005 …yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[-2].minor.yy528…
170006 …if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy322, &yymsp[0].minor…
170007 sqlite3ExprListSetSpan(pParse,yymsp[-4].minor.yy322,yymsp[-3].minor.yy522,yymsp[-1].minor.yy522);
170012 Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
170013 yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy322, p);
170019 Expr *pLeft = tokenExpr(pParse, TK_ID, yymsp[-2].minor.yy0);
170021 yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, pDot);
170028 {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
170036 yymsp[-1].minor.yy131 = yymsp[0].minor.yy131;
170037 sqlite3SrcListShiftJoinType(pParse,yymsp[-1].minor.yy131);
170042 …if( ALWAYS(yymsp[-1].minor.yy131 && yymsp[-1].minor.yy131->nSrc>0) ) yymsp[-1].minor.yy131->a[yyms…
170047 …yymsp[-4].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-4].minor.yy131,&yymsp[-3].minor…
170052 …yymsp[-5].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy131,&yymsp[-4].minor…
170053 sqlite3SrcListIndexedBy(pParse, yymsp[-5].minor.yy131, &yymsp[-1].minor.yy0);
170058 …yymsp[-7].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-7].minor.yy131,&yymsp[-6].minor…
170059 sqlite3SrcListFuncArgs(pParse, yymsp[-7].minor.yy131, yymsp[-3].minor.yy322);
170064 …yymsp[-5].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy131,0,0,&yymsp[-1].m…
170069 …if( yymsp[-5].minor.yy131==0 && yymsp[-1].minor.yy0.n==0 && yymsp[0].minor.yy561.pOn==0 && yymsp[0…
170070 yymsp[-5].minor.yy131 = yymsp[-3].minor.yy131;
170071 }else if( yymsp[-3].minor.yy131->nSrc==1 ){
170072 …yymsp[-5].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy131,0,0,&yymsp[-1].m…
170073 if( yymsp[-5].minor.yy131 ){
170074 SrcItem *pNew = &yymsp[-5].minor.yy131->a[yymsp[-5].minor.yy131->nSrc-1];
170075 SrcItem *pOld = yymsp[-3].minor.yy131->a;
170076 pNew->zName = pOld->zName;
170077 pNew->zDatabase = pOld->zDatabase;
170078 pNew->pSelect = pOld->pSelect;
170079 if( pNew->pSelect && (pNew->pSelect->selFlags & SF_NestedFrom)!=0 ){
170080 pNew->fg.isNestedFrom = 1;
170082 if( pOld->fg.isTabFunc ){
170083 pNew->u1.pFuncArg = pOld->u1.pFuncArg;
170084 pOld->u1.pFuncArg = 0;
170085 pOld->fg.isTabFunc = 0;
170086 pNew->fg.isTabFunc = 1;
170088 pOld->zName = pOld->zDatabase = 0;
170089 pOld->pSelect = 0;
170091 sqlite3SrcListDelete(pParse->db, yymsp[-3].minor.yy131);
170094 sqlite3SrcListShiftJoinType(pParse,yymsp[-3].minor.yy131);
170095 pSubquery = sqlite3SelectNew(pParse,0,yymsp[-3].minor.yy131,0,0,0,0,SF_NestedFrom,0);
170096 …yymsp[-5].minor.yy131 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-5].minor.yy131,0,0,&yymsp[-1].m…
170107 …if( IN_RENAME_OBJECT && yylhsminor.yy131 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy131->a[0].zN…
170113 yylhsminor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
170114 …if( IN_RENAME_OBJECT && yylhsminor.yy131 ) sqlite3RenameTokenMap(pParse, yylhsminor.yy131->a[0].zN…
170116 yymsp[-2].minor.yy131 = yylhsminor.yy131;
170119 {yymsp[0].minor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[0].minor.yy0,0); /*A-overwrites-X*/}
170122 {yymsp[-2].minor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /…
170126 …yymsp[-4].minor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,&yymsp[-2].minor.yy0); …
170127 …if( yymsp[-4].minor.yy131 ) yymsp[-4].minor.yy131->a[0].zAlias = sqlite3NameFromToken(pParse->db, …
170132 yymsp[-2].minor.yy131 = sqlite3SrcListAppend(pParse,0,&yymsp[-2].minor.yy0,0); /*A-overwrites-X*/
170133 …if( yymsp[-2].minor.yy131 ) yymsp[-2].minor.yy131->a[0].zAlias = sqlite3NameFromToken(pParse->db, …
170140 {yymsp[-1].minor.yy394 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
170143 {yymsp[-2].minor.yy394 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-o…
170146 {yymsp[-3].minor.yy394 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1…
170149 {yymsp[-1].minor.yy561.pOn = yymsp[0].minor.yy528; yymsp[-1].minor.yy561.pUsing = 0;}
170152 {yymsp[-3].minor.yy561.pOn = 0; yymsp[-3].minor.yy561.pUsing = yymsp[-1].minor.yy254;}
170158 {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
170161 {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
170165 {yymsp[-2].minor.yy322 = yymsp[0].minor.yy322;}
170169 yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322,yymsp[-2].minor.yy528);
170170 sqlite3ExprListSetSortOrder(yymsp[-4].minor.yy322,yymsp[-1].minor.yy394,yymsp[0].minor.yy394);
170175 yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[-2].minor.yy528); /*A-overwrites-Y*/
170176 sqlite3ExprListSetSortOrder(yymsp[-2].minor.yy322,yymsp[-1].minor.yy394,yymsp[0].minor.yy394);
170190 {yymsp[-1].minor.yy394 = SQLITE_SO_ASC;}
170193 {yymsp[-1].minor.yy394 = SQLITE_SO_DESC;}
170209 {yymsp[-1].minor.yy528 = yymsp[0].minor.yy528;}
170212 {yymsp[-1].minor.yy528 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy528,0);}
170215 {yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
170218 {yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_LIMIT,yymsp[0].minor.yy528,yymsp[-2].minor.yy528);}
170222 sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy131, &yymsp[-1].minor.yy0);
170223 sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy131,yymsp[0].minor.yy528,0,0);
170227 {sqlite3AddReturning(pParse,yymsp[0].minor.yy322); yymsp[-1].minor.yy528 = 0;}
170230 {sqlite3AddReturning(pParse,yymsp[0].minor.yy322); yymsp[-3].minor.yy528 = yymsp[-2].minor.yy528;}
170234 sqlite3SrcListIndexedBy(pParse, yymsp[-5].minor.yy131, &yymsp[-4].minor.yy0);
170235 sqlite3ExprListCheckLength(pParse,yymsp[-2].minor.yy322,"set list");
170236 if( yymsp[-1].minor.yy131 ){
170237 SrcList *pFromClause = yymsp[-1].minor.yy131;
170238 if( pFromClause->nSrc>1 ){
170246 yymsp[-5].minor.yy131 = sqlite3SrcListAppendList(pParse, yymsp[-5].minor.yy131, pFromClause);
170248 …sqlite3Update(pParse,yymsp[-5].minor.yy131,yymsp[-2].minor.yy322,yymsp[0].minor.yy528,yymsp[-6].mi…
170253 …yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy322, yymsp[0].minor.yy528);
170254 sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy0, 1);
170259 …yymsp[-6].minor.yy322 = sqlite3ExprListAppendVector(pParse, yymsp[-6].minor.yy322, yymsp[-3].minor…
170265 sqlite3ExprListSetName(pParse, yylhsminor.yy322, &yymsp[-2].minor.yy0, 1);
170267 yymsp[-2].minor.yy322 = yylhsminor.yy322;
170271 …yymsp[-4].minor.yy322 = sqlite3ExprListAppendVector(pParse, 0, yymsp[-3].minor.yy254, yymsp[0].min…
170276 …sqlite3Insert(pParse, yymsp[-3].minor.yy131, yymsp[-1].minor.yy47, yymsp[-2].minor.yy254, yymsp[-5…
170281 sqlite3Insert(pParse, yymsp[-4].minor.yy131, 0, yymsp[-3].minor.yy254, yymsp[-6].minor.yy394, 0);
170288 { yymsp[-1].minor.yy444 = 0; sqlite3AddReturning(pParse,yymsp[0].minor.yy322); }
170291 { yymsp[-11].minor.yy444 = sqlite3UpsertNew(pParse->db,yymsp[-8].minor.yy322,yymsp[-6].minor.yy528,…
170294 { yymsp[-8].minor.yy444 = sqlite3UpsertNew(pParse->db,yymsp[-5].minor.yy322,yymsp[-3].minor.yy528,0…
170297 { yymsp[-4].minor.yy444 = sqlite3UpsertNew(pParse->db,0,0,0,0,0); }
170300 { yymsp[-7].minor.yy444 = sqlite3UpsertNew(pParse->db,0,0,yymsp[-2].minor.yy322,yymsp[-1].minor.yy5…
170309 {yymsp[-2].minor.yy254 = yymsp[-1].minor.yy254;}
170312 {yymsp[-2].minor.yy254 = sqlite3IdListAppend(pParse,yymsp[-2].minor.yy254,&yymsp[0].minor.yy0);}
170315 {yymsp[0].minor.yy254 = sqlite3IdListAppend(pParse,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
170318 {yymsp[-2].minor.yy528 = yymsp[-1].minor.yy528;}
170322 {yymsp[0].minor.yy528=tokenExpr(pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
170326 Expr *temp1 = tokenExpr(pParse,TK_ID,yymsp[-2].minor.yy0);
170330 yymsp[-2].minor.yy528 = yylhsminor.yy528;
170334 Expr *temp1 = tokenExpr(pParse,TK_ID,yymsp[-4].minor.yy0);
170335 Expr *temp2 = tokenExpr(pParse,TK_ID,yymsp[-2].minor.yy0);
170343 yymsp[-4].minor.yy528 = yylhsminor.yy528;
170347 {yymsp[0].minor.yy528=tokenExpr(pParse,yymsp[0].major,yymsp[0].minor.yy0); /*A-overwrites-X*/}
170351 yylhsminor.yy528 = sqlite3ExprAlloc(pParse->db, TK_INTEGER, &yymsp[0].minor.yy0, 1);
170352 if( yylhsminor.yy528 ) yylhsminor.yy528->w.iOfst = (int)(yymsp[0].minor.yy0.z - pParse->zTail);
170365 ** in the virtual machine. #N is the N-th register. */
170366 Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
170368 if( pParse->nested==0 ){
170373 if( yymsp[0].minor.yy528 ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy528->iTable);
170380 …yymsp[-2].minor.yy528 = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy528, &yymsp[0].minor.…
170385 yymsp[-5].minor.yy528 = sqlite3ExprAlloc(pParse->db, TK_CAST, &yymsp[-1].minor.yy0, 1);
170386 sqlite3ExprAttachSubtrees(pParse->db, yymsp[-5].minor.yy528, yymsp[-3].minor.yy528, 0);
170391 …yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy322, &yymsp[-4].minor.yy0, yymsp[
170393 yymsp[-4].minor.yy528 = yylhsminor.yy528;
170397 yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0, 0);
170399 yymsp[-3].minor.yy528 = yylhsminor.yy528;
170403 …yylhsminor.yy528 = sqlite3ExprFunction(pParse, yymsp[-2].minor.yy322, &yymsp[-5].minor.yy0, yymsp[
170406 yymsp[-5].minor.yy528 = yylhsminor.yy528;
170410 yylhsminor.yy528 = sqlite3ExprFunction(pParse, 0, &yymsp[-4].minor.yy0, 0);
170413 yymsp[-4].minor.yy528 = yylhsminor.yy528;
170423 ExprList *pList = sqlite3ExprListAppend(pParse, yymsp[-3].minor.yy322, yymsp[-1].minor.yy528);
170424 yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_VECTOR, 0, 0);
170425 if( yymsp[-4].minor.yy528 ){
170426 yymsp[-4].minor.yy528->x.pList = pList;
170427 if( ALWAYS(pList->nExpr) ){
170428 yymsp[-4].minor.yy528->flags |= pList->a[0].pExpr->flags & EP_Propagate;
170431 sqlite3ExprListDelete(pParse->db, pList);
170436 {yymsp[-2].minor.yy528=sqlite3ExprAnd(pParse,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);}
170445 {yymsp[-2].minor.yy528=sqlite3PExpr(pParse,yymsp[-1].major,yymsp[-2].minor.yy528,yymsp[0].minor.yy5…
170448 {yymsp[-1].minor.yy0=yymsp[0].minor.yy0; yymsp[-1].minor.yy0.n|=0x80000000; /*yymsp[-1].minor.yy0-o…
170453 int bNot = yymsp[-1].minor.yy0.n & 0x80000000;
170454 yymsp[-1].minor.yy0.n &= 0x7fffffff;
170456 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy528);
170457 yymsp[-2].minor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
170458 if( bNot ) yymsp[-2].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-2].minor.yy528, 0);
170459 if( yymsp[-2].minor.yy528 ) yymsp[-2].minor.yy528->flags |= EP_InfixFunc;
170465 int bNot = yymsp[-3].minor.yy0.n & 0x80000000;
170466 yymsp[-3].minor.yy0.n &= 0x7fffffff;
170467 pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
170468 pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy528);
170470 yymsp[-4].minor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy0, 0);
170471 if( bNot ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.yy528, 0);
170472 if( yymsp[-4].minor.yy528 ) yymsp[-4].minor.yy528->flags |= EP_InfixFunc;
170476 {yymsp[-1].minor.yy528 = sqlite3PExpr(pParse,yymsp[0].major,yymsp[-1].minor.yy528,0);}
170479 {yymsp[-2].minor.yy528 = sqlite3PExpr(pParse,TK_NOTNULL,yymsp[-2].minor.yy528,0);}
170483 yymsp[-2].minor.yy528 = sqlite3PExpr(pParse,TK_IS,yymsp[-2].minor.yy528,yymsp[0].minor.yy528);
170484 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-2].minor.yy528, TK_ISNULL);
170489 yymsp[-3].minor.yy528 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-3].minor.yy528,yymsp[0].minor.yy528);
170490 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-3].minor.yy528, TK_NOTNULL);
170495 yymsp[-5].minor.yy528 = sqlite3PExpr(pParse,TK_IS,yymsp[-5].minor.yy528,yymsp[0].minor.yy528);
170496 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-5].minor.yy528, TK_ISNULL);
170501 yymsp[-4].minor.yy528 = sqlite3PExpr(pParse,TK_ISNOT,yymsp[-4].minor.yy528,yymsp[0].minor.yy528);
170502 binaryToUnaryIfNull(pParse, yymsp[0].minor.yy528, yymsp[-4].minor.yy528, TK_NOTNULL);
170507 {yymsp[-1].minor.yy528 = sqlite3PExpr(pParse, yymsp[-1].major, yymsp[0].minor.yy528, 0);/*A-overwri…
170511 …yymsp[-1].minor.yy528 = sqlite3PExpr(pParse, yymsp[-1].major==TK_PLUS ? TK_UPLUS : TK_UMINUS, yyms…
170512 /*A-overwrites-B*/
170517 ExprList *pList = sqlite3ExprListAppend(pParse, 0, yymsp[-2].minor.yy528);
170519 yylhsminor.yy528 = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy0, 0);
170521 yymsp[-2].minor.yy528 = yylhsminor.yy528;
170529 ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
170531 yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy528, 0);
170532 if( yymsp[-4].minor.yy528 ){
170533 yymsp[-4].minor.yy528->x.pList = pList;
170535 sqlite3ExprListDelete(pParse->db, pList);
170537 …if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.y…
170542 if( yymsp[-1].minor.yy322==0 ){
170551 sqlite3ExprUnmapAndDelete(pParse, yymsp[-4].minor.yy528);
170552 …yymsp[-4].minor.yy528 = sqlite3Expr(pParse->db, TK_STRING, yymsp[-3].minor.yy394 ? "true" : "false…
170553 if( yymsp[-4].minor.yy528 ) sqlite3ExprIdToTrueFalse(yymsp[-4].minor.yy528);
170555 Expr *pRHS = yymsp[-1].minor.yy322->a[0].pExpr;
170556 …if( yymsp[-1].minor.yy322->nExpr==1 && sqlite3ExprIsConstant(pRHS) && yymsp[-4].minor.yy528->op!=T…
170557 yymsp[-1].minor.yy322->a[0].pExpr = 0;
170558 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
170560 yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_EQ, yymsp[-4].minor.yy528, pRHS);
170562 yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
170563 if( yymsp[-4].minor.yy528==0 ){
170564 sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy322);
170565 }else if( yymsp[-4].minor.yy528->pLeft->op==TK_VECTOR ){
170566 int nExpr = yymsp[-4].minor.yy528->pLeft->x.pList->nExpr;
170567 Select *pSelectRHS = sqlite3ExprListToValues(pParse, nExpr, yymsp[-1].minor.yy322);
170570 sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, pSelectRHS);
170573 yymsp[-4].minor.yy528->x.pList = yymsp[-1].minor.yy322;
170574 sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy528);
170577 …if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.y…
170583 yymsp[-2].minor.yy528 = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
170584 sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy528, yymsp[-1].minor.yy47);
170589 yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
170590 sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, yymsp[-1].minor.yy47);
170591 …if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.y…
170596 SrcList *pSrc = sqlite3SrcListAppend(pParse, 0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);
170599 yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy528, 0);
170600 sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy528, pSelect);
170601 …if( yymsp[-3].minor.yy394 ) yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_NOT, yymsp[-4].minor.y…
170607 p = yymsp[-3].minor.yy528 = sqlite3PExpr(pParse, TK_EXISTS, 0, 0);
170608 sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy47);
170613 yymsp[-4].minor.yy528 = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy528, 0);
170614 if( yymsp[-4].minor.yy528 ){
170615 …yymsp[-4].minor.yy528->x.pList = yymsp[-1].minor.yy528 ? sqlite3ExprListAppend(pParse,yymsp[-2].mi…
170616 sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy528);
170618 sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy322);
170619 sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy528);
170625 …yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[-2].minor.yy528);
170626 yymsp[-4].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy322, yymsp[0].minor.yy528);
170631 yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy528);
170632 yymsp[-3].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy322, yymsp[0].minor.yy528);
170636 {yymsp[0].minor.yy528 = yymsp[0].minor.yy528; /*A-overwrites-X*/}
170639 {yymsp[-2].minor.yy322 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy322,yymsp[0].minor.yy528);}
170642 {yymsp[0].minor.yy322 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy528); /*A-overwrites-Y*/}
170646 {yymsp[-2].minor.yy322 = yymsp[-1].minor.yy322;}
170650 sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
170651 …sqlite3SrcListAppend(pParse,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy322, yymsp[-10].minor.yy3…
170652 …&yymsp[-11].minor.yy0, yymsp[0].minor.yy528, SQLITE_SO_ASC, yymsp[-8].minor.yy394, SQLITE_IDXTYPE_…
170653 if( IN_RENAME_OBJECT && pParse->pNewIndex ){
170654 sqlite3RenameTokenMap(pParse, pParse->pNewIndex->zName, &yymsp[-4].minor.yy0);
170667 …yymsp[-4].minor.yy322 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy322, &yymsp[-2].minor.yy…
170672 …yymsp[-2].minor.yy322 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.y…
170676 {sqlite3DropIndex(pParse, yymsp[0].minor.yy131, yymsp[-1].minor.yy394);}
170682 {sqlite3Vacuum(pParse,&yymsp[-1].minor.yy0,yymsp[0].minor.yy528);}
170685 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
170688 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
170691 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
170694 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
170697 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
170702 all.z = yymsp[-3].minor.yy0.z;
170703 all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
170704 sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy33, &all);
170709-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy394, yymsp[-4].minor.yy180.a, yymsp[-4].min…
170710 …yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-ove…
170714 { yymsp[0].minor.yy394 = yymsp[0].major; /*A-overwrites-X*/ }
170717 { yymsp[-1].minor.yy394 = TK_INSTEAD;}
170724 {yymsp[0].minor.yy180.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy180.b = 0;}
170727 {yymsp[-2].minor.yy180.a = TK_UPDATE; yymsp[-2].minor.yy180.b = yymsp[0].minor.yy254;}
170735 { yymsp[-1].minor.yy528 = yymsp[0].minor.yy528; }
170739 assert( yymsp[-2].minor.yy33!=0 );
170740 yymsp[-2].minor.yy33->pLast->pNext = yymsp[-1].minor.yy33;
170741 yymsp[-2].minor.yy33->pLast = yymsp[-1].minor.yy33;
170746 assert( yymsp[-1].minor.yy33!=0 );
170747 yymsp[-1].minor.yy33->pLast = yymsp[-1].minor.yy33;
170752 yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
170773 …tep(pParse, &yymsp[-6].minor.yy0, yymsp[-2].minor.yy131, yymsp[-3].minor.yy322, yymsp[-1].minor.yy…
170774 yymsp[-8].minor.yy33 = yylhsminor.yy33;
170778-4].minor.yy0,yymsp[-3].minor.yy254,yymsp[-2].minor.yy47,yymsp[-6].minor.yy394,yymsp[-1].minor.yy4…
170780 yymsp[-7].minor.yy33 = yylhsminor.yy33;
170783 …sminor.yy33 = sqlite3TriggerDeleteStep(pParse, &yymsp[-3].minor.yy0, yymsp[-1].minor.yy528, yymsp[
170784 yymsp[-5].minor.yy33 = yylhsminor.yy33;
170787 …ggerSelectStep(pParse->db, yymsp[-1].minor.yy47, yymsp[-2].minor.yy522, yymsp[0].minor.yy522); /*y…
170788 yymsp[-2].minor.yy33 = yylhsminor.yy33;
170792 yymsp[-3].minor.yy528 = sqlite3PExpr(pParse, TK_RAISE, 0, 0);
170793 if( yymsp[-3].minor.yy528 ){
170794 yymsp[-3].minor.yy528->affExpr = OE_Ignore;
170800 yymsp[-5].minor.yy528 = sqlite3ExprAlloc(pParse->db, TK_RAISE, &yymsp[-1].minor.yy0, 1);
170801 if( yymsp[-5].minor.yy528 ) {
170802 yymsp[-5].minor.yy528->affExpr = (char)yymsp[-3].minor.yy394;
170814 sqlite3DropTrigger(pParse,yymsp[0].minor.yy131,yymsp[-1].minor.yy394);
170819 sqlite3Attach(pParse, yymsp[-3].minor.yy528, yymsp[-1].minor.yy528, yymsp[0].minor.yy528);
170831 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
170837 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
170841 sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy131,&yymsp[0].minor.yy0);
170846 yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
170847 sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
170852 sqlite3AlterDropColumn(pParse, yymsp[-3].minor.yy131, &yymsp[0].minor.yy0);
170863 …sqlite3AlterRenameColumn(pParse, yymsp[-5].minor.yy131, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
170874 …sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yym…
170893 {yymsp[-1].minor.yy516 = M10d_Yes;}
170896 {yymsp[-2].minor.yy516 = M10d_No;}
170900 …sp[-5].minor.yy385 = sqlite3CteNew(pParse, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy322, yymsp[-1].…
170905 yymsp[0].minor.yy521 = sqlite3WithAdd(pParse, 0, yymsp[0].minor.yy385); /*A-overwrites-X*/
170910 yymsp[-2].minor.yy521 = sqlite3WithAdd(pParse, yymsp[-2].minor.yy521, yymsp[0].minor.yy385);
170920 sqlite3WindowChain(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy41);
170921 yymsp[0].minor.yy41->pNextWin = yymsp[-2].minor.yy41;
170924 yymsp[-2].minor.yy41 = yylhsminor.yy41;
170928 if( ALWAYS(yymsp[-1].minor.yy41) ){
170929 …yymsp[-1].minor.yy41->zName = sqlite3DbStrNDup(pParse->db, yymsp[-4].minor.yy0.z, yymsp[-4].minor.…
170931 yylhsminor.yy41 = yymsp[-1].minor.yy41;
170933 yymsp[-4].minor.yy41 = yylhsminor.yy41;
170937 …yymsp[-4].minor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy322, y…
170942 …e3WindowAssemble(pParse, yymsp[0].minor.yy41, yymsp[-2].minor.yy322, yymsp[-1].minor.yy322, &yymsp…
170944 yymsp[-5].minor.yy41 = yylhsminor.yy41;
170948 …yymsp[-3].minor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, yymsp[-1].minor.yy322…
170953 …1 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, yymsp[-1].minor.yy322, &yymsp[-4].minor.…
170955 yymsp[-4].minor.yy41 = yylhsminor.yy41;
170966 yylhsminor.yy41 = sqlite3WindowAssemble(pParse, yymsp[0].minor.yy41, 0, 0, &yymsp[-1].minor.yy0);
170968 yymsp[-1].minor.yy41 = yylhsminor.yy41;
170977 …ylhsminor.yy41 = sqlite3WindowAlloc(pParse, yymsp[-2].minor.yy394, yymsp[-1].minor.yy595.eType, yy…
170979 yymsp[-2].minor.yy41 = yylhsminor.yy41;
170983 …wAlloc(pParse, yymsp[-5].minor.yy394, yymsp[-3].minor.yy595.eType, yymsp[-3].minor.yy595.pExpr, yy…
170985 yymsp[-5].minor.yy41 = yylhsminor.yy41;
170995 {yylhsminor.yy595.eType = yymsp[-1].major; yylhsminor.yy595.pExpr = 0;}
170996 yymsp[-1].minor.yy595 = yylhsminor.yy595;
170999 {yylhsminor.yy595.eType = yymsp[0].major; yylhsminor.yy595.pExpr = yymsp[-1].minor.yy528;}
171000 yymsp[-1].minor.yy595 = yylhsminor.yy595;
171006 {yymsp[-1].minor.yy516 = yymsp[0].minor.yy516;}
171010 {yymsp[-1].minor.yy516 = yymsp[-1].major; /*A-overwrites-X*/}
171013 {yymsp[0].minor.yy516 = yymsp[0].major; /*A-overwrites-X*/}
171016 { yymsp[-1].minor.yy41 = yymsp[0].minor.yy41; }
171021 yymsp[0].minor.yy41->pFilter = yymsp[-1].minor.yy528;
171023 sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy528);
171027 yymsp[-1].minor.yy41 = yylhsminor.yy41;
171031 yylhsminor.yy41 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
171033 yylhsminor.yy41->eFrmType = TK_FILTER;
171034 yylhsminor.yy41->pFilter = yymsp[0].minor.yy528;
171036 sqlite3ExprDelete(pParse->db, yymsp[0].minor.yy528);
171043 yymsp[-3].minor.yy41 = yymsp[-1].minor.yy41;
171044 assert( yymsp[-3].minor.yy41!=0 );
171049 yymsp[-1].minor.yy41 = (Window*)sqlite3DbMallocZero(pParse->db, sizeof(Window));
171050 if( yymsp[-1].minor.yy41 ){
171051 …yymsp[-1].minor.yy41->zName = sqlite3DbStrNDup(pParse->db, yymsp[0].minor.yy0.z, yymsp[0].minor.yy…
171056 { yymsp[-4].minor.yy528 = yymsp[-1].minor.yy528; }
171138 yypParser->yytos = yymsp;
171139 yymsp->stateno = (YYACTIONTYPE)yyact;
171140 yymsp->major = (YYCODETYPE)yygoto;
171159 while( yypParser->yytos>yypParser->yystack ) yy_pop_parser_stack(yypParser);
171207 yypParser->yyerrcnt = -1;
171209 assert( yypParser->yytos==yypParser->yystack );
171231 ** <li> An option argument of a grammar-specified type.
171255 assert( yypParser->yytos!=0 );
171260 yyact = yypParser->yytos->stateno;
171268 yyTracePrompt,yyTokenName[yymajor],yyact-YY_MIN_REDUCE);
171274 assert( yypParser->yytos>=yypParser->yystack );
171275 assert( yyact==yypParser->yytos->stateno );
171278 unsigned int yyruleno = yyact - YY_MIN_REDUCE; /* Reduce by this rule */
171288 yypParser->yytos[yysize].stateno);
171302 if( (int)(yypParser->yytos - yypParser->yystack)>yypParser->yyhwm ){
171303 yypParser->yyhwm++;
171304 assert( yypParser->yyhwm ==
171305 (int)(yypParser->yytos - yypParser->yystack));
171309 if( yypParser->yytos>=yypParser->yystackEnd ){
171314 if( yypParser->yytos>=&yypParser->yystack[yypParser->yystksz-1] ){
171326 yypParser->yyerrcnt--;
171330 yypParser->yytos--;
171364 if( yypParser->yyerrcnt<0 ){
171367 yymx = yypParser->yytos->major;
171378 while( yypParser->yytos > yypParser->yystack ){
171379 yyact = yy_find_reduce_action(yypParser->yytos->stateno,
171384 if( yypParser->yytos <= yypParser->yystack || yymajor==0 ){
171388 yypParser->yyerrcnt = -1;
171395 yypParser->yyerrcnt = 3;
171398 yyact = yypParser->yytos->stateno;
171420 if( yypParser->yyerrcnt<=0 ){
171423 yypParser->yyerrcnt = 3;
171428 yypParser->yyerrcnt = -1;
171440 for(i=&yypParser->yystack[1]; i<=yypParser->yytos; i++){
171441 fprintf(yyTraceFILE,"%c%s", cDiv, yyTokenName[i->major]);
171469 ** The author disclaims copyright to this source code. In place of
171480 ** individual tokens and sends those tokens one-by-one over to the
171505 #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
171510 #define CC_SLASH 16 /* '/'. / or c-style comment */
171569 ** lower-case ASCII equivalent. On ASCII machines, this is just
171570 ** an upper-to-lower case map. On EBCDIC machines we also need
171610 ** named keywordhash.h and then included into this source file by
171623 ** might be implemented more directly using a hand-written hash table.
171681 /* aKWHash[i] is the hash value for the i-th keyword */
171695 ** then the i-th keyword has no more hash collisions. Otherwise,
171696 ** the next keyword with the same hash is aKWHash[i]-1. */
171711 /* aKWLen[i] is the length (in bytes) of the i-th keyword */
171727 ** the text for the i-th keyword. */
171742 /* aKWCode[i] is the parser symbol code for the i-th keyword */
171904 /* Check to see if z[0..n-1] is a keyword. If it is, write the
171911 i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n*1) % 127;
171912 for(i=((int)aKWHash[i])-1; i>=0; i=((int)aKWNext[i])-1){
172106 ** For ASCII, any character with the high-order bit set is
172107 ** allowed in an identifier. For 7-bit characters,
172137 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
172179 ** impossible to call a window-function without a FILTER clause.
172226 switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
172240 if( z[1]=='-' ){
172242 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
172278 *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
172404 || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
172520 void *pEngine; /* The LEMON-generated LALR(1) parser */
172523 int lastTokenParsed = -1; /* type of the previous token */
172524 sqlite3 *db = pParse->db; /* The database connection */
172528 yyParser sEngine; /* Space to hold the Lemon-generated Parser object */
172530 VVA_ONLY( u8 startedWithOom = db->mallocFailed );
172533 mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
172534 if( db->nVdbeActive==0 ){
172535 AtomicStore(&db->u1.isInterrupted, 0);
172537 pParse->rc = SQLITE_OK;
172538 pParse->zTail = zSql;
172540 if( db->flags & SQLITE_ParserTrace ){
172557 assert( pParse->pNewTable==0 );
172558 assert( pParse->pNewTrigger==0 );
172559 assert( pParse->nVar==0 );
172560 assert( pParse->pVList==0 );
172561 pParentParse = db->pParse;
172562 db->pParse = pParse;
172565 mxSqlLen -= n;
172567 pParse->rc = SQLITE_TOOBIG;
172568 pParse->nErr++;
172580 if( AtomicLoad(&db->u1.isInterrupted) ){
172581 pParse->rc = SQLITE_INTERRUPT;
172582 pParse->nErr++;
172619 pParse->sLastToken.z = zSql;
172620 pParse->sLastToken.n = n;
172621 sqlite3Parser(pEngine, tokenType, pParse->sLastToken);
172624 assert( db->mallocFailed==0 || pParse->rc!=SQLITE_OK || startedWithOom );
172625 if( pParse->rc!=SQLITE_OK ) break;
172640 if( db->mallocFailed ){
172641 pParse->rc = SQLITE_NOMEM_BKPT;
172643 if( pParse->zErrMsg || (pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE) ){
172644 if( pParse->zErrMsg==0 ){
172645 pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
172647 sqlite3_log(pParse->rc, "%s in \"%s\"", pParse->zErrMsg, pParse->zTail);
172650 pParse->zTail = zSql;
172652 sqlite3_free(pParse->apVtabLock);
172655 if( pParse->pNewTable && !IN_SPECIAL_PARSE ){
172656 /* If the pParse->declareVtab flag is set, do not delete any table
172657 ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
172660 sqlite3DeleteTable(db, pParse->pNewTable);
172662 if( pParse->pNewTrigger && !IN_RENAME_OBJECT ){
172663 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
172665 if( pParse->pVList ) sqlite3DbNNFreeNN(db, pParse->pVList);
172666 db->pParse = pParentParse;
172667 assert( nErr==0 || pParse->rc!=SQLITE_OK );
172678 if( pStr->nChar && sqlite3IsIdChar(pStr->zText[pStr->nChar-1]) ){
172684 ** Compute a normalization of the SQL given by zSql[0..nSql-1]. Return
172696 int prevType = 0; /* Previous non-whitespace token */
172704 tokenType = -1;
172708 for(i=0; zSql[i] && pStr->accError==0; i+=n){
172736 iStartIN = pStr->nChar;
172744 assert( pStr->nChar>=(u32)iStartIN );
172745 pStr->nChar = iStartIN+1;
172749 nParen--;
172755 j = pStr->nChar;
172779 while( j<pStr->nChar ){
172780 pStr->zText[j] = sqlite3Tolower(pStr->zText[j]);
172791 j = pStr->nChar;
172793 while( j<pStr->nChar ){
172794 pStr->zText[j] = sqlite3Toupper(pStr->zText[j]);
172811 ** The author disclaims copyright to this source code. In place of
172822 ** This code used to be part of the tokenizer.c source file. But by
172838 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
172867 ** (0) INVALID We have not yet seen a non-whitespace character.
172965 case '/': { /* C-style comments */
172977 case '-': { /* SQL-style comments from "--" to end of line */
172978 if( zSql[1]!='-' ){
172987 case '[': { /* Microsoft-style identifiers in [...] */
172994 case '`': /* Grave-accent quoted symbols used by MySQL */
172995 case '"': /* single- and double-quoted strings */
173056 zSql += nId-1;
173073 ** above, except that the parameter is required to be UTF-16 encoded, not
173074 ** UTF-8.
173086 sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
173104 ** The author disclaims copyright to this source code. In place of
173125 ** The author disclaims copyright to this source code. In place of
173158 ** The author disclaims copyright to this source code. In place of
173195 ** The author disclaims copyright to this source code. In place of
173224 ** This is an extension initializer that is a no-op and always
173225 ** succeeds, except that it fails if the fault-simulation is set
173253 ** built-in extensions.
173293 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
173299 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
173304 /* IMPLEMENTATION-OF: R-25063-23286 The sqlite3_sourceid() function returns a
173312 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
173317 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
173319 ** the SQLITE_THREADSAFE compile-time option being set to 0.
173325 ** this variable being set to non-zero will cause OSTRACE macros to emit
173372 ** This routine is a no-op except on its very first call for the process,
173388 ** * Calls to this routine from Y must block until the outer-most
173409 ** combination, the work-around is to set the correct pointer
173410 ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
173414 ** to sqlite3_initialize() should be a no-op. But the initialization
173437 ** malloc subsystem - this implies that the allocation of a static
173474 ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
173521 sqlite3GlobalConfig.nRefInitMutex--;
173538 u64 x = (((u64)1)<<63)-1;
173549 ** compile-time option.
173567 ** when this routine is invoked, then this routine is a harmless no-op.
173616 ** the SQLite library at run-time.
173637 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
173639 /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
173640 ** Single-thread. */
173646 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
173648 /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
173649 ** Multi-thread. */
173655 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
173657 /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
173664 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
173671 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
173680 /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
173683 ** low-level memory allocation routines to be used in place of the memory
173689 /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
173698 /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
173709 /* EVIDENCE-OF: R-18761-36601 There are three arguments to
173710 ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
173719 /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
173731 /* no-op */
173741 /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
173749 /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
173760 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
173765 /* EVIDENCE-OF: R-19854-42126 There are three arguments to
173766 ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
173781 /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
173791 /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
173826 /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
173827 ** can be changed at start-time using the
173832 /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
173833 ** argument of type int. If non-zero, then URI handling is globally
173841 /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
173859 /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
173865 /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
173866 ** negative, then that argument is changed to its compile-time default.
173868 ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
173870 ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
173871 ** compile-time option.
173883 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
173885 /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
173945 int nBig; /* Number of full-size slots */
173946 int nSm; /* Number smaller LOOKASIDE_SMALL-byte slots */
173955 if( db->lookaside.bMalloced ){
173956 sqlite3_free(db->lookaside.pStart);
173961 sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
173969 pStart = sqlite3Malloc( szAlloc ); /* IMP: R-61949-35727 */
173978 nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
173981 nSm = (szAlloc - sz*nBig)/LOOKASIDE_SMALL;
173990 db->lookaside.pStart = pStart;
173991 db->lookaside.pInit = 0;
173992 db->lookaside.pFree = 0;
173993 db->lookaside.sz = (u16)sz;
173994 db->lookaside.szTrue = (u16)sz;
174001 p->pNext = db->lookaside.pInit;
174002 db->lookaside.pInit = p;
174006 db->lookaside.pSmallInit = 0;
174007 db->lookaside.pSmallFree = 0;
174008 db->lookaside.pMiddle = p;
174010 p->pNext = db->lookaside.pSmallInit;
174011 db->lookaside.pSmallInit = p;
174016 db->lookaside.pEnd = p;
174017 db->lookaside.bDisable = 0;
174018 db->lookaside.bMalloced = pBuf==0 ?1:0;
174019 db->lookaside.nSlot = nBig+nSm;
174021 db->lookaside.pStart = 0;
174023 db->lookaside.pSmallInit = 0;
174024 db->lookaside.pSmallFree = 0;
174025 db->lookaside.pMiddle = 0;
174027 db->lookaside.pEnd = 0;
174028 db->lookaside.bDisable = 1;
174029 db->lookaside.sz = 0;
174030 db->lookaside.bMalloced = 0;
174031 db->lookaside.nSlot = 0;
174033 db->lookaside.pTrueEnd = db->lookaside.pEnd;
174049 return db->mutex;
174062 sqlite3_mutex_enter(db->mutex);
174064 for(i=0; i<db->nDb; i++){
174065 Btree *pBt = db->aDb[i].pBt;
174072 sqlite3_mutex_leave(db->mutex);
174077 ** Flush any dirty pages in the pager-cache for any attached database
174088 sqlite3_mutex_enter(db->mutex);
174090 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
174091 Btree *pBt = db->aDb[i].pBt;
174102 sqlite3_mutex_leave(db->mutex);
174112 sqlite3_mutex_enter(db->mutex);
174116 /* IMP: R-06824-28531 */
174117 /* IMP: R-36257-52125 */
174118 db->aDb[0].zDbSName = va_arg(ap,char*);
174123 void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
174124 int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
174125 int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
174137 pVdbe->pSharedBlock = pSharedBlock;
174139 pVdbe->startPos = pSharedBlock->startPos;
174141 pVdbe->totalRows = 0;
174142 pVdbe->blockFull = 0;
174143 pVdbe->addedRows = 0;
174176 rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
174181 u64 oldFlags = db->flags;
174183 db->flags |= aFlagOp[i].mask;
174185 db->flags &= ~(u64)aFlagOp[i].mask;
174187 if( oldFlags!=db->flags ){
174191 *pRes = (db->flags & aFlagOp[i].mask)!=0;
174201 sqlite3_mutex_leave(db->mutex);
174217 /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
174223 rc = nKey1 - nKey2;
174239 while( nKey1 && pK1[nKey1-1]==' ' ) nKey1--;
174240 while( nKey2 && pK2[nKey2-1]==' ' ) nKey2--;
174245 ** Return true if CollSeq is the default built-in BINARY.
174248 assert( p==0 || p->xCmp!=binCollFunc || strcmp(p->zName,"BINARY")==0 );
174249 return p==0 || p->xCmp==binCollFunc;
174253 ** Another built-in collating sequence: NOCASE.
174259 ** At the moment there is only a UTF-8 implementation.
174270 r = nKey1-nKey2;
174285 return db->lastRowid;
174298 sqlite3_mutex_enter(db->mutex);
174299 db->lastRowid = iRowid;
174300 sqlite3_mutex_leave(db->mutex);
174313 return db->nChange;
174329 return db->nTotalChange;
174338 ** at the b-tree/pager level.
174341 while( db->pSavepoint ){
174342 Savepoint *pTmp = db->pSavepoint;
174343 db->pSavepoint = pTmp->pNext;
174346 db->nSavepoint = 0;
174347 db->nStatement = 0;
174348 db->isTransactionSavepoint = 0;
174359 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
174360 pDestructor = p->u.pDestructor;
174362 pDestructor->nRef--;
174363 if( pDestructor->nRef==0 ){
174364 pDestructor->xDestroy(pDestructor->pUserData);
174379 for(i=0; i<db->nDb; i++){
174380 Schema *pSchema = db->aDb[i].pSchema;
174382 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
174388 for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
174390 if( pMod->pEpoTab ){
174391 sqlite3VtabDisconnect(db, pMod->pEpoTab);
174407 assert( sqlite3_mutex_held(db->mutex) );
174408 if( db->pVdbe ) return 1;
174409 for(j=0; j<db->nDb; j++){
174410 Btree *pBt = db->aDb[j].pBt;
174421 /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
174422 ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
174428 sqlite3_mutex_enter(db->mutex);
174429 if( db->mTrace & SQLITE_TRACE_CLOSE ){
174430 db->trace.xV2(SQLITE_TRACE_CLOSE, db->pTraceArg, db, 0);
174438 ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
174440 ** SQL statements below, as the v-table implementation may be storing
174451 sqlite3_mutex_leave(db->mutex);
174464 db->eOpenState = SQLITE_STATE_ZOMBIE;
174475 int iTxn = -1;
174479 return -1;
174482 sqlite3_mutex_enter(db->mutex);
174485 if( iDb<0 ) nDb--;
174488 nDb = db->nDb-1;
174491 Btree *pBt = db->aDb[iDb].pBt;
174495 sqlite3_mutex_leave(db->mutex);
174528 if( db->eOpenState!=SQLITE_STATE_ZOMBIE || connectionIsBusy(db) ){
174529 sqlite3_mutex_leave(db->mutex);
174541 ** they are reset. And that the required b-tree mutex is held to make
174549 for(j=0; j<db->nDb; j++){
174550 struct Db *pDb = &db->aDb[j];
174551 if( pDb->pBt ){
174552 sqlite3BtreeClose(pDb->pBt);
174553 pDb->pBt = 0;
174555 pDb->pSchema = 0;
174560 if( db->aDb[1].pSchema ){
174561 sqlite3SchemaClear(db->aDb[1].pSchema);
174567 assert( db->nDb<=2 );
174568 assert( db->aDb==db->aDbStatic );
174571 ** locks and does not require any further unlock-notify callbacks.
174575 for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
174580 pNext = p->pNext;
174585 sqlite3HashClear(&db->aFunc);
174586 for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
174596 sqlite3HashClear(&db->aCollSeq);
174598 for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
174603 sqlite3HashClear(&db->aModule);
174607 sqlite3ValueFree(db->pErr);
174610 sqlite3_free(db->auth.zAuthUser);
174611 sqlite3_free(db->auth.zAuthPW);
174614 db->eOpenState = SQLITE_STATE_ERROR;
174616 /* The temp-database schema is allocated differently from the other schema
174622 sqlite3DbFree(db, db->aDb[1].pSchema);
174623 if( db->xAutovacDestr ){
174624 db->xAutovacDestr(db->pAutovacPagesArg);
174626 sqlite3_mutex_leave(db->mutex);
174627 db->eOpenState = SQLITE_STATE_CLOSED;
174628 sqlite3_mutex_free(db->mutex);
174630 if( db->lookaside.bMalloced ){
174631 sqlite3_free(db->lookaside.pStart);
174638 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
174647 assert( sqlite3_mutex_held(db->mutex) );
174650 /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
174652 ** modified the database schema. If the b-tree mutexes are not taken
174653 ** here, then another shared-cache connection might sneak in between
174657 schemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0 && db->init.busy==0;
174659 for(i=0; i<db->nDb; i++){
174660 Btree *p = db->aDb[i].pBt;
174678 db->nDeferredCons = 0;
174679 db->nDeferredImmCons = 0;
174680 db->flags &= ~(u64)(SQLITE_DeferFKs|SQLITE_CorruptRdOnly);
174682 /* If one has been configured, invoke the rollback-hook callback */
174683 if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
174684 db->xRollbackCallback(db->pRollbackArg);
174871 ** Return non-zero to retry the lock. Return zero to stop trying
174887 int tmout = db->busyTimeout;
174895 delay = delays[NDELAY-1];
174896 prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
174899 delay = tmout - prior;
174902 sqlite3OsSleep(db->pVfs, delay*1000);
174908 int tmout = ((sqlite3 *)ptr)->busyTimeout;
174912 sqlite3OsSleep(db->pVfs, 1000000);
174923 ** If this routine returns non-zero, the lock is retried. If it
174928 if( p->xBusyHandler==0 || p->nBusy<0 ) return 0;
174929 rc = p->xBusyHandler(p->pBusyArg, p->nBusy);
174931 p->nBusy = -1;
174933 p->nBusy++;
174950 sqlite3_mutex_enter(db->mutex);
174951 db->busyHandler.xBusyHandler = xBusy;
174952 db->busyHandler.pBusyArg = pArg;
174953 db->busyHandler.nBusy = 0;
174954 db->busyTimeout = 0;
174955 sqlite3_mutex_leave(db->mutex);
174977 sqlite3_mutex_enter(db->mutex);
174979 db->xProgress = xProgress;
174980 db->nProgressOps = (unsigned)nOps;
174981 db->pProgressArg = pArg;
174983 db->xProgress = 0;
174984 db->nProgressOps = 0;
174985 db->pProgressArg = 0;
174987 sqlite3_mutex_leave(db->mutex);
175003 db->busyTimeout = ms;
175015 if( !sqlite3SafetyCheckOk(db) && (db==0 || db->eOpenState!=SQLITE_STATE_ZOMBIE) ){
175020 AtomicStore(&db->u1.isInterrupted, 1);
175046 assert( sqlite3_mutex_held(db->mutex) );
175052 || (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG)
175116 if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==(u32)enc && p->nArg==nArg ){
175117 if( db->nVdbeActive ){