Lines Matching +full:an +full:- +full:1585
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
20 ** The content in this amalgamation comes from Fossil check-in
54 ** NO_TEST - The branches on this line are not
59 ** OPTIMIZATION-IF-TRUE - This branch is allowed to always be false
63 ** OPTIMIZATION-IF-FALSE - This branch is allowed to always be true
67 ** PREVENTS-HARMLESS-OVERREAD - This branch prevents a buffer overread
72 ** slash-asterisk...asterisk-slash comment marks, with no spaces between the
147 ** 2015-03-02
185 ** large file support, or if the OS is windows, these should be no-ops.
191 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
194 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
200 ** on 2008-11-28.) These days, all Linux kernels support large files, so
217 ** SQLITE_DISABLE_INTRINSIC macro means do not use any compiler-specific
224 ** so the GCC_VERSION macro will be set to a correct non-zero value even
280 ** some MinGW-specific macros). When compiling for MinGW, either the
303 /* Optionally #include a user-defined header, whereby compilation options
321 ** 2001-09-15
332 ** presents to client programs. If a C-function, structure, datatype,
343 ** The official C-language API documentation for SQLite is derived
388 ** that require non-default calling conventions.
413 ** These no-op macros are used in front of interfaces to mark those
415 ** should not use deprecated interfaces - they are supported for backwards
439 ** CAPI3REF: Compile-Time Library Version Numbers
445 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
455 ** <a href="http://fossil-scm.org/">Fossil configuration management
457 ** a string which identifies a particular check-in of SQLite
459 ** string contains the date and time of the check-in (UTC) and a SHA1
460 ** or SHA3-256 hash of the entire source tree. If the source code has
470 #define SQLITE_SOURCE_ID "2025-07-30 19:33:53 4d8adfb30e03f9cf27f800a2c1ba3c48fb4ca1b08b0f5ed5…
473 ** CAPI3REF: Run-Time Library Version Numbers
495 ** sqlite3_libversion_number() function returns an integer equal to
499 ** using an edited copy of [the amalgamation], then the last four characters
510 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
519 ** returning the N-th compile time option string. ^If N is out of range,
544 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
558 ** This interface can be used by an application to make sure that the
562 ** This interface only reports on the compile-time mutex setting
568 ** sqlite3_threadsafe() function shows only the compile-time setting of
569 ** thread safety, not any run-time changes to that setting made by
581 ** Each open SQLite database is represented by a pointer to an instance of
582 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
583 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
588 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
594 ** CAPI3REF: 64-Bit Integer Types
597 ** Because there is no cross-platform way to specify 64-bit integer types
598 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
605 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
628 ** substitute integer for floating-point.
654 ** connection immediately, it marks the database connection as an unusable
661 ** ^If an [sqlite3] object is destroyed while a transaction is open,
666 ** pointer or an [sqlite3] object pointer obtained
670 ** argument is a harmless no-op.
683 ** CAPI3REF: One-Step Query Execution Interface
688 ** that allows an application to run multiple statements of SQL
691 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
692 ** semicolon-separate SQL statements passed into its 2nd argument,
702 ** ^If an error occurs while evaluating the SQL statements passed into
714 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
720 ** callback is an array of pointers to strings obtained as if from
721 ** [sqlite3_column_text()], one for each column. ^If an element of a
724 ** sqlite3_exec() callback is an array of pointers to strings where each
729 ** to an empty string, or a pointer that contains only whitespace and/or
747 sqlite3*, /* An open database */
758 ** Many SQLite functions return an integer result code from the set shown
766 /* beginning-of-error-codes */
770 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
797 /* end-of-error-codes */
805 ** these result codes are too coarse-grained. They do not provide as
806 ** much information about problems as programmers might like. In an effort to
904 ** though future versions of SQLite might change so that an error is
911 ** [sqlite3_open_v2()] has historically be a no-op and might become an
946 ** object returns an integer which is a vector of these
954 ** are aligned to an address which is an integer multiple of
967 ** read-only media and cannot be changed even by processes with
978 ** property, SQLite is careful to only do full-page reads and write
979 ** on aligned pages, with the one exception that it will do a sub-page
1004 ** of an [sqlite3_io_methods] object. These values are ordered from
1019 ** When SQLite invokes the xSync() method of an
1037 ** (Third-party VFS implementations might also make the distinction
1049 ** An [sqlite3_file] object represents an open file in the
1053 ** for their own use. The pMethods entry is a pointer to an
1059 const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
1065 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
1067 ** [sqlite3_file] object) with a pointer to an instance of this object.
1072 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1096 ** requested lock, then the call to xLock() is a no-op.
1099 ** to xUnlock() is a no-op.
1106 ** VFS implementations to directly control an open file using the
1107 ** [sqlite3_file_control()] interface. The second "op" argument is an
1112 ** locking strategy (for example to use dot-file locks), to inquire
1150 ** are aligned to an address which is an integer multiple of
1160 ** fails to zero-fill short reads might seem to work. However,
1161 ** failure to zero-fill short reads will eventually lead to
1205 ** into an integer that the pArg argument points to.
1217 ** The [SQLITE_FCNTL_SIZE_LIMIT] opcode is used by in-memory VFS that
1218 ** implements [sqlite3_deserialize()] to set an upper bound on the size
1219 ** of the in-memory database. The argument is a pointer to a [sqlite3_int64].
1229 ** point to an integer (type int) containing the new chunk-size to use
1231 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1242 ** the [rollback journal] or the [write-ahead log]) for a particular database
1255 ** this file-control is NULL. However, if the database file is being synced
1256 ** as part of a multi-database commit, the argument points to a nul-terminated
1257 ** string containing the transactions super-journal file name. VFSes that
1274 ** anti-virus programs. By default, the windows VFS will retry file read,
1277 ** by an additional 25 milliseconds with each subsequent retry. This
1280 ** within the same process. The argument is a pointer to an array of two
1298 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1300 ** WAL mode. If the integer is -1, then it is overwritten with the current
1305 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1308 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1309 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1310 ** mode. If the integer is -1, then it is overwritten with the current
1311 ** zero-damage mode setting.
1322 ** final bottom-level VFS are written into memory obtained from
1326 ** all file-control actions, there is no guarantee that this will actually
1328 ** pointer in case this file-control is not implemented. This file-control
1332 ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1336 ** to a pointer to the top-level VFS.)^
1338 ** upper-most shim only.
1341 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1344 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1347 ** pragma or NULL if the pragma has no argument. ^The handler for an
1355 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1357 ** of the result string if the string is non-NULL.
1360 ** that the VFS encountered an error while handling the [PRAGMA] and the
1361 ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1363 ** it is able to override built-in [PRAGMA] statements.
1367 ** file-control may be invoked by SQLite on the database file handle
1369 ** to the connection's busy-handler callback. The argument is of type (void**)
1370 ** - an array of two (void *) values. The first (void *) actually points
1372 ** busy-handler, this function should be invoked with the second (void *) in
1373 ** the array as the only argument. If it returns non-zero, then the operation
1378 ** ^Applications can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1388 ** maximum number of bytes that will be used for memory-mapped I/O.
1390 ** is an advisory maximum number of bytes in the file to memory map. The
1394 ** file-control is used internally to implement [PRAGMA mmap_size].
1400 ** The argument is a zero-terminated string. Higher layers in the
1402 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1406 ** pointer to an integer and it writes a boolean into that integer depending
1423 ** The [SQLITE_FCNTL_NULL_IO] opcode sets the low-level file descriptor
1432 ** Applications should <em>not</em> use this file-control.
1481 ** The parameter is a pointer to a 32-bit signed integer that contains
1482 ** the value that M is to be set to. Before returning, the 32-bit signed
1493 ** a database file. The argument is a pointer to a 32-bit unsigned integer.
1519 ** file to the database file, but before the *-shm file is updated to
1524 ** whether or not there is a database client in another process with a wal-mode
1526 ** (void*) argument passed with this file-control should be a pointer to a
1529 ** currently has an SQL transaction open on the database. It is set to 0 if
1530 ** the database is not a wal-mode db, or if there is no such connection in any
1540 ** database is not a temp db, then the [SQLITE_FCNTL_RESET_CACHE] file-control
1541 ** purges the contents of the in-memory page cache. If there is an open
1542 ** transaction, or if the db is a temp-db, this opcode is a no-op, not an error.
1598 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1600 ** at the internal representation of an [sqlite3_mutex]. It only
1622 ** as a normal, nul-terminated, UTF-8 buffer containing the filename, but
1640 ** An instance of the sqlite3_vfs object defines the interface between
1646 ** the end. Each time such an extension occurs, the iVersion field
1653 ** Note that due to an oversight, the structure
1665 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1681 ** from xFullPathname() with an optional suffix added.
1683 ** consist of a single "-" character followed by no more than
1684 ** 11 alphanumeric and/or "-" characters.
1699 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1717 ** change the way it deals with files. For example, an application
1719 ** the open of a journal file a no-op. Writes to this journal would
1720 ** also be no-ops, and any attempt to read the journal would return
1722 ** file will be doing page-aligned sector reads and writes in a random
1742 ** be created, and that it is an error if it already exists.
1761 ** flag is never actually used and is not implemented in the built-in
1764 ** non-zero error code if there is an I/O error or if the name of
1766 ** is returned, then non-zero or zero is written into *pResOut to indicate
1780 ** of good-quality randomness into zOut. The return value is
1786 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1788 ** a 24-hour day).
1814 void *pAppData; /* Pointer to application-specific data */
1851 ** the xAccess method of an [sqlite3_vfs] object. They determine
1919 ** A call to sqlite3_initialize() is an "effective" call if it is
1922 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1924 ** are harmless no-ops.)^
1926 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1928 ** an effective call to sqlite3_shutdown() does any deinitialization.
1929 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1944 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1947 ** SQLite interfaces so that an application usually does not need to
1952 ** compile-time option, then the automatic calls to sqlite3_initialize()
1961 ** The sqlite3_os_init() routine does operating-system specific
1977 ** (using the [SQLITE_OS_OTHER=1] compile-time
1979 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
2002 ** The first argument to sqlite3_config() is an integer
2014 ** [sqlite3_shutdown()] with a first argument that is not an anytime
2017 ** implementation of an application-defined [sqlite3_os_init()].
2021 ** then this routine returns a non-zero [error code].
2035 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
2047 ** An instance of this object defines the interface between SQLite
2048 ** and low-level memory allocation routines.
2051 ** A pointer to an instance of this object is the argument to
2054 ** By creating an instance of this object
2056 ** during configuration, an application can specify an alternative
2060 ** Note that SQLite comes with several [built-in memory allocators]
2064 ** also used during testing of SQLite in order to specify an alternative
2065 ** memory allocator that simulates memory out-of-memory conditions in
2104 ** SQLite will never invoke xInit() more than once without an intervening
2111 void *(*xRealloc)(void*,int); /* Resize an allocation */
2112 int (*xSize)(void*); /* Return the size of an allocation */
2130 ** ^Calling [sqlite3_config()] with a first argument that is not an
2132 ** [sqlite3_shutdown()] is a no-op that returns SQLITE_MISUSE.
2147 ** non-zero [error code] if a discontinued or unsupported configuration option
2153 ** [threading mode] to Single-thread. In other words, it disables
2156 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2158 ** value of Single-thread and so [sqlite3_config()] will return
2164 ** [threading mode] to Multi-thread. In other words, it disables
2168 ** are enabled so that SQLite will be safe to use in a multi-threaded
2171 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2172 ** it is not possible to set the Multi-thread [threading mode] and
2187 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2194 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
2196 ** alternative low-level memory allocation routines to be used in place of
2203 ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
2224 ** disabled, the following SQLite interfaces become non-operational:
2245 ** This configuration option is a no-op if an application-defined page
2248 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
2256 ** argument must be either a NULL pointer or a pointer to an 8-byte
2263 ** ^If pMem is NULL and N is non-zero, then each database connection
2264 ** does an initial bulk allocation for page cache memory
2266 ** of -1024*N bytes if N is negative, . ^If additional
2279 ** An 8-byte aligned pointer to the memory,
2286 ** The first pointer (the memory pointer) must be aligned to an 8-byte
2293 ** pointer to an instance of the [sqlite3_mutex_methods] structure.
2294 ** The argument specifies alternative low-level mutex routines to be used
2298 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2305 ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
2311 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
2325 ** The [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to change the
2326 ** default lookaside configuration at compile-time.
2331 ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
2337 ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
2347 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
2349 ** passed through as the first parameter to the application-defined logger
2352 ** [sqlite3_log()] call and is intended to be a [result code] or an
2357 ** In a multi-threaded application, the application-defined logger
2362 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
2379 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2380 ** if that compile-time option is omitted.
2390 ** They are retained for backwards compatibility but are now no-ops.
2396 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2406 ** third parameter is passed NULL In this case. An example of using this
2412 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2419 ** compile-time maximum mmap size set by the
2420 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2422 ** changed to its compile-time default.
2427 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2428 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2434 ** is a pointer to an integer and writes into that integer the number of extra
2442 ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2444 ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
2453 ** becomes the [statement journal] spill-to-disk threshold.
2456 ** Or if the threshold is -1, statement journals are always held
2462 ** [SQLITE_STMTJRNL_SPILL] compile-time option.
2467 ** of type (int) - the new value of the sorter-reference size threshold.
2468 ** Usually, when SQLite uses an external sort to order records according
2469 ** to an ORDER BY clause, all fields required by the caller are present in the
2471 ** of a table column that its values are likely to be very large - larger
2472 ** than the configured sorter-reference size threshold - then a reference
2478 ** [SQLITE_ENABLE_SORTER_REFERENCES] compile-time option.
2483 ** [sqlite3_int64] parameter which is the default maximum size for an in-memory
2486 ** [SQLITE_FCNTL_SIZE_LIMIT] [sqlite3_file_control|file-control]. If this
2488 ** by the [SQLITE_MEMDB_DEFAULT_MAXSIZE] compile-time option. If that
2489 ** compile-time option is not set, then the default maximum is 1073741824.
2495 ** compiled with -DSQLITE_ALLOW_ROWID_IN_VIEW, in which case the capability
2497 ** changes the setting to off or on. The argument is a pointer to an integer.
2503 ** is compiled without -DSQLITE_ALLOW_ROWID_IN_VIEW (which is the usual and
2521 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
2522 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
2545 ** The [sqlite3_db_config()] interface is a var-args functions. It takes a
2550 ** page says "the N-th argument" it means "the N-th parameter past the
2551 ** configuration option" or "the (N+2)-th parameter to sqlite3_db_config()".
2557 ** non-zero [error code] if a discontinued or unsupported configuration option
2590 ** The buffer must be aligned to an 8-byte boundary.
2598 ** If the "buf" argument is NULL and an attempt
2604 ** [-DSQLITE_DEFAULT_LOOKASIDE] option can be used to set the default lookaside
2605 ** configuration at compile-time. Typical values for lookaside are 1200 for
2614 ** The first argument is an integer which is 0 to disable FK enforcement,
2616 ** unchanged. The second parameter is a pointer to an integer into which
2625 ** The first argument is an integer which is 0 to disable triggers,
2627 ** The second parameter is a pointer to an integer into which
2635 ** triggers in the main database schema or in the schemas of [ATTACH]-ed
2642 ** The first argument is an integer which is 0 to disable views,
2644 ** The second parameter is a pointer to an integer into which
2652 ** views in the main database schema or in the schemas of ATTACH-ed
2659 ** [FTS3] full-text search engine extension.
2661 ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2664 ** The second parameter is a pointer to an integer into which
2674 ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2676 ** When the first argument to this interface is 1, then only the C-API is
2678 ** this interface is 0, then both the C-API and the SQL function are disabled.
2679 ** If the first argument is -1, then no changes are made to state of either the
2680 ** C-API or the SQL function.
2681 ** The second parameter is a pointer to an integer into which
2709 ** operation (the third parameter to [sqlite3_db_config()]) is an integer
2710 ** which is positive to disable checkpoints-on-close, or zero (the default)
2712 ** The second argument (the fourth parameter) is a pointer to an integer
2713 ** into which is written 0 or 1 to indicate whether checkpoints-on-close
2714 ** have been disabled - 0 if they are not disabled, 1 if they are.
2726 ** The first argument to this setting is an integer which is 0 to disable
2728 ** unchanged. The second parameter is a pointer to an integer into which
2737 ** behavior. The first parameter passed to this operation is an integer -
2740 ** The second parameter is a pointer to an integer into which is written
2741 ** 0 or 1 to indicate whether output-for-triggers has been disabled - 0 if
2747 ** [VACUUM] in order to reset a database back to an empty database
2788 ** The first argument to this setting is an integer which is 0 to disable
2790 ** leave the setting unchanged. The second parameter is a pointer to an
2799 ** behaves as it did prior to [version 3.24.0] (2018-06-04). See the
2808 ** the legacy [double-quoted string literal] misfeature for DML statements
2810 ** default value of this setting is determined by the [-DSQLITE_DQS]
2811 ** compile-time option.
2817 ** the legacy [double-quoted string literal] misfeature for DDL statements,
2819 ** default value of this setting is determined by the [-DSQLITE_DQS]
2820 ** compile-time option.
2847 ** created database file to have a schema format version number (the 4-byte
2859 ** the [VACUUM] command will fail with an obscure error when attempting to
2873 ** by default. <p>This option takes two arguments: an integer and a pointer to
2874 ** an integer.. The first argument is 1, 0, or -1 to enable, disable, or
2888 ** two arguments which are an integer and a pointer to an integer. The first
2889 ** argument is 1, 0, or -1 to enable, disable, or leave unchanged the
2904 ** This option takes two arguments which are an integer and a pointer
2905 ** to an integer. The first argument is 1, 0, or -1 to enable, disable, or
2906 ** leave unchanged the attach-create flag, respectively. If the second
2908 ** second argument points to depending on if the attach-create flag is set
2919 ** but the database will be opened read-only. If this option is disabled,
2923 ** This option takes two arguments which are an integer and a pointer
2924 ** to an integer. The first argument is 1, 0, or -1 to enable, disable, or
2936 ** An application can disable or reenable comments in SQL text using this
2938 ** This option takes two arguments which are an integer and a pointer
2939 ** to an integer. The first argument is 1, 0, or -1 to enable, disable, or
2953 ** The second argument is a pointer to an integer. If the first argument is 1,
2955 ** option is disabled. If the first argument is -1, then the option setting
2956 ** is unchanged. The second argument, the pointer to an integer, may be NULL.
3007 ** has a unique 64-bit signed
3009 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
3034 ** ^(If an [INSERT] occurs within a trigger then this routine will
3039 ** ^An [INSERT] that fails due to a constraint violation is not a
3049 ** ^For the purposes of this routine, an [INSERT] is considered to
3087 ** does not count as an INSERT, UPDATE or DELETE statement and hence the rows
3092 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
3097 ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
3114 ** any changes performed by sub-triggers, as the sqlite3_changes()
3115 ** value will be saved and restored after each sub-trigger has run.)^
3183 ** CAPI3REF: Interrupt A Long-Running Query
3189 ** or Ctrl-C where the user wants a long query operation to halt
3197 ** ^If an SQL operation is very nearly finished at the time when
3198 ** sqlite3_interrupt() is called, then it might not have an opportunity
3201 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
3202 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
3203 ** that is inside an explicit transaction, then the entire transaction
3214 ** SQL statements is a no-op and has no effect on SQL statements
3218 ** or not an interrupt is currently in effect for [database connection] D.
3219 ** It returns 1 if an interrupt is currently in effect, or 0 otherwise.
3225 ** CAPI3REF: Determine If An SQL Statement Is Complete
3227 ** These routines are useful during command-line input to determine if the
3233 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
3248 ** then the return value from sqlite3_complete16() will be non-zero
3251 ** The input to [sqlite3_complete()] must be a zero-terminated
3252 ** UTF-8 string.
3254 ** The input to [sqlite3_complete16()] must be a zero-terminated
3255 ** UTF-16 string in native byte order.
3262 ** KEYWORDS: {busy-handler callback} {busy handler}
3267 ** an attempt is made to access a database table associated with
3284 ** ^If the callback returns non-zero, then another attempt
3295 ** to promote to an exclusive lock. The first process cannot proceed
3332 ** ^Calling this routine with an argument less than or equal to zero
3351 ** handle. In non-SQLITE_ENABLE_SETLK_TIMEOUT builds, or if the VFS does
3352 ** not support blocking locks, this function is a no-op.
3355 ** -1 to this function requests that the VFS blocks for a long time -
3359 ** Internally, each SQLite database handle store two timeout values - the
3360 ** busy-timeout (used for rollback mode databases, or if the VFS does not
3361 ** support blocking locks) and the setlk-timeout (used for blocking locks
3362 ** on wal-mode databases). The sqlite3_busy_timeout() method sets both
3363 ** values, this function sets only the setlk-timeout value. Therefore,
3364 ** to configure separate busy-timeout and setlk-timeout values for a single
3368 ** 1 to 0, the last connection takes an exclusive lock on the database,
3370 ** new connection that tries to read from the database fails with an
3398 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
3400 ** to zero-terminated strings that contain the names of the columns.
3402 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
3409 ** ^(As an example of the result table format, suppose a query result
3414 ** -----------------------
3422 ** in an array named azResult. Then azResult holds this content:
3436 ** semicolon-separated SQL statements in the zero-terminated UTF-8
3456 sqlite3 *db, /* An open database */
3468 ** These routines are work-alikes of the "printf()" family of functions
3472 ** plus some additional non-standard formats ([%q], [%Q], [%w], and [%z]).
3473 ** See the [built-in printf()] documentation for details.
3486 ** first two parameters is reversed from snprintf().)^ This is an
3496 ** guarantees that the buffer is always zero-terminated. ^The first
3499 ** written will be n-1 characters.
3503 ** See also: [built-in printf()], [printf() SQL function]
3515 ** does not include operating-system specific [VFS] implementation. The
3526 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
3527 ** of a signed 32-bit integer.
3532 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
3537 ** might result if sqlite3_free() is called with a non-NULL pointer that
3557 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
3558 ** of a 32-bit signed integer.
3572 ** is always aligned to at least an 8 byte boundary, or to a
3573 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
3597 ** routines, which form the built-in memory allocation subsystem.
3602 ** value of [sqlite3_memory_used()] since the high-water mark
3609 ** ^The memory high-water mark is reset to the current value of
3612 ** by [sqlite3_memory_highwater(1)] is the high-water mark
3619 ** CAPI3REF: Pseudo-Random Number Generator
3621 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
3624 ** the built-in random() and randomblob() SQL functions. This interface allows
3634 ** ^If the previous call to this routine had an N of 1 or more and a
3635 ** non-NULL P then the pseudo-randomness is generated
3642 ** CAPI3REF: Compile-Time Authorization Callbacks
3646 ** ^This routine registers an authorizer callback with a particular
3658 ** rejected with an error. ^If the authorizer callback returns
3661 ** the authorizer will fail with an error message.
3666 ** authorizer will fail with an error message explaining that
3671 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
3673 ** to the callback are either NULL pointers or zero-terminated strings
3683 ** return can be used to deny an untrusted user access to individual
3688 ** is invoked once for that table with a column name that is an empty string.
3693 ** An authorizer is used when [sqlite3_prepare | preparing]
3694 ** SQL statements from an untrusted source, to ensure that the SQL statements
3697 ** example, an application may allow a user to enter arbitrary
3700 ** database. An authorizer could then be put in place while the
3701 ** user-entered SQL is being [sqlite3_prepare | prepared] that
3707 ** in addition to using an authorizer.
3720 ** statement might be re-prepared during [sqlite3_step()] due to a
3748 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
3749 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
3756 ** second parameter to the callback is an integer code that specifies
3766 ** is the name of the inner-most trigger or view that is responsible for
3768 ** top-level SQL code.
3817 ** various times when an SQL statement is being run by [sqlite3_step()].
3818 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3822 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3824 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3829 ** the original statement text and an estimate of wall-clock time
3849 ** to [sqlite3_trace_v2(D,M,X,P)] is an OR-ed combination of one or more of
3863 ** <dd>^An SQLITE_TRACE_STMT callback is invoked when a prepared statement
3868 ** is the unexpanded SQL text of the prepared statement or an SQL comment
3871 ** interface by using the X argument when X begins with "--" and invoking
3875 ** <dd>^An SQLITE_TRACE_PROFILE callback provides approximately the same
3878 ** X argument points to a 64-bit integer which is approximately
3883 ** <dd>^An SQLITE_TRACE_ROW callback is invoked whenever a prepared
3889 ** <dd>^An SQLITE_TRACE_CLOSE callback is invoked when a database
3908 ** M argument should be the bitwise OR-ed combination of
3945 ** database connection D. An example use for this
3960 ** ^If the progress callback returns non-zero, the operation is
3983 ** ^These routines open an SQLite database file as specified by the
3984 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3985 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3987 ** returned in *ppDb, even if an error occurs. The only exception is that
3991 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
3993 ** an English language description of the error following a failure of any
3996 ** ^The default encoding will be UTF-8 for databases created using
3998 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
4000 ** Whether or not an error occurs when it is opened, resources
4012 ** <dd>The database is opened in read-only mode. If the database does
4013 ** not already exist, an error is returned.</dd>)^
4019 ** an error is returned. For historical reasons, if opening in
4020 ** read-write mode fails due to OS-level permissions, an attempt is
4021 ** made to open it in read-only mode. [sqlite3_db_readonly()] can be
4023 ** read-write.</dd>)^
4039 ** <dd>The database will be opened as an in-memory database. The database
4040 ** is named by the "filename" argument for the purposes of cache-sharing,
4045 ** <dd>The new database connection will use the "multi-thread"
4063 ** this option is a no-op.
4076 ** to return an extended result code.</dd>
4089 ** upon it. Note in particular that the SQLITE_OPEN_EXCLUSIVE flag is a no-op
4100 ** ^If the filename is ":memory:", then a private, temporary in-memory database
4101 ** is created for the connection. ^This in-memory database will vanish when
4108 ** ^If the filename is an empty string, then a private, temporary
4109 ** on-disk database will be created. ^This private database will be
4119 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
4125 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
4126 ** authority, then it must be either an empty string or the string
4127 ** "localhost". ^If the authority is not an empty string or "localhost", an
4133 ** then it is interpreted as an absolute path. ^If the path does not begin
4136 ** ^(On windows, the first component of an absolute path
4142 ** SQLite and its built-in [VFSes] interpret the
4149 ** an empty string the default VFS object is used. ^Specifying an unknown
4150 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
4156 ** an error)^.
4157 ** ^If "ro" is specified, then the database is opened for read-only
4160 ** "rw", then the database is opened for read-write (but not create)
4164 ** set to "memory" then a pure [in-memory database] that never reads
4165 ** or writes from disk is used. ^It is an error to specify a value for
4191 ** read-only media. ^When immutable is set, SQLite assumes that the
4193 ** privilege, and so the database is opened read-only and all locking
4201 ** ^Specifying an unknown parameter in the query component of a URI is not an
4217 ** An error. "darkstar" is not a recognized authority.
4218 ** <tr><td style="white-space:nowrap">
4222 ** necessary - space characters can be used literally
4225 ** Open file "data.db" in the current directory for read-only access.
4226 ** Regardless of whether or not shared-cache mode is enabled by
4228 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
4229 ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
4230 ** that uses dot-files in place of posix advisory locking.
4232 ** An error. "readonly" is not a valid option for the "mode" parameter.
4238 ** percent sign - "%" - followed by exactly two hexadecimal digits
4239 ** specifying an octet value. ^Before the path or query components of a
4240 ** URI filename are interpreted, they are encoded using UTF-8 and all
4242 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
4246 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
4248 ** characters must be converted to UTF-8 prior to passing them into
4258 const char *filename, /* Database filename (UTF-8) */
4262 const void *filename, /* Database filename (UTF-16) */
4266 const char *filename, /* Database filename (UTF-8) */
4297 ** a pointer to an empty string.
4303 ** case or if the value begins with a non-zero number. The
4311 ** 64-bit signed integer and returns that integer, or D if P does not
4312 ** exist. If the value of P is something other than an integer, then
4316 ** the value) of the N-th query parameter for filename F, or a NULL
4318 ** parameters minus 1. The N value is zero-based so N should be 0 to obtain
4350 ** If F is the name of an sqlite database file, journal file, or WAL file
4354 ** If F is the name of an sqlite database file, journal file, or WAL file
4359 ** If F is the name of an sqlite database file, journal file, or WAL file
4377 ** ^If X is the name of a rollback or WAL-mode journal file that is
4383 ** only. It is not a general-purpose interface.
4401 ** an array P of N URI Key/Value pairs. The result from
4417 ** The P parameter in sqlite3_create_filename(D,J,W,N,P) should be an array
4427 ** sqlite3_free_filename(Y) where Y is a NULL pointer is a harmless no-op.
4463 ** change the value of the error code. The error-code preserving
4474 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
4475 ** text that describes the error, as either UTF-8 or UTF-16 respectively,
4483 ** ^The sqlite3_errstr(E) interface returns the English-language text
4484 ** that describes the [result code] E, as UTF-8, or NULL if E is not an
4494 ** SQL, then the sqlite3_error_offset() function returns -1.
4506 ** If an interface fails with SQLITE_MISUSE, that means the interface
4521 ** An instance of this object represents a single SQL statement that
4529 ** The life-cycle of a prepared statement object usually goes like this:
4544 ** CAPI3REF: Run-time Limits
4557 ** set at compile-time by a C preprocessor macro called
4566 ** simply invoke this interface with the third parameter set to -1.
4568 ** Run-time limits are intended for use in applications that manage
4570 ** by untrusted external sources. An example application might be a
4578 ** created by an untrusted script can be contained using the
4581 ** New run-time limit categories may be added in future releases.
4586 ** CAPI3REF: Run-Time Limit Categories
4590 ** that can be lowered at run-time using [sqlite3_limit()].
4599 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
4603 ** result set of a [SELECT] or the maximum number of columns in an index
4604 ** or in an ORDER BY or GROUP BY clause.</dd>)^
4614 ** used to implement an SQL statement. If [sqlite3_prepare_v2()] or
4616 ** in a single prepared statement, an SQLITE_NOMEM error is returned.</dd>)^
4631 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
4676 ** <dd>The SQLITE_PREPARE_NORMALIZE flag is a no-op. This flag used
4685 ** to return an error (error code SQLITE_ERROR) if the statement uses
4692 ** compiles to see if some SQL syntax is well-formed, without generating
4705 ** CAPI3REF: Compiling An SQL Statement
4710 ** To execute an SQL statement, it must first be compiled into a byte-code
4716 ** [sqlite3_prepare_v3()] has an extra "prepFlags" option that is used
4719 ** The use of the UTF-8 interfaces is preferred, as SQLite currently
4720 ** does all parsing using UTF-8. The UTF-16 interfaces are provided
4721 ** as a convenience. The UTF-16 interfaces work by converting the
4722 ** input text into UTF-8, then invoking the corresponding UTF-8 interface.
4729 ** as either UTF-8 or UTF-16. The sqlite3_prepare(), sqlite3_prepare_v2(),
4731 ** interfaces use UTF-8, and sqlite3_prepare16(), sqlite3_prepare16_v2(),
4732 ** and sqlite3_prepare16_v3() use UTF-16.
4740 ** If the caller knows that the supplied string is nul-terminated, then
4741 ** there is a small performance advantage to passing an nByte parameter that
4743 ** the nul-terminator.
4745 ** characters, even for the UTF-16 interfaces.
4753 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
4754 ** to NULL. ^If the input text contains no SQL (if the input is an empty
4761 ** otherwise an [error code] is returned.
4777 ** retries will occur before sqlite3_step() gives up and returns an error.
4781 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
4795 ** ^The specific value of a WHERE-clause [parameter] might influence the
4796 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
4797 ** or [GLOB] operator or if the parameter is compared to an indexed column
4798 ** and the [SQLITE_ENABLE_STAT4] compile-time option is enabled.
4810 const char *zSql, /* SQL statement, UTF-8 encoded */
4817 const char *zSql, /* SQL statement, UTF-8 encoded */
4824 const char *zSql, /* SQL statement, UTF-8 encoded */
4832 const void *zSql, /* SQL statement, UTF-16 encoded */
4839 const void *zSql, /* SQL statement, UTF-16 encoded */
4846 const void *zSql, /* SQL statement, UTF-16 encoded */
4857 ** ^The sqlite3_sql(P) interface returns a pointer to a copy of the UTF-8
4861 ** ^The sqlite3_expanded_sql(P) interface returns a pointer to a UTF-8
4864 ** ^The sqlite3_normalized_sql(P) interface returns a pointer to a UTF-8
4880 ** ^The [SQLITE_TRACE_SIZE_LIMIT] compile-time option limits the size of
4881 ** bound parameter expansions. ^The [SQLITE_OMIT_TRACE] compile-time
4892 ** the [SQLITE_ENABLE_NORMALIZE] compile-time option is defined.
4901 ** CAPI3REF: Determine If An SQL Statement Writes The Database
4904 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
4908 ** Note that [application-defined SQL functions] or
4910 ** ^(For example, if an application defines a function "eval()" that
4912 ** change the database file through side-effects:
4937 ** ^For example, an UPDATE statement might have a WHERE clause that
4938 ** makes it a no-op, but the sqlite3_stmt_readonly() result would still
4940 ** read-only no-op if the table already exists, but
4943 ** ^If prepared statement X is an [EXPLAIN] or [EXPLAIN QUERY PLAN]
4954 ** prepared statement S is an EXPLAIN statement, or 2 if the
4955 ** statement S is an EXPLAIN QUERY PLAN.
4957 ** an ordinary statement or a NULL pointer.
4984 ** is called to convert the statement into an ordinary statement, the EXPLAIN
4989 ** changed, or an error code if the explain mode could not be changed.
5000 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
5026 ** An sqlite3_value object may be either "protected" or "unprotected".
5028 ** will accept either a protected or an unprotected sqlite3_value.
5032 ** protected sqlite3_value from an unprotected sqlite3_value.
5035 ** a mutex is held. An internal mutex is held for a protected
5036 ** sqlite3_value object but no mutex is held for an unprotected
5037 ** sqlite3_value object. If SQLite is compiled to be single-threaded
5048 ** implementation of [application-defined SQL functions] are protected.
5064 ** The context in which an SQL function executes is stored in an
5065 ** sqlite3_context object. ^A pointer to an sqlite3_context object
5066 ** is always first parameter to [application-defined SQL functions].
5067 ** The application-defined SQL function implementation will pass this
5093 ** In the templates above, NNN represents an integer literal,
5094 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
5103 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
5117 ** it should be a pointer to well-formed UTF8 text.
5119 ** it should be a pointer to well-formed UTF16 text.
5121 ** it should be a pointer to a well-formed unicode string that is
5125 ** [[byte-order determination rules]] ^The byte-order of
5126 ** UTF16 input text is determined by the byte-order mark (BOM, U+FEFF)
5143 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
5179 ** (just an integer to hold its size) while it is being processed.
5183 ** ^A negative value for the zeroblob results in a zero-length BLOB.
5185 ** ^The sqlite3_bind_pointer(S,I,P,T,D) routine causes the I-th parameter in
5186 ** [prepared statement] S to have an SQL value of NULL, but to also be
5204 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
5257 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
5266 ** ^The first host parameter has an index of 1, not 0.
5268 ** ^If the value N is out of range or if the N-th parameter is
5270 ** always in UTF-8 encoding even if the named parameter was
5271 ** originally specified as UTF-16 in [sqlite3_prepare16()],
5284 ** ^Return the index of an SQL parameter given its name. ^The
5288 ** name must be given in UTF-8 even if the original statement
5289 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()] or
5314 ** [prepared statement] returns no data (for example an [UPDATE]).
5330 ** interface returns a pointer to a zero-terminated UTF-8 string
5331 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
5332 ** UTF-16 string. ^The first parameter is the [prepared statement]
5343 ** (for example during a conversion from UTF-8 to UTF-16) then a
5347 ** that column, if there is an AS clause. If there is no AS clause
5362 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
5371 ** ^The names returned are the original un-aliased names of the
5377 ** ^The left-most column is column 0 for these routines.
5379 ** ^If the Nth column returned by the statement is an expression or
5386 ** UTF-16 encoded strings and the other functions return UTF-8.
5389 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
5409 ** returned result set of that [SELECT] is a table column (not an
5411 ** column is returned.)^ ^If the Nth column of the result set is an
5413 ** ^The returned string is always UTF-8 encoded.
5426 ** ^SQLite uses dynamic run-time typing. ^So just because a column
5437 ** CAPI3REF: Evaluate An SQL Statement
5461 ** or occurs outside of an explicit transaction, then you can retry the
5462 ** statement. If the statement is not a [COMMIT] and occurs within an
5476 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
5496 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
5501 ** break because any application that ever receives an SQLITE_MISUSE error
5502 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
5532 ** will return non-zero if previous call to [sqlite3_step](P) returned
5534 ** where it always returns zero since each step of that multi-step
5548 ** <li> 64-bit signed integer
5549 ** <li> 64-bit IEEE floating point number
5582 ** <tr><td><b>sqlite3_column_int</b><td>→<td>32-bit INTEGER result
5583 ** <tr><td><b>sqlite3_column_int64</b><td>→<td>64-bit INTEGER result
5584 ** <tr><td><b>sqlite3_column_text</b><td>→<td>UTF-8 TEXT result
5585 ** <tr><td><b>sqlite3_column_text16</b><td>→<td>UTF-16 TEXT result
5586 ** <tr><td><b>sqlite3_column_value</b><td>→<td>The result as an
5590 ** or a UTF-8 TEXT result in bytes
5592 ** <td>→ <td>Size of UTF-16
5624 ** if the query returns an integer but the sqlite3_column_text() interface
5625 ** is used to extract the value) then an automatic type conversion is performed.
5644 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
5646 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
5647 ** the string to UTF-8 and then returns the number of bytes.
5649 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
5653 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
5655 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
5656 ** the string to UTF-16 and then returns the number of bytes.
5658 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
5669 ** even empty strings, are always zero-terminated. ^The return
5670 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
5676 ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
5678 ** an unprotected sqlite3_value object may only be used safely with
5686 ** [application-defined SQL functions] or [virtual tables], not within
5687 ** top-level application code.
5705 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
5726 ** sqlite3_column_text16() is called. A zero-terminator might
5728 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
5730 ** to UTF-16.</li>
5731 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
5733 ** to UTF-8.</li>
5736 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
5767 ** fail if an out-of-memory error occurs during a format conversion.
5768 ** Only the following subset of interfaces are subject to out-of-memory
5779 ** If an out-of-memory error occurs, then the return value from these
5780 ** routines is the same as if the column had contained an SQL NULL value.
5781 ** Valid SQL NULL returns can be distinguished from out-of-memory errors
5815 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
5830 ** object back to its initial state, ready to be re-executed.
5846 ** [prepared statement] S indicated an error, then
5847 ** [sqlite3_reset(S)] returns an appropriate [error code].
5848 ** ^The [sqlite3_reset(S)] interface might also return an [error code]
5850 ** the prepared statement caused a new error. ^For example, if an
5881 ** function is to be added. ^If an application uses more than one database
5882 ** connection then application-defined SQL functions must be added
5886 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
5887 ** representation, exclusive of the zero-terminator. ^Note that the name
5888 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
5894 ** aggregate takes. ^If this parameter is -1, then the SQL function or
5897 ** parameter is less than -1 or greater than 127 then the behavior is
5904 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
5905 ** implementation invokes [sqlite3_value_text16be()] on an input, or
5916 ** deterministic. The built-in [random()] SQL function is an example of a
5927 ** all application-defined SQL functions that do not need to be
5931 ** Without this flag, an attacker might be able to modify the schema of
5936 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
5941 ** pointers to C-language functions that implement the SQL function or
5942 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
5944 ** parameters. ^An aggregate SQL function requires an implementation of xStep
5945 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
5951 ** C-language callbacks that implement the new function. xStep and xFinal
5952 ** must both be non-NULL. xValue and xInverse may either both be NULL, in
5954 ** non-NULL, in which case the new function may be used as either an aggregate
5957 ** [user-defined window functions|available here].
5972 ** SQL function is used. ^A function implementation with a non-negative
5981 ** ^Built-in functions may be overloaded by new application-defined functions.
5983 ** ^An application-defined function is permitted to call other
6038 #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
6039 #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
6040 #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
6067 ** from top-level SQL, and cannot be used in VIEWs or TRIGGERs nor in
6072 ** [application-defined SQL function]
6073 ** that has side-effects or that could potentially leak sensitive information.
6074 ** This will prevent attacks in which an application is tricked
6076 ** modified to invoke the application-defined function in ways that are
6080 ** [application-defined SQL functions], regardless of whether or not they
6084 ** that do not have access to the application-defined functions.
6089 ** to cause problems even if misused. An innocuous function should have
6091 ** input parameters. The [abs|abs() function] is an example of an
6096 ** exactly the same. The [random|random() function] is an example of a
6103 ** the function is tagged with SQLITE_INNOCUOUS. Most built-in functions
6105 ** SQLITE_INNOCUOUS flag for application-defined functions unless the
6107 ** security-adverse side-effects and information-leaks.
6112 ** [sqlite3_value_subtype()] to inspect the sub-types of its arguments.
6113 ** This flag instructs SQLite to omit some corner-case optimizations that
6119 ** a non-zero subtype was specified by the function argument expression.
6123 ** [sqlite3_result_subtype()] to cause a sub-type to be associated with its
6127 ** might become a no-op if the function is used as term in an
6134 ** The SQLITE_SELFORDER1 flag indicates that the function is an aggregate
6136 ** ordered-set aggregate SQL notation with a single ORDER BY term can be
6137 ** used to invoke this function. If the ordered-set aggregate notation is
6138 ** used on a function that lacks this flag, then an error is raised. Note
6139 ** that the ordered-set aggregate syntax is only available if SQLite is
6140 ** built using the -DSQLITE_ENABLE_ORDERED_SET_AGGREGATES compile-time option.
6179 ** <tr><td><b>sqlite3_value_int</b><td>→<td>32-bit INTEGER value
6180 ** <tr><td><b>sqlite3_value_int64</b><td>→<td>64-bit INTEGER value
6182 ** <tr><td><b>sqlite3_value_text</b><td>→<td>UTF-8 TEXT value
6183 ** <tr><td><b>sqlite3_value_text16</b><td>→<td>UTF-16 TEXT value in
6185 ** <tr><td><b>sqlite3_value_text16be</b><td>→<td>UTF-16be TEXT value
6186 ** <tr><td><b>sqlite3_value_text16le</b><td>→<td>UTF-16le TEXT value
6189 ** or a UTF-8 TEXT in bytes
6191 ** <td>→ <td>Size of UTF-16
6198 ** <td>→ <td>True if the column is unchanged in an UPDATE
6209 ** implement [application-defined SQL functions] and [virtual tables].
6212 ** Any attempt to use these routines on an [unprotected sqlite3_value]
6217 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
6219 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
6220 ** in the native byte-order of the host machine. ^The
6222 ** extract UTF-16 strings as big-endian and little-endian respectively.
6235 ** Other interfaces might change the datatype for an sqlite3_value object.
6243 ** numeric affinity to the value. This means that an attempt is
6244 ** made to convert the value to an integer or floating point. If
6257 ** was unchanging). ^Within an [xUpdate] method, any value for which
6260 ** than within an [xUpdate] method call for an UPDATE statement, then
6263 ** ^The sqlite3_value_frombind(X) interface returns non-zero if the
6265 ** interfaces. ^If X comes from an SQL literal value, or a table column,
6266 ** or an expression, then sqlite3_value_frombind(X) returns zero.
6278 ** fail if an out-of-memory error occurs during a format conversion.
6279 ** Only the following subset of interfaces are subject to out-of-memory
6292 ** If an out-of-memory error occurs, then the return value from these
6293 ** routines is the same as if the column had contained an SQL NULL value.
6294 ** Valid SQL NULL returns can be distinguished from out-of-memory errors
6316 ** CAPI3REF: Report the internal text encoding state of an sqlite3_value object
6331 ** internal state of an [sqlite3_value] object. Ordinary applications should
6332 ** not need to know what the internal state of an sqlite3_value object is and
6342 ** an [application-defined SQL function] argument V. The subtype
6345 ** routine to set the subtype for the return value of an SQL function.
6347 ** Every [application-defined SQL function] that invokes this interface
6366 ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
6368 ** then sqlite3_value_free(V) is a harmless no-op.
6388 ** an aggregate query, the xStep() callback of the aggregate function
6429 ** the application-defined function is running.
6449 ** These functions may be used by (non-aggregate) SQL functions to
6453 ** might be preserved. An example of where this might be useful is in a
6454 ** regular-expression matching function. The compiled version of the regular
6462 ** value to the application-defined function. ^N is zero for the left-most
6468 ** N-th argument of the application-defined function. ^Subsequent
6494 ** to sqlite3_set_auxdata() might still return NULL if an out-of-memory
6500 ** function parameters that are compile-time constants, including literal
6503 ** The value of the N parameter to these interfaces should be non-negative.
6528 ** If P and X are both non-NULL, then the destructor X is invoked with
6531 ** <li> An out-of-memory error occurs during the call to
6544 ** to store additional information about an SQLite database connection.
6559 ** languages or in other circumstances where it might be possible for an
6587 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
6590 ** CAPI3REF: Setting The Result Of An SQL Function
6603 ** an application-defined function to be the BLOB whose content is pointed
6608 ** interfaces set the result of the application-defined function to be
6612 ** an application-defined function to be a floating point value specified
6616 ** cause the implemented SQL function to throw an exception.
6619 ** as the text of an error message. ^SQLite interprets the error
6620 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
6621 ** interprets the string from sqlite3_result_error16() as UTF-16 using
6622 ** the same [byte-order determination rules] as [sqlite3_bind_text16()].
6627 ** sqlite3_result_error16() is non-negative then SQLite takes that many
6634 ** returned by SQLite as a result of an error in a function. ^By default,
6638 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
6641 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
6645 ** of the application-defined function to be the 32-bit signed integer
6648 ** of the application-defined function to be the 64-bit signed integer
6652 ** of the application-defined function to be NULL.
6656 ** set the return value of the application-defined function to be
6657 ** a text string which is represented as UTF-8, UTF-16 native byte order,
6658 ** UTF-16 little endian, or UTF-16 big endian, respectively.
6659 ** ^The sqlite3_result_text64() interface sets the return value of an
6660 ** application-defined function to be a text string in an encoding
6670 ** is non-negative, then as many bytes (not characters) of the text
6671 ** pointed to by the 2nd parameter are taken as the application-defined
6672 ** function result. If the 3rd parameter is non-negative, then it
6679 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
6695 ** byte-order mark (BOM, U+FEFF) then the BOM is removed from the
6697 ** byte-order specified by the BOM. ^The byte-order specified by
6698 ** the BOM at the beginning of the text overrides the byte-order
6701 ** with bytes 0xfe, 0xff (a big-endian byte-order mark) then the
6712 ** the application-defined function to be a copy of the
6717 ** ^A [protected sqlite3_value] object may always be used where an
6721 ** ^The sqlite3_result_pointer(C,P,T,D) interface sets the result to an
6723 ** also associates the host-language pointer P or type T with that
6724 ** NULL value such that the pointer can be retrieved within an
6725 ** [application-defined SQL function] using [sqlite3_value_pointer()].
6733 ** than the one containing the application-defined function that received
6761 ** CAPI3REF: Setting The Subtype Of An SQL Function
6765 ** the result from the [application-defined SQL function] with
6772 ** Every [application-defined SQL function] that invokes this interface
6780 ** If SQLite is compiled with -DSQLITE_STRICT_SUBTYPE=1, then any
6783 ** an error. Future versions of SQLite might enable -DSQLITE_STRICT_SUBTYPE=1
6795 ** ^The name of the collation is a UTF-8 string
6797 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
6814 ** on an even byte address.
6816 ** ^The fourth argument, pArg, is an application data pointer that is passed
6831 ** function must return an integer that is negative, zero, or positive
6836 ** must give an equivalent answer when invoked with equivalent strings.
6860 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
6898 ** [database connection] to be invoked whenever an undefined collation
6903 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
6904 ** the names are passed as UTF-16 in machine native byte order.
6905 ** ^A call to either function replaces the existing collation-needed callback.
6958 ** VFS and operating system. Some system treat a negative argument as an
6971 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
6973 ** is a NULL pointer, then SQLite performs a search for an appropriate
7009 ** features that require the use of temporary files may fail. Here is an
7013 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
7014 ** TemporaryFolder->Path->Data();
7017 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
7030 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
7069 ** a non-NULL value will be copied into memory obtained from [sqlite3_malloc]
7074 ** the current directory on the sub-platforms of Win32 where that concept is
7078 ** UTF-8 or UTF-16, respectively.
7097 ** CAPI3REF: Test For Auto-Commit Mode
7101 ** ^The sqlite3_get_autocommit() interface returns non-zero or
7105 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
7107 ** If certain kinds of errors occur on a statement within a multi-statement
7112 ** an error is to use this function.
7138 ** for the N-th database on database connection D, or a NULL pointer if N is
7139 ** out of range. An N value of 0 means the main database file. An N of 1 is
7140 ** the "temp" schema. Larger values of N correspond to various ATTACH-ed
7148 ** remember the string long-term should make their own copy. Applications that
7150 ** threads should mutex-protect calls to this API and should make their own
7162 ** connection D, or if database N is a temporary or in-memory database, then
7163 ** this function will return either a NULL pointer or an empty string.
7167 ** is [DETACH]-ed or until the database connection closes.
7171 ** will be an absolute pathname, even if the filename used
7188 ** CAPI3REF: Determine if a database is read-only
7192 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
7211 ** a valid schema, then -1 is returned.
7259 ** [sqlite3_next_stmt(D,S)] must refer to an open database
7277 ** ^If the callback on a commit hook function returns non-zero,
7299 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
7301 ** hook returning non-zero, just as it would be with any other rollback.
7304 ** rolled back if an explicit "ROLLBACK" statement is executed, or
7305 ** an error or constraint causes an implicit rollback to occur.
7321 ** the schema-name of the attached database that is being autovacuumed,
7329 ** <p>^If there are multiple ATTACH-ed database files that are being
7339 ** ^The X parameter to sqlite3_autovacuum_pages(D,C,P,X) is an optional
7403 ** ^In the case of an update, this is the [rowid] after the update takes place.
7410 ** is not invoked when conflicting rows are deleted because of an
7452 ** [-DSQLITE_OMIT_SHARED_CACHE]. The [-DSQLITE_OMIT_SHARED_CACHE]
7453 ** compile-time option is recommended because the
7456 ** ^Cache sharing is enabled and disabled for an entire process.
7467 ** successfully. An [error code] is returned otherwise.)^
7479 ** shared cache mode should be enabled per-database connection via
7483 ** 32-bit integer is atomic.
7485 ** See Also: [SQLite Shared-Cache Mode]
7493 ** of heap memory by deallocating non-essential memory allocations
7495 ** pages to improve performance is an example of non-essential memory.
7498 ** ^The sqlite3_release_memory() routine is a no-op returning zero
7512 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
7532 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
7543 ** the heap limit prior to the call, or negative in the case of an
7547 ** sqlite3_soft_heap_limit64(-1) or sqlite3_hard_heap_limit(-1).
7571 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
7572 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
7573 ** <li> An alternative page cache implementation is specified using
7605 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
7609 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
7618 ** (i.e. "main", "temp", or an attached database) containing the specified
7646 ** ^If the specified table is actually a view, an [error code] is returned.
7649 ** is not a [WITHOUT ROWID] table and an
7664 ** parsed, if that has not already been done, and returns an error if
7676 int *pAutoinc /* OUTPUT: True if column is auto-increment */
7680 ** CAPI3REF: Load An Extension
7683 ** ^This interface loads an SQLite extension library from the named file.
7685 ** ^The sqlite3_load_extension() interface attempts to load an
7688 ** with various operating-system specific extensions added.
7694 ** ^(zProc may be 0, in which case SQLite will try to come up with an
7697 ** X consists of the lower-case equivalent of all ASCII alphabetic
7702 ** ^If an error occurs and pzErrMsg is not 0, then the
7712 ** otherwise an error will be returned.
7736 ** [extension loading] while evaluating user-entered SQL, the following API
7744 ** ^This interface enables or disables both the C-API
7747 ** to enable or disable only the C-API.)^
7767 ** arguments and expects an integer result as if the signature of the
7778 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
7779 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
7780 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
7783 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
7786 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
7787 ** on the list of automatic extensions is a harmless no-op. ^No entry point
7889 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
7901 ** expr on the right-hand side can be evaluated (and thus the constraint
7905 ** and makes other simplifications to the WHERE clause in an attempt to
7916 ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
7922 ** non-zero.
7926 ** the right-hand side of the corresponding aConstraint[] is evaluated
7927 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
7930 ** aConstraintUsage[].omit flag is an optimization hint. When the omit flag
7946 ** ^The estimatedCost value is an estimate of the cost of a particular
7948 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
7950 ** binary search on a unique indexed field of an SQLite table with N rows.
7952 ** ^The estimatedRows value is an estimate of the number of rows that
7975 ** used with an SQLite version earlier than 3.8.2, the results of attempting
7989 int iColumn; /* Column constrained. -1 for ROWID */
7992 int iTermOffset; /* Used internally - xBestIndex should ignore */
8033 ** an operator that is part of a constraint term in the WHERE clause of
8036 ** ^The left-hand operand of the operator is given by the corresponding
8037 ** aConstraint[].iColumn field. ^An iColumn of -1 indicates the left-hand
8040 ** operators have no left-hand operand, and so for those operators the
8049 ** The right-hand operands for each constraint might be accessible using
8050 ** the [sqlite3_vtab_rhs_value()] interface. Usually the right-hand
8052 ** in the input SQL. If the right-hand operand is another column or an
8056 ** SQLITE_INDEX_CONSTRAINT_ISNOTNULL operators have no right-hand operand
8061 ** the [sqlite3_vtab_collation()] interface. For most real-world virtual
8097 ** parameter is an arbitrary client data pointer that is passed through
8136 ** The L parameter must be either NULL or a pointer to an array of pointers
8158 ** ^Virtual tables methods can set an error message by assigning a
8216 ** of the new function always causes an exception to be thrown. So
8224 ** CAPI3REF: A Handle To An Open BLOB
8227 ** An instance of this object represents an open BLOB on which
8256 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
8258 ** read-only access.
8261 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
8275 ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
8293 ** ^(If the row that a BLOB handle points to is modified by an
8294 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
8299 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
8310 ** and the built-in [zeroblob] SQL function may be used to create a
8311 ** zero-filled blob to read or write using the incremental-blob interface.
8334 ** ^This function is used to move an existing [BLOB handle] so that it points
8338 ** remain the same. Moving an existing [BLOB handle] to a new row is
8341 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
8344 ** it does not contain a blob or text value, or if another error occurs, an
8347 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
8348 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
8359 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
8360 ** unconditionally. Even if this routine returns an error code, the
8363 ** ^If the blob handle being closed was opened for read-write access, and if
8364 ** the database is in auto-commit mode and there are no other open read-write
8366 ** committed. ^If an error occurs while committing the transaction, an error
8369 ** Calling this function with an argument that is not a NULL pointer or an
8372 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
8379 ** CAPI3REF: Return The Size Of An Open BLOB
8398 ** ^(This function is used to read data from an open [BLOB handle] into a
8399 ** caller-supplied buffer. N bytes of data are copied into buffer Z
8408 ** ^An attempt to read from an expired [BLOB handle] fails with an
8412 ** Otherwise, an [error code] or an [extended error code] is returned.)^
8427 ** ^(This function is used to write data into an open [BLOB handle] from a
8428 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
8432 ** Otherwise, an [error code] or an [extended error code] is returned.)^
8449 ** ^An attempt to write to an expired [BLOB handle] fails with an
8468 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
8477 ** ^Names are zero-terminated UTF-8 strings.
8484 ** ^To make an existing VFS into the default VFS, register it again
8487 ** VFS is registered with a name that is NULL or an empty string,
8507 ** of these mutex routines. An appropriate implementation
8508 ** is selected automatically at compile-time. The following
8519 ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
8524 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
8561 ** cases where it really needs one. If a faster non-recursive mutex
8591 ** mutex must be exited an equal number of times before another thread
8593 ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
8598 ** sqlite3_mutex_try() as an optimization, so this is acceptable
8610 ** then any of the four routines behaves as a no-op.
8623 ** An instance of this structure defines the low-level routines
8630 ** creates and populates an instance of this structure to pass
8632 ** Additionally, an instance of this structure can be used as an
8667 ** (i.e. it is acceptable to provide an implementation that segfaults if
8673 ** xMutexInit() must be no-ops.
8703 ** never uses these routines except inside an assert() and applications
8719 ** the routine should return 1. This seems counter-intuitive since
8723 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
8739 ** next. Applications that override the built-in mutex logic must be
8755 #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
8770 ** ^If the [threading mode] is Single-thread or Multi-thread then this
8776 ** CAPI3REF: Low-Level Control Of Database Files
8811 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
8823 ** purposes. ^The first parameter is an operation code that determines
8892 ** by enclosing in double-quotes) so as not to confuse the parser.
8897 ** The sqlite3_keyword_name(N,Z,L) interface finds the 0-based N-th keyword and
8900 ** zero-terminated. The sqlite3_keyword_name(N,Z,L) routine returns
8906 ** the L-byte UTF8 identifier that Z points to is a keyword, returning non-zero
8910 ** a keyword as an identifier as long as such use does not result in a
8918 ** <li> Put all identifier names inside double-quotes. This is the official
8929 ** compile-time options. For example, "VACUUM" is not a keyword if
8930 ** SQLite is compiled with the [-DSQLITE_OMIT_VACUUM] option. Also,
8941 ** An instance of the sqlite3_str object contains a dynamically-sized
8944 ** The lifecycle of an sqlite3_str object is as follows:
8965 ** valid [sqlite3_str] object, though in the event of an out-of-memory
9001 ** These interfaces add content to an sqlite3_str object previously obtained
9005 ** [sqlite3_str_vappendf(X,F,V)] interfaces uses the [built-in printf]
9010 ** onto the end of the [sqlite3_str] object X. N must be non-negative.
9011 ** S must contain at least N non-zero bytes of content. To append a
9012 ** zero-terminated string in its entirety, use the [sqlite3_str_appendall()]
9016 ** zero-terminated string S onto the end of [sqlite3_str] object X.
9019 ** single-byte character C onto the end of [sqlite3_str] object X.
9025 ** These methods do not return a result code. ^If an error occurs, that fact
9040 ** These interfaces return the current status of an [sqlite3_str] object.
9044 ** an appropriate error code. ^The [sqlite3_str_errcode(X)] method returns
9045 ** [SQLITE_NOMEM] following any out-of-memory error, or
9052 ** zero-termination byte.
9074 ** highwater marks. ^The first argument is an integer code for
9087 ** SQLITE_OK on success and a non-zero [error code] on failure.
9090 ** be represented by a 32-bit integer, then the values returned by
9108 ** These integer constants designate various run-time status parameters
9116 ** and internal memory usage by the SQLite library. Auxiliary page-cache
9189 ** is an integer constant, taken from the set of
9201 ** non-zero [error code] on failure.
9217 ** The [sqlite3_db_status()] interface will return a non-zero error code
9227 ** satisfied using lookaside memory. Only the high-water value is meaningful;
9235 ** Only the high-water value is meaningful;
9243 ** Only the high-water value is meaningful;
9267 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
9299 ** If an IO or other error occurs while writing a page to disk, the effect
9308 ** to disk all at once. When pages spill mid-transaction, that introduces
9347 ** an index.
9352 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
9379 ** A non-zero value in this counter may indicate an opportunity to
9385 ** A non-zero value in this counter may indicate an opportunity to
9414 ** step was bypassed because a Bloom filter returned not-found. The
9471 ** register an alternative page cache implementation by passing in an
9476 ** custom page cache using this API, an application can better control
9482 ** The alternative page cache mechanism is an
9484 ** The built-in page cache is recommended for most uses.
9486 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
9499 ** built-in default page cache is used instead of the application defined
9514 ** ^SQLite will never invoke xInit() more than once without an intervening
9531 ** false if it is used for an in-memory database. The cache implementation
9542 ** suggested maximum cache-size (number of pages stored) for the cache
9554 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
9588 ** as its second argument. If the third parameter, discard, is non-zero,
9602 ** previously contains an entry associated with newKey, it must be
9622 ** is not obligated to free any memory, but well-behaved implementations should
9667 ** The sqlite3_backup object records state information about an ongoing
9681 ** for copying in-memory databases to or from persistent files.
9687 ** ^The source database is read-locked only while it is being read;
9712 ** an [ATTACH] statement for an attached database.
9718 ** an error.
9721 ** there is already a read or read-write transaction open on the
9724 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
9725 ** returned and an error code and error message are stored in the
9730 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
9745 ** ^If an error occurs while running sqlite3_backup_step(B,N),
9746 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
9748 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
9753 ** <li> the destination database was opened read-only, or
9754 ** <li> the destination database is using write-ahead-log journaling
9756 ** <li> the destination database is an in-memory database and the
9760 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
9761 ** the [sqlite3_busy_handler | busy-handler function]
9763 ** busy-handler returns non-zero before the lock is available, then
9777 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
9784 ** sqlite3_backup_step(), the source database may be modified mid-way
9785 ** through the backup process. ^If the source database is modified by an
9801 ** active write-transaction on the destination database is rolled back.
9808 ** ^If an out-of-memory condition or IO error occurred during any prior
9864 ** Other techniques for safely creating a consistent backup of an SQLite
9887 ** ^When running in shared-cache mode, a database operation may fail with
9888 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
9889 ** individual tables within the shared-cache cannot be obtained. See
9890 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
9894 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
9898 ** ^Shared-cache locks are released when a database connection concludes
9902 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
9904 ** has locked the required resource is stored internally. ^After an
9905 ** application receives an SQLITE_LOCKED error, it may call the
9912 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
9918 ** ^If the blocked connection is attempting to obtain a write-lock on a
9919 ** shared-cache table, and more than one other connection currently holds
9920 ** a read-lock on the same table, then SQLite arbitrarily selects one of
9923 ** ^(There may be at most one unlock-notify callback registered by a
9925 ** blocked connection already has a registered unlock-notify callback,
9928 ** unlock-notify callback is canceled. ^The blocked connection's
9929 ** unlock-notify callback may also be canceled by closing the blocked
9932 ** The unlock-notify callback is not reentrant. If an application invokes
9933 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
9941 ** When an unlock-notify callback is registered, the application provides a
9944 ** it an array of void* context pointers. The first argument passed to
9945 ** an unlock-notify callback is a pointer to an array of void* pointers,
9949 ** more than one blocked connection that has registered for an unlock-notify
9953 ** specified by the blocked connections bundled together into an array.
9954 ** This gives the application an opportunity to prioritize any actions
9959 ** Assuming that after registering for an unlock-notify callback a
9970 ** unlock-notify callback is registered. The system is said to be in
9971 ** a deadlocked state if connection A has registered for an unlock-notify
9973 ** B has itself registered for an unlock-notify callback when connection
9976 ** registered for an unlock-notify callback on the conclusion of connection
9988 ** sqlite3_unlock_notify() results in the unlock-notify callback being
9989 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
9990 ** or "DROP INDEX" query, an infinite loop might be the result.
9993 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
10009 ** and extensions to compare the contents of two buffers containing UTF-8
10010 ** strings in a case-independent fashion, using the same definition of "case
10026 ** Note that this routine returns zero on a match and non-zero if the strings
10043 ** insensitive - equivalent upper and lower case ASCII characters match
10049 ** Note that this routine returns zero on a match and non-zero if the strings
10066 ** nothing to prevent an application from calling sqlite3_log(), doing so
10073 ** a fixed-length buffer on the stack. If the log message is longer than
10080 ** CAPI3REF: Write-Ahead Log Commit Hook
10087 ** the associated write-lock on the database released)^, so the implementation
10093 ** ^The third parameter is the name of the database that was written to -
10094 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
10095 ** is the number of pages currently in the write-ahead log file,
10098 ** The callback function should normally return [SQLITE_OK]. ^If an error
10101 ** to report an error, though the commit will have still occurred. If the
10106 ** A single database handle may have at most a single write-ahead log callback
10108 ** previously registered write-ahead log callback. ^The return value is
10121 ** CAPI3REF: Configure an auto-checkpoint
10128 ** more frames in the [write-ahead log] file. ^Passing zero or
10143 ** ^Every new [database connection] defaults to having the auto-checkpoint
10159 ** [write-ahead log] for database X on [database connection] D to be
10160 ** transferred into the database file and for the write-ahead log to
10186 ** in the log were checkpointed. ^The [busy-handler callback]
10193 ** [sqlite3_busy_handler|busy-handler callback]) until there is no
10202 ** [busy-handler callback])
10215 ** the log file or to -1 if the checkpoint could not run because
10216 ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
10219 ** was called) or to -1 if the checkpoint could not run due to an error or
10221 ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
10224 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
10227 ** busy-handler configured, it will not be invoked in this case.
10231 ** obtained immediately, and a busy-handler is configured, it is invoked and
10232 ** the writer lock retried until either the busy-handler returns 0 or the lock
10233 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
10234 ** database readers as described above. ^If the busy-handler returns 0 before
10237 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
10244 ** an SQLITE_BUSY error is encountered when processing one or more of the
10247 ** error occurs while processing an attached database, processing is abandoned
10252 ** ^If database zDb is the name of an attached database that is not in WAL
10253 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
10294 ** If this interface is invoked outside the context of an xConnect or
10321 ** where X is an integer. If X is zero, then the [virtual table] whose
10329 ** If X is non-zero, then the virtual table implementation guarantees
10373 ** all schemas ("main", "temp", and any ATTACH-ed databases) whenever the
10387 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
10400 ** column is being fetched as part of an UPDATE operation during which the
10404 ** [xUpdate] method understands as a "no-change" value.
10413 ** The sqlite3_vtab_nochange() routine is an optimization. Virtual table
10432 ** must be an index into the aConstraint[] array belonging to the
10438 ** different [sqlite3_index_info] object, even an exact copy.
10447 ** of the constraint specifies an alternative collating sequence via
10460 ** This API may only be used from within an [xBestIndex|xBestIndex method]
10464 ** ^The sqlite3_vtab_distinct() interface returns an integer between 0 and
10534 ** [sqlite3_index_info] object or an incorrect answer may result.
10541 ** sqlite3_vtab_distinct() interface is merely an optimization. ^Careful
10553 ** This interface may only be used from within an
10566 ** on the right-hand side of the IN operator.)^ Thus the virtual table
10567 ** only sees a single value from the right-hand side of the IN operator
10571 ** table to see all values on the right-hand of the IN operator all at
10576 ** ^A call to sqlite3_vtab_in(P,N,-1) will return true (non-zero)
10577 ** if and only if the [sqlite3_index_info|P->aConstraint][N] constraint
10578 ** is an [IN operator] that can be processed all at once. ^In other words,
10579 ** sqlite3_vtab_in() with -1 in the third argument is a mechanism
10580 ** by which the virtual table can ask SQLite if all-at-once processing
10586 ** the IN operator all-at-once, respectively. ^Thus when the third
10587 ** parameter (F) is non-negative, this interface is the mechanism by
10596 ** (non-zero), that means that the constraint is an IN operator
10597 ** that can be processed all-at-once. ^If the constraint is not an IN
10598 ** operator or cannot be processed all-at-once, then the interface returns
10601 ** ^(All-at-once processing of the IN operator is selected if both of the
10605 ** <li><p> The P->aConstraintUsage[N].argvIndex value is set to a positive
10607 ** use the N-th constraint.
10610 ** non-negative had F>=1.
10614 ** the traditional one-at-a-time processing strategy for the IN constraint.
10615 ** ^If both conditions are true, then the argvIndex-th parameter to the
10616 ** xFilter method will be an [sqlite3_value] that appears to be NULL,
10618 ** [sqlite3_vtab_in_next()] to find all values on the right-hand side
10624 ** CAPI3REF: Find all elements on the right-hand side of an IN constraint.
10634 ** a parameter that was previously selected for all-at-once IN constraint
10637 ** an xFilter argument that was selected for all-at-once IN constraint
10640 ** ^(Use these routines to access all values on the right-hand side
10651 ** // an error has occurred
10677 ** from outside of an xBestIndex method are undefined and probably harmful.
10682 ** J being a 0-based index into P->aConstraint[], then this routine
10683 ** attempts to set *V to the value of the right-hand operand of
10684 ** that constraint if the right-hand operand is known. ^If the
10685 ** right-hand operand is not known, then *V is set to a NULL pointer.
10688 ** inteface returns SQLITE_NOTFOUND if the right-hand side of the J-th
10694 ** the right-hand operand of a constraint is a literal value in the original
10695 ** SQL statement. If the right-hand operand is an expression or a reference
10700 ** [SQLITE_INDEX_CONSTRAINT_ISNOTNULL], have no right-hand operand. For such
10708 ** The "_rhs_" in the name of this routine is an abbreviation for
10709 ** "Right-Hand Side".
10728 /* #define SQLITE_ABORT 4 // Also an error code */
10744 ** not available, the output variable is set to -1 if the value is numeric,
10750 ** set to the total number of times that the X-th loop has run.</dd>
10754 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
10759 ** iteration of the X-th loop. If the query planner's estimate was accurate,
10766 ** to a zero-terminated UTF-8 string containing the name of the index or table
10767 ** used for the X-th loop.</dd>
10771 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
10772 ** description for the X-th loop.</dd>
10776 ** id for the X-th query plan element. The id value is unique within the
10777 ** statement. The select-id is the same value as is output in the first
10778 ** column of an [EXPLAIN QUERY PLAN] query.</dd>
10784 ** returned in the second column of an [EXPLAIN QUERY PLAN] query.</dd>
10788 ** according to the processor time-stamp counter, that elapsed while the
10790 ** all query elements - if it is unavailable the output variable is
10791 ** set to -1.</dd>
10814 ** compile-time option.
10822 ** one flag is defined - SQLITE_SCANSTAT_COMPLEX. If SQLITE_SCANSTAT_COMPLEX
10832 ** for. Query elements are numbered starting from zero. A value of -1 may
10834 ** - less than -1 or greater than or equal to the total number of query
10835 ** elements used to implement the statement - a non-zero value is returned and
10861 ** CAPI3REF: Zero Scan-Status Counters
10866 ** This API is only available if the library is built with pre-processor
10872 ** CAPI3REF: Flush caches to disk mid-transaction
10875 ** ^If a write-transaction is open on [database connection] D when the
10877 ** pages in the pager-cache that are not currently in use are written out
10878 ** to disk. A dirty page may be in use if a database cursor created by an
10881 ** interface flushes caches for all schemas - "main", "temp", and
10886 ** immediately and there is a busy-handler callback configured, it is invoked
10888 ** the database is skipped and an attempt made to flush any dirty pages
10894 ** example an IO error or out-of-memory condition), then processing is
10895 ** abandoned and an SQLite [error code] is returned to the caller immediately.
10905 ** CAPI3REF: The pre-update hook.
10909 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
10939 ** For an UPDATE or DELETE operation on a [rowid table], the sixth
10941 ** row being modified or deleted. For an INSERT operation on a rowid table,
10943 ** parameter is undefined. For an INSERT or UPDATE on a rowid table the
10970 ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
10979 ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
10985 ** operation; or 1 for inserts, updates, or deletes invoked by top-level
10986 ** triggers; or 2 for changes resulting from triggers called by top-level
10990 ** the pre-update hook is invoked with SQLITE_DELETE, because
10995 ** pre-update hook is being invoked for some other reason, including a
10996 ** regular DELETE, sqlite3_preupdate_blobwrite() returns -1.
11022 ** CAPI3REF: Low-level system error code
11027 ** The return value is OS-dependent. For example, on unix systems, after
11038 ** An instance of the snapshot object records the state of a [WAL mode]
11044 ** transaction, that connection sees an unchanging copy of the database
11049 ** The sqlite3_snapshot object records state information about an historical
11067 ** If there is not already a read-transaction open on schema S when
11070 ** If a read-transaction is opened by this function, then it is guaranteed
11072 ** writer or checkpointer until after the read-transaction is closed. This
11073 ** is not guaranteed if a read-transaction is already open when this
11076 ** even while the read-transaction remains open.
11107 ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
11116 ** CAPI3REF: Start a read transaction on an historical snapshot
11120 ** transaction or upgrades an existing one for schema S of
11124 ** on success or an appropriate [error code] if it fails.
11141 ** is returned. If another error code - for example SQLITE_PROTOCOL or an
11142 ** SQLITE_IOERR error code - is returned, then the final state of the
11156 ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
11173 ** [SQLITE_ENABLE_SNAPSHOT] compile-time option is used.
11195 ** Otherwise, this API returns a negative value if P1 refers to an older
11221 ** sqlite3_snapshot_open(). It is an error if there is already a read
11225 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
11241 ** For an ordinary on-disk database file, the serialization is just a
11242 ** copy of the disk file. For an in-memory database or a "TEMP" database,
11286 ** Zero or more of the following constants can be OR-ed together for
11290 ** a pointer to contiguous in-memory database that it is currently using,
11292 ** a contiguous in-memory database, then this option causes
11294 ** using a contiguous in-memory database if it has been initialized by a
11304 ** reopen S as an in-memory database based on the serialization contained
11308 ** permitted to add content to the in-memory database as long as the total
11330 ** in an [SQLITE_CANTOPEN] error. The application can set the
11370 ** should be treated as read-only.
11374 #define SQLITE_DESERIALIZE_READONLY 4 /* Database is read-only */
11425 /* The double-precision datatype used by RTree depends on the
11426 ** SQLITE_RTREE_INT_ONLY compile-time option.
11435 ** Register a geometry callback named zGeom that can be used as part of an
11436 ** R-Tree geometry query as follows:
11461 ** Register a 2nd-generation geometry callback named zScore that can be
11462 ** used as part of an R-Tree geometry query as follows:
11535 ** An instance of this object is a [session] that can be used to
11543 ** An instance of this object acts as a cursor for iterating
11554 ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
11568 ** is not possible for an application to register a pre-update hook on a
11571 ** which a pre-update hook is already defined. The results of attempting
11575 ** database zDb, where zDb is either "main", or "temp", or the name of an
11576 ** attached database. It is not an error if database zDb is not attached
11628 ** It is an error (SQLITE_MISUSE) to attempt to modify this setting after
11640 ** It is an error (SQLITE_MISUSE) to attempt to modify this setting after
11652 ** disabled - it does not. A newly created session object is enabled.
11659 ** no-op, and may be used to query the current state of the session.
11676 ** <li> The change is made by an SQL trigger or foreign key action
11682 ** for an indirect change above, or direct otherwise.
11712 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
11715 ** It is not an error if the named table does not exist in the database. Nor
11716 ** is it an error if the named table does not have a PRIMARY KEY. However,
11722 ** SQLITE_OK is returned if the call completes without error. Or, if an error
11723 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
11727 ** As of SQLite version 3.22.0, the "sqlite_stat1" table is an exception to
11736 ** rows a zero-length blob (SQL value X'') is stored in the changeset or
11742 ** zero-length blob back to a NULL value when updating the sqlite_stat1
11746 ** conflict-handler callback) then the X'' value is returned. The application
11786 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
11787 ** zero and return an SQLite error code.
11790 ** each representing a change to a single row of an attached table. An INSERT
11792 ** contains the original values of each field of a deleted database row. An
11793 ** UPDATE change contains the original values of each field of an updated
11794 ** database row along with the updated values for each updated non-primary-key
11795 ** column. It is not possible for an UPDATE change to represent a change that
11797 ** is represented in a changeset as a DELETE followed by an INSERT.
11802 ** function. If an existing row with one or more NULL values stored in
11803 ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
11804 ** only an INSERT is appears in the changeset. Similarly, if an existing row
11805 ** with non-NULL PRIMARY KEY values is updated so that one or more of its
11809 ** The contents of a changeset may be traversed using an iterator created
11818 ** are sorted in the same order in which they were attached (or auto-attached)
11832 ** recorded once - the first time a row with said primary key is inserted,
11839 ** The session object therefore accumulates two types of records - those
11850 ** <li> For each record generated by an insert, the database is queried
11851 ** for a row with a matching primary key. If one is found, an INSERT
11855 ** <li> For each record generated by an update or delete, the database is
11857 ** found and one or more of the non-primary key fields have been
11858 ** modified from their original values, an UPDATE change is added to
11869 ** active, the resulting changeset will contain an UPDATE change instead of
11870 ** a DELETE and an INSERT.
11874 ** This may appear to have some counter-intuitive effects if a single row
11881 ** the resulting changeset will contain an UPDATE change that updates both
11891 ** CAPI3REF: Return An Upper-limit For The Size Of The Changeset
11899 ** When enabled, this function returns an upper limit, in bytes, for the size
11913 ** does not have a primary key, this function is a no-op (but does not return
11914 ** an error).
11928 ** are compatible but do not have any PRIMARY KEY columns, it is not an error
11933 ** used to update the table in database zFrom (call this the "from-table")
11935 ** object (call this the "to-table"). Specifically:
11938 ** <li> For each row (primary key) that exists in the to-table but not in
11939 ** the from-table, an INSERT record is added to the session object.
11941 ** <li> For each row (primary key) that exists in the to-table but not in
11942 ** the from-table, a DELETE record is added to the session object.
11945 ** different non-PK values in each, an UPDATE record is added to the
11954 ** Unless the call to this function is a no-op as described above, it is an
11958 ** If the operation is successful, SQLITE_OK is returned. Otherwise, an SQLite
11960 ** may be set to point to a buffer containing an English language error
11989 ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
11991 ** Because the non-primary key "old.*" fields are omitted, no
12010 ** Return non-zero if no changes to attached tables have been recorded by
12017 ** an attached table is modified and then later on the original values
12018 ** are restored. However, if this function returns non-zero, then it is
12033 ** CAPI3REF: Create An Iterator To Traverse A Changeset
12036 ** Create an iterator used to iterate through the contents of a changeset.
12038 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
12060 ** an application iterates through a changeset using an iterator created by
12094 ** It is an error to specify this flag with a patchset.
12104 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
12105 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
12108 ** Immediately after an iterator is created by sqlite3changeset_start(), it
12118 ** If an error occurs, an SQLite error code is returned. Possible error
12128 ** The pIter argument passed to this function may either be an iterator
12129 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
12142 ** *pzTab is set to point to a nul-terminated utf-8 encoded string containing
12145 ** or until the conflict-handler function returns.
12148 ** is an indirect change, or false (0) otherwise. See the documentation for
12152 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
12161 int *pbIndirect /* OUT: True for an 'indirect' change */
12177 ** If successful, *pabPK is set to point to an array of nCol entries, where
12192 unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
12200 ** The pIter argument passed to this function may either be an iterator
12201 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
12218 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
12231 ** The pIter argument passed to this function may either be an iterator
12232 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
12246 ** returns SQLITE_OK. If the change is an UPDATE and does not include
12252 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
12266 ** conflict-handler callback by [sqlite3changeset_apply()] with either
12277 ** "conflicting row" associated with the current conflict-handler callback
12280 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
12293 ** This function may only be called with an iterator passed to an
12310 ** This function is used to finalize an iterator allocated with
12314 ** [sqlite3changeset_start()] function. If an application calls this
12315 ** function with an iterator passed to a conflict-handler by
12319 ** If an error was encountered within a call to an sqlite3changeset_xxx()
12320 ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
12321 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
12323 ** returned. This is to allow the following pattern (pseudo-code):
12332 ** // An error has occurred
12341 ** This function is used to "invert" a changeset object. Applying an inverted
12346 ** <li> Each DELETE change is changed to an INSERT, and
12356 ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
12357 ** zeroed and an SQLite error code returned.
12378 ** This function combines the two input changesets using an
12409 ** A changegroup is an object used to combine two or more
12418 ** An sqlite3_changegroup object is used to combine two or more changesets
12426 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
12429 ** The usual usage pattern for an sqlite3_changegroup object is as follows:
12458 ** ("main", "temp", or the name of an attached database). If
12461 ** object is left in an undefined state.
12507 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
12508 ** <tr><th style="white-space:pre">Existing Change </th>
12509 ** <th style="white-space:pre">New Change </th>
12536 ** change, the existing DELETE is replaced by an UPDATE within the
12559 ** detected, SQLITE_CORRUPT is returned. Or, if an out-of-memory condition
12562 ** In all cases, if an error occurs the state of the final contents of the
12576 ** returned. Otherwise, an SQLite error code is returned.
12609 ** If an error occurs, an SQLite error code is returned and the output
12641 ** Otherwise, if the return value is non-zero or the xFilter argument to
12657 ** If there is no compatible table, it is not an error, but none of the
12662 ** For each change for which there is a compatible table, an attempt is made
12677 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
12678 ** returns an illegal value, any changes already made are rolled back and
12681 ** returned by each invocation of the conflict-handler function. Refer to
12690 ** stored in all non-primary key columns also match the values stored in
12694 ** the non-primary key fields contains a value different from the original
12695 ** row value stored in the changeset, the conflict-handler function is
12698 ** only the values of those non-primary key fields are compared against
12699 ** the current database contents - any trailing database table columns
12703 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
12708 ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
12710 ** operation is attempted because an earlier call to the conflict handler
12714 ** For each INSERT change, an attempt is made to insert the new row into
12727 ** This includes the case where the INSERT operation is re-attempted because
12728 ** an earlier call to the conflict handler function returned
12735 ** stored in all modified non-primary key columns also match the values
12739 ** the modified non-primary key fields contains a value different from an
12740 ** original row value stored in the changeset, the conflict-handler function
12742 ** UPDATE changes only contain values for non-primary key fields that are
12744 ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
12747 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
12751 ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
12754 ** an earlier call to the conflict handler function returned
12766 ** rolled back, restoring the target database to its original state, and an
12769 ** If the output parameters (ppRebase) and (pnRebase) are non-NULL and
12830 ** applied, or rolled back if an error occurs. Specifying this flag
12832 ** caller has an open transaction or savepoint when apply_v2() is called,
12838 ** an error to specify this flag with a patchset.
12847 ** <li>an update change if the modified fields are already set to
12849 ** <li>an insert change if all fields of the conflicting row match
12867 ** Values that may be passed as the second argument to a conflict-handler.
12874 ** (non primary-key) fields modified by the update do not contain the
12890 ** handler while processing an INSERT change if the operation would result
12942 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
12946 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
12975 ** For example, if both the local and remote changesets contain an
12993 ** resolution was OMIT, then add an UPDATE change to the rebased
13001 ** operation was an UPDATE, then the old.* fields of change are updated
13007 ** is changed into an INSERT. Any undefined values in the new.* record
13035 ** combined on a per-field basis, not per-row. This means that in the
13045 ** <li> An sqlite3_rebaser object is created by calling
13065 ** point to the new object and return SQLITE_OK. Otherwise, if an error
13066 ** occurs, return an SQLite error code (e.g. SQLITE_NOMEM) and set (*ppNew)
13096 ** sqlite3_free(). Otherwise, if an error occurs, (*ppOut) and (*pnOut)
13097 ** are set to zero and an SQLite error code returned.
13119 ** corresponding non-streaming API functions:
13121 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
13122 ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
13132 ** Non-streaming functions that accept changesets (or patchsets) as input
13136 ** Normally this is convenient. However, if an application running in a
13137 ** low-memory environment is required to handle very large changesets, the
13163 ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
13164 ** error code should be returned. In all cases, if an xInput callback returns
13165 ** an error, all processing is abandoned and the streaming API function
13170 ** iterator. If such an xInput callback returns an error, the iterator enters
13171 ** an error state, whereby all subsequent calls to iterator functions
13201 ** The sessions module never invokes an xOutput callback with the third
13318 ** This function returns SQLITE_OK if successful, or an SQLite error code
13401 ** non-negative but less than the number of columns in the table, return
13406 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
13407 ** an OOM condition or IO error), an appropriate SQLite error code is
13416 ** non-negative but less than the number of columns in the table, set
13420 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
13421 ** an OOM condition or IO error), an appropriate SQLite error code is
13424 ** This function may be quite inefficient if used with an FTS5 table
13433 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
13435 ** if an error occurs, an SQLite error code is returned and the final values
13450 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
13452 ** This API can be quite slow if used with an FTS5 table created with the
13466 ** first token of the phrase. SQLITE_OK is returned if successful, or an
13467 ** error code (i.e. SQLITE_NOMEM) if an error occurs.
13469 ** This API can be quite slow if used with an FTS5 table created with the
13504 ** the callback, an SQLite error code is returned.
13519 ** If there is already an auxiliary data pointer when this function is
13520 ** invoked, then it is replaced by the new pointer. If an xDelete callback
13527 ** If an error (e.g. an OOM condition) occurs within this function,
13528 ** the auxiliary data is set to NULL and an error code returned. If the
13538 ** If the bClear argument is non-zero, then the auxiliary data is cleared
13560 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
13562 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
13564 ** // An instance of phrase iPhrase at offset iOff of column iCol
13568 ** modify this structure directly - it should only be used as shown above
13572 ** This API can be quite slow if used with an FTS5 table created with the
13576 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
13594 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
13596 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
13601 ** This API can be quite slow if used with an FTS5 table created with the
13604 ** then this API always iterates through an empty set (all calls to
13605 ** xPhraseFirstColumn() set iCol to -1).
13647 ** to scan the portion of the full-text index that matches the prefix
13654 ** of the initial querying of the full-text index, avoiding the second scan
13657 ** either on a per-table basis using the [FTS5 insttoken | 'insttoken']
13658 ** option, or on a per-query basis using the
13661 ** This API can be quite slow if used with an FTS5 table created with the
13673 ** into the fts5 table, then (*pzLocale) is set to point to a nul-terminated
13674 ** buffer containing the name of the locale in utf-8 encoding. (*pnLocale)
13676 ** nul-terminator.
13678 ** If successful, SQLITE_OK is returned. Or, if an error occurs, an
13761 ** The second and third arguments are an array of nul-terminated strings
13766 ** The final argument is an output variable. If successful, (*ppOut)
13768 ** returned. If an error occurs, some value other than SQLITE_OK should
13779 ** by argument pText. pText may or may not be nul-terminated. The first
13780 ** argument passed to this function is a pointer to an Fts5Tokenizer object
13781 ** returned by an earlier call to xCreate().
13787 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
13792 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
13796 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
13801 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
13802 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
13803 ** function. Or an fts5_api.xColumnSize() request made by the same
13807 ** The sixth and seventh arguments passed to xTokenize() - pLocale and
13808 ** nLocale - are a pointer to a buffer containing the locale to use for
13810 ** pLocale buffer is not nul-terminated. pLocale may be passed NULL (in
13829 ** If an xToken() callback returns any value other than SQLITE_OK, then
13833 ** if an error occurs with the xTokenize() implementation itself, it
13837 ** If the tokenizer is registered using an fts5_tokenizer_v2 object,
13838 ** then the xTokenize() method has two additional arguments - pLocale
13842 ** an nLocale byte buffer containing the name of the locale to use as utf-8
13843 ** text. pLocale is not nul-terminated.
13847 ** There is also an fts5_tokenizer object. This is an older, deprecated,
13865 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
13899 ** still appears to contain just two phrases - "(first OR 1st)"
13910 ** when tokenizing query text (it should not - to do so would be
13930 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
13957 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
14046 /* Find an existing tokenizer */
14074 /* Find an existing tokenizer */
14106 ** autoconf-based build
14134 ** The hard limit is the ability of a 32-bit signed integer
14135 ** to count the size: 2^31-1 or 2147483647.
14146 ** * Columns in an index
14148 ** * Terms in the SET clause of an UPDATE statement
14151 ** * Terms in the VALUES clause of an INSERT statement
14154 ** tell you that in a well-normalized database, you usually should
14159 ** An index can only have SQLITE_MAX_COLUMN columns from the user
14160 ** point of view, but the underlying b-tree that implements the index
14183 ** The maximum depth of an expression tree. This is limited to
14185 ** want to place more severe limits on the complexity of an
14213 ** The maximum number of arguments to an SQL function.
14224 ** The suggested maximum number of in-memory pages to use for
14227 ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
14229 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
14230 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
14233 # define SQLITE_DEFAULT_CACHE_SIZE -2000
14247 ** counted using a signed 8-bit integer which has a maximum value of 127
14259 ** as a signed 32-bit integer can hold.
14266 ** imposed by the use of 16-bit offsets within each page.
14270 ** a library that is technically incompatible with an SQLite library
14272 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
14273 ** compiled with the default page-size limit will not be able to rollback
14296 ** device characteristics (sector-size and atomic write() support),
14313 ** This value can be lowered (or raised) at run-time using that the
14344 #pragma warn -rch /* unreachable code */
14345 #pragma warn -ccc /* Condition is always true or false */
14346 #pragma warn -aus /* Assigned value is never used */
14347 #pragma warn -csu /* Comparing signed and unsigned */
14348 #pragma warn -spa /* Suspicious pointer arithmetic */
14356 # define __has_extension(x) 0 /* compatibility with non-clang compilers */
14386 ** if it is available, it requires an #include of specific headers
14389 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
14402 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
14403 #else /* Generates a warning - but it always works */
14429 ** compiling with an appropriate version of MSVC unless prevented by
14448 ** SEH support if the -DSQLITE_OMIT_SEH option is given.
14458 ** disables it using -DSQLITE_DIRECT_OVERFLOW_READ=0
14461 /* Disable if -DSQLITE_DIRECT_OVERFLOW_READ=0 */
14473 ** level of threadsafety. 2 means the library is multithreaded - multiple
14477 ** Older versions of SQLite used an optional THREADSAFE macro.
14481 ** for compile-time options at runtime (e.g. "PRAGMA compile_options"), this
14489 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
14495 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
14502 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
14521 ** will cause HeapValidate to be called. If heap validation should fail, an
14531 # error "Two or more of the following compile-time configuration options\
14569 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
14634 ** Disable ALWAYS() and NEVER() (make them pass-throughs) for coverage
14646 ** of SQLite to unexpected behavior - to make the code "self-healing"
14652 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
14740 ** Return true (non-zero) if the input is an integer that is too large
14741 ** to fit in 32-bits. This macro is used inside of various testcase()
14742 ** macros to verify that we have tested SQLite for large-file support.
14769 ** This is the header file for the generic hash-table implementation
14779 /* A complete hash table is an instance of the following structure.
14780 ** The internals of this structure are intended to be opaque -- client
14787 ** All elements of the hash table are on a single doubly-linked list.
14791 ** the global doubly-linked list. The contents of the bucket are the
14792 ** element pointed to plus the next _ht.count-1 elements in the list.
14810 /* Each element in the hash table is an instance of the following
14811 ** structure. All elements are stored on a single doubly-linked list.
14843 #define sqliteHashFirst(H) ((H)->first)
14844 #define sqliteHashNext(E) ((E)->next)
14845 #define sqliteHashData(E) ((E)->data)
14846 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
14847 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
14852 #define sqliteHashCount(H) ((H)->count)
15065 int xxn=(N);while(xxn-->0)*(xxd++)=*(xxs++);}
15070 ** substitute integer for floating-point
15075 # define fabs(X) ((X)<0?-(X):(X))
15101 ** The "file format" number is an integer that is incremented whenever
15102 ** the VDBE-level file format changes. The following macros define the
15113 ** changed at run-time using a pragma.
15121 ** on the command-line
15151 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
15153 ** The default value of "20" was chosen to minimize the run-time of the
15154 ** speedtest1 test program with options: --shrink-memory --reprepare
15168 ** The compile-time options SQLITE_MMAP_READWRITE and
15181 #define offsetof(STRUCTURE,FIELD) ((size_t)((char*)&((STRUCTURE*)0)->FIELD))
15185 ** Work around C99 "flex-array" syntax for pre-C99 compilers, so as
15186 ** to avoid complaints from -fsanitize=strict-bounds.
15222 ** types can be conveniently redefined at compile-type. Like this:
15224 ** cc '-DUINTPTR_TYPE=long long int' ...
15261 typedef sqlite_int64 i64; /* 8-byte signed integer */
15262 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
15263 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
15264 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
15265 typedef INT16_TYPE i16; /* 2-byte signed integer */
15266 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
15267 typedef INT8_TYPE i8; /* 1-byte signed integer */
15280 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
15289 ** Estimated quantities used for query planning are stored as 16-bit
15291 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
15300 ** 1 -> 0 20 -> 43 10000 -> 132
15301 ** 2 -> 10 25 -> 46 25000 -> 146
15302 ** 3 -> 16 100 -> 66 1000000 -> 199
15303 ** 4 -> 20 1000 -> 99 1048576 -> 200
15304 ** 10 -> 33 1024 -> 100 4294967296 -> 320
15309 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
15312 #define LOGEST_MIN (-32768)
15331 /* The uptr type is an unsigned integer large enough to hold a pointer
15354 ** if the sub-buffer S..E-1 overflows the buffer whose last byte is P-1.
15359 ** |-----------------| FALSE
15360 ** |-------|
15364 ** |-----------------|
15365 ** |-------| TRUE
15369 ** |-----------------|
15370 ** |-------| FALSE
15377 ** and whether or not that determination is run-time or compile-time.
15379 ** For best performance, an attempt is made to guess at the byte-order
15380 ** using C-preprocessor macros. If that is unsuccessful, or if
15381 ** -DSQLITE_BYTEORDER=0 is set, then byte-order is determined
15382 ** at run-time.
15387 ** -DSQLITE_BYTEORDER=1234
15391 ** -DSQLITE_BYTEORDER=4321
15393 ** to cause the build to work for little-endian or big-endian processors,
15396 #ifndef SQLITE_BYTEORDER /* Replicate changes at tag-20230904a */
15434 ** Constants for the largest and smallest possible 64-bit signed integers.
15435 ** These macros are designed to work correctly on both 32-bit and 64-bit
15440 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
15447 #define SMXV(n) ((((i64)1)<<(sizeof(n)*8-1))-1)
15448 #define UMXV(n) ((((i64)1)<<(sizeof(n)*8))-1)
15452 ** to force 8-byte alignment on 64-bit architectures.
15456 ** ROUND8P() assumes that the argument is already an integer number of
15457 ** pointers in size, and so it is a no-op on systems where the pointer
15473 ** Assert that the pointer X is aligned to an 8-byte boundary. This
15478 ** underlying malloc() implementation might return us 4-byte aligned
15479 ** pointers. In that case, only verify 4-byte alignment.
15482 # define EIGHT_BYTE_ALIGNMENT(X) ((((uptr)(X) - (uptr)0)&3)==0)
15484 # define EIGHT_BYTE_ALIGNMENT(X) ((((uptr)(X) - (uptr)0)&7)==0)
15496 ** Default maximum size of memory used by memory-mapped I/O in the VFS
15516 ** default MMAP_SIZE is specified at compile-time, make sure that it does
15540 sqlite3DebugPrintf("%u/%d/%p: ",(S)->selId,(P)->addrExplain,(S)),\
15552 ** 0x00000008 Result-set wildcard expansion
15558 ** 0x00000200 Count-of-view optimization
15563 ** 0x00004000 Push-down optimization
15564 ** 0x00008000 After all FROM-clause analysis
15586 ** (---any--) Top-level block structure
15587 ** 0x-------F High-level debug messages
15588 ** 0x----FFF- More detail
15589 ** 0xFFFF---- Low-level debug messages
15597 ** 0x00000020 Range an equality scan metrics
15612 ** 0x00080000 Star-query heuristic
15617 ** An instance of the following structure is used to store the busy-handler
15622 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
15656 ** The root-page of the schema table.
15668 ** an array.
15675 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
15694 ** directly, we use its constant as a key to lookup the run-time allocated
15696 ** for the run-time allocated buffer.
15699 ** macros become no-ops and have zero performance impact.
15718 ** implementation of an SQL aggregate step callback may not use the
15801 ** Changing this from a 64-bit to a 32-bit type limits the number of
15823 #define ALLBITS ((Bitmask)-1)
15824 #define TOPBIT (((Bitmask)1)<<(BMS-1))
15830 ** just an array of integers.
15853 ** This header file (together with is companion C source-code file
15857 ** This header file is #include-ed by sqliteInt.h and thus ends up
15865 ** necessary pre-processor macros for it.
15881 ** This file contains pre-processor directives related to operating system
15902 ** If SQLITE_OS_OTHER=1 is specified at compile-time, then the application
15965 ** a no-op
15998 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
16000 ** 2006-10-31: The default prefix used to be "sqlite_". But then
16001 ** Mcafee started using SQLite in their anti-virus product and it
16026 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
16029 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
16030 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
16047 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
16051 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
16083 ** is set high so that we don't have to allocate an unused page except
16155 ** sqlite3_malloc() to obtain space for the file-handle structure.
16191 #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
16211 ** Page number PAGER_SJ_PGNO is never used in an SQLite database (it is
16214 ** is devoted to storing a super-journal name - there are no more pages to
16218 #define PAGER_SJ_PGNO_COMPUTED(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
16219 #define PAGER_SJ_PGNO(x) ((x)->lckPgno)
16227 #define PAGER_MEMORY 0x0002 /* In-memory database */
16232 #define PAGER_LOCKINGMODE_QUERY -1
16243 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
16248 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
16249 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
16255 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
16259 ** if( isOpen(pPager->jfd) ){ ...
16263 ** if( pPager->jfd->pMethods ){ ...
16265 #define isOpen(pFd) ((pFd)->pMethods!=0)
16271 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
16293 ** that make up the Pager sub-system API. See source code comments for
16445 ** This header file defines the interface that the sqlite B-Tree file
16458 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
16465 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
16466 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
16479 sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
16494 #define BTREE_MEMORY 2 /* This is an in-memory DB */
16495 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
16549 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
16551 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
16552 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
16555 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
16556 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
16571 ** to constants so that the offset of the corresponding field in an
16576 ** For example, the free-page-count field is located at byte offset 36 of
16577 ** the database file header. The incr-vacuum-flag field is located at
16581 ** It is a read-only number computed by the pager. But we merge it with
16594 #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
16602 ** The first argument is an Expr* (which is guaranteed to be constant for
16608 ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
16609 ** column of the b-tree of the cursor. The Expr tree will not contain
16610 ** any function calls nor subqueries nor references to b-trees other than
16613 ** The design of the _RANGE hint is aid b-tree implementations that try
16614 ** to prefetch content from remote machines - to provide those
16639 #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
16644 ** For read-only cursors the wrFlag argument is always zero. For read-write
16654 ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
16655 ** by this, the native b-tree engine of SQLite, but it is available to
16657 ** b-tree system. For alternative storage engines in which a delete of
16661 ** and DELETE operations as no-ops, and any READ operation against a
16664 #define BTREE_WRCSR 0x00000004 /* read-write cursor */
16670 int wrFlag, /* 1 for writing. 0 for read-only */
16704 #define BTREE_APPEND 0x08 /* Insert is likely an append */
16707 /* An instance of the BtreePayload object describes the content of a single
16708 ** entry in either an index or table btree.
16711 ** an arbitrary key and no data. These btrees have pKey,nKey set to the
16713 ** fields give an array of Mem objects that are a decomposition of the key.
16716 ** Table btrees (used for rowid tables) contain an integer rowid used as
16769 Pgno *aRoot, /* An array of root pages numbers for individual trees */
16819 ** Enter and Leave procedures no-ops.
16877 ** or VDBE. The VDBE implements an abstract machine that runs a
16885 ** A single VDBE is an opaque structure named "Vdbe". Only routines
16901 ** an IN operator.
16904 int selId; /* SELECT-id for the SELECT statement on the RHS */
16913 ** A single instruction of the virtual machine has an opcode
16915 ** as an instance of the following structure:
16920 u16 p5; /* Fifth parameter is an unsigned 16-bit integer */
16948 u32 iSrcLine; /* Source-code line that generated this opcode
16960 ** A sub-routine used to implement a trigger program.
16963 VdbeOp *aOp; /* Array of opcodes for sub-program */
16969 SubProgram *pNext; /* Next sub-program already visited */
16989 #define P4_STATIC (-1) /* Pointer to a static string */
16990 #define P4_COLLSEQ (-2) /* P4 is a pointer to a CollSeq structure */
16991 #define P4_INT32 (-3) /* P4 is a 32-bit signed integer */
16992 #define P4_SUBPROGRAM (-4) /* P4 is a pointer to a SubProgram structure */
16993 #define P4_TABLE (-5) /* P4 is a pointer to a Table structure */
16995 #define P4_FREE_IF_LE (-6)
16996 #define P4_DYNAMIC (-6) /* Pointer to memory from sqliteMalloc() */
16997 #define P4_FUNCDEF (-7) /* P4 is a pointer to a FuncDef structure */
16998 #define P4_KEYINFO (-8) /* P4 is a pointer to a KeyInfo structure */
16999 #define P4_EXPR (-9) /* P4 is a pointer to an Expr tree */
17000 #define P4_MEM (-10) /* P4 is a pointer to a Mem* structure */
17001 #define P4_VTAB (-11) /* P4 is a pointer to an sqlite3_vtab structure */
17002 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
17003 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
17004 #define P4_INTARRAY (-14) /* P4 is a vector of 32-bit integers */
17005 #define P4_FUNCCTX (-15) /* P4 is a pointer to an sqlite3_context object */
17006 #define P4_TABLEREF (-16) /* Like P4_TABLE, but reference counted */
17007 #define P4_SUBRTNSIG (-17) /* P4 is a SubrtnSig pointer */
17036 ** into an index into the Parse.aLabel[] array that contains the resolved
17099 #define OP_IfPos 50 /* jump, synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
17109 #define OP_IfNotZero 60 /* jump, synopsis: if r[P1]!=0 then r[P1]--, goto P2 */
17110 #define OP_DecrJumpZero 61 /* jump, synopsis: if (--r[P1])==0 goto P2 */
17139 #define OP_Compare 90 /* synopsis: r[P1@P3] <-> r[P2@P3] */
17157 #define OP_Subtract 108 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
17173 #define OP_SeekScan 124 /* synopsis: Scan-ahead up to P1 rows */
17209 #define OP_OffsetLimit 160 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) …
17245 #define OPFLG_IN1 0x02 /* in1: P1 is an input */
17246 #define OPFLG_IN2 0x04 /* in2: P2 is an input */
17247 #define OPFLG_IN3 0x08 /* in3: P3 is an input */
17248 #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
17249 #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
17290 ** Additional non-public SQLITE_PREPARE_* flags
17345 # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
17350 # define sqlite3ExplainBreakpoint(A,B) /*no-op*/
17429 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
17453 ** only works with an amalgamation build. That's ok since a VDBE branch
17466 ** VdbeCoverageNeverNull(v) // Previous three-way branch is only
17471 ** // in distinguishing equal and not-equal.
17474 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
17475 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
17483 ** is responsible for keeping track of this and reporting byte-code branches
17560 ** Every page in the cache is controlled by an instance of the following
17595 #define PGHDR_MMAP 0x020 /* This is an mmap page object */
17621 /* Modify the page-size after the cache has been created. */
17643 /* Change a page number. Used by incr-vacuum. */
17664 /* Increment the reference count of an existing page */
17685 /* Set and get the suggested cache-size for the specified pager-cache.
17688 ** the total number of pages cached by purgeable pager-caches to the sum
17689 ** of the suggested cache-sizes.
17696 /* Set or get the suggested spill-size for the specified pager-cache.
17698 ** The spill-size is the minimum number of pages in cache before the cache
17748 ** to all source files. We break it out in an effort to keep the code
17762 ** at start-time.
17764 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
17767 ** start-time.
17769 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
17771 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
17788 ** If this is a no-op implementation, implement everything as macros.
17809 /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
17829 ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
17830 ** In other words, the zero-based numbers are used for all external interfaces
17831 ** and the one-based values are used internally.
17841 ** Each database file to be accessed by the system is an instance
17856 ** An instance of the following structure stores a database schema.
17859 ** the Schema for the TEMP database (sqlite3.aDb[1]) which is free-standing.
17888 ** Db.pSchema->flags field.
17890 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
17891 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
17892 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
17893 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
17896 ** Allowed values for the DB.pSchema->flags field.
17916 ** Lookaside malloc is a set of fixed-size buffers that can be used
17938 ** in a performance-critical path. sz should be set by to szTrue whenever
17943 ** come off of pFree first, then pInit as a fallback. This dual-list
17944 ** allows use to compute a high-water mark - the maximum number of allocations
17945 ** outstanding at any point in the past - by subtracting the number of
17948 ** Enhancement on 2019-12-12: Two-size-lookaside
17952 ** The two-size-lookaside enhancement breaks up the lookaside allocation
17953 ** into two pools: One of 128-byte slots and the other of the default size
17954 ** (1200-byte) slots. Allocations are filled from the small-pool first,
17955 ** failing over to the full-size pool if that does not work. Thus more
17972 void *pMiddle; /* First byte past end of full-size buffers and
17977 void *pTrueEnd; /* True value of pEnd, when db->pnBytesFreed!=0 */
17983 #define DisableLookaside db->lookaside.bDisable++;db->lookaside.sz=0
17984 #define EnableLookaside db->lookaside.bDisable--;\
17985 db->lookaside.sz=db->lookaside.bDisable?0:db->lookaside.szTrue
17987 /* Size of the smaller allocations in two-size lookaside */
17995 ** A hash table for built-in function definitions. (Application-defined
18015 /* This is an extra SQLITE_TRACE macro that indicates "legacy" tracing
18033 ** Each database connection is an instance of the following structure.
18046 u32 nSchemaLock; /* Do not reset the schema when non-zero */
18054 u8 autoCommit; /* The auto-commit flag. */
18058 u8 dfltLockMode; /* Default locking-mode for attached dbs */
18064 u8 noSharedCache; /* True if no shared-cache backends */
18077 unsigned imposterTable : 1; /* Building an imposter table */
18112 PreUpdate *pPreUpdate; /* Context for active pre-update callback */
18151 int setlkTimeout; /* Blocking lock timeout, in msec. -1 -> inf. */
18154 int nSavepoint; /* Number of non-transaction savepoints */
18155 int nStatement; /* Number of nested statement-transactions */
18168 ** tried to do recently failed with an SQLITE_LOCKED error due to locks
18182 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
18183 #define ENC(db) ((db)->enc)
18188 ** C-compilers still do not accept LL integer literals.
18231 #define SQLITE_DqsDDL 0x20000000 /* dbl-quoted strings allowed in DDL*/
18232 #define SQLITE_DqsDML 0x40000000 /* dbl-quoted strings allowed in DML*/
18238 #define SQLITE_ReadUncommit HI(0x00004) /* READ UNCOMMITTED in shared-cache */
18258 #define DBFLAG_PreferBuiltin 0x0002 /* Preference to built-in funcs */
18279 #define SQLITE_CountOfView 0x00000200 /* The count-of-view optimization */
18283 #define SQLITE_PushDown 0x00001000 /* WHERE-clause push-down opt */
18285 #define SQLITE_SkipScan 0x00004000 /* Skip-scans */
18293 #define SQLITE_BalancedMerge 0x00200000 /* Balance multi-way merges */
18298 #define SQLITE_Coroutines 0x02000000 /* Co-routines for subqueries */
18300 #define SQLITE_OnePass 0x08000000 /* Single-pass DELETE and UPDATE */
18308 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
18309 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
18315 #define ConstFactorOk(P) ((P)->okConstFactor)
18325 #define SQLITE_STATE_ERROR 0xd5 /* An SQLITE_MISUSE error occurred */
18329 ** Each SQL function is defined by an instance of the following
18330 ** structure. For global built-in functions (ex: substr(), max(), count())
18332 ** For per-connection application-defined functions, a pointer to this
18333 ** structure is held in the db->aHash hash table.
18335 ** The u.pHash field is used by the global built-ins. The u.pDestructor
18336 ** field is used by per-connection app-def functions.
18339 i16 nArg; /* Number of arguments. -1 means unlimited */
18343 void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
18346 void (*xInverse)(sqlite3_context*,int,sqlite3_value**); /* inverse agg-step */
18355 ** This structure encapsulates a user-function destructor callback (as
18388 ** SQLITE_FUNC_UNSAFE == SQLITE_INNOCUOUS -- opposite meanings!!!
18395 ** See multiple instances of tag-20230109-1.
18399 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
18402 #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
18403 #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
18404 #define SQLITE_FUNC_BYTELEN 0x00c0 /* Built-in octet_length() function */
18405 #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
18406 /* 0x0200 -- available for reuse */
18407 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
18411 ** single query - might change over time */
18412 #define SQLITE_FUNC_TEST 0x4000 /* Built-in testing functions */
18414 #define SQLITE_FUNC_WINDOW 0x00010000 /* Built-in window-only function */
18419 #define SQLITE_FUNC_INLINE 0x00400000 /* Functions implemented in-line */
18420 #define SQLITE_FUNC_BUILTIN 0x00800000 /* This is a built-in function */
18424 /* Identifier numbers for each in-line function */
18442 ** as the user-data (sqlite3_user_data()) for the function. If
18453 ** zName is the name of a function that is implemented by in-line
18459 ** zName is the name of a test-only function implemented by in-line
18468 ** a single query. The iArg is ignored. The user-data is always set
18472 ** For math-library functions. xPtr is an arbitrary pointer.
18477 ** ignored and the user-data for these functions is set to an
18478 ** arbitrary non-NULL pointer. The bNC parameter is not used.
18481 ** Used to create an aggregate function definition implemented by
18487 ** Used to create an aggregate function definition implemented by
18496 ** available as the function user-data (sqlite3_user_data()). The
18561 char *zName; /* Savepoint name (nul-terminated) */
18577 ** Each SQLite module (virtual table definition) is defined by an
18591 ** Information about each column of an SQL table is held in an instance
18617 unsigned notNull :4; /* An OE_ code for handling a NOT NULL constraint */
18622 u16 iDflt; /* 1-based index of DEFAULT. 0 means "none" */
18653 #define COLFLAG_SORTERREF 0x0010 /* Use sorter-refs with this column */
18664 ** A "Collating Sequence" is defined by an instance of the following
18669 ** collating sequence is undefined. Indices built on an undefined
18673 char *zName; /* Name of the collating sequence, UTF-8 encoded */
18685 #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
18708 #define SQLITE_AFF_DEFER 0x58 /* 'X' - defer computation until later */
18713 ** The SQLITE_AFF_MASK values masks off the significant bits of an
18719 ** Additional bit values that can be ORed with an affinity without
18723 ** It causes an assert() to fire if either operand to a comparison
18732 ** An object of this type is created for each virtual table present in
18740 ** database connections, even when the rest of the in-memory database
18750 ** database schema are initially stored in a linked-list pointed to by
18752 ** When an sqlite3_prepare() operation is required to access the virtual
18757 ** When an in-memory Table object is deleted (for example when the
18765 ** Refer to comments above function sqlite3VtabUnlockList() for an
18766 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
18793 ** in memory by an instance of the following structure.
18808 LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
18840 ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
18841 ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
18851 #define TF_Readonly 0x00000001 /* Read-only system table */
18861 #define TF_NoVisibleRowid 0x00000200 /* No user-visible "rowid" column */
18862 #define TF_OOOHidden 0x00000400 /* Out-of-Order hidden columns */
18866 #define TF_Ephemeral 0x00004000 /* An ephemeral table */
18867 #define TF_Eponymous 0x00008000 /* An eponymous virtual table */
18877 #define IsView(X) ((X)->eTabType==TABTYP_VIEW)
18878 #define IsOrdinaryTable(X) ((X)->eTabType==TABTYP_NORM)
18886 # define IsVirtual(X) ((X)->eTabType==TABTYP_VTAB)
18888 ((X)->op==TK_COLUMN && (X)->y.pTab->eTabType==TABTYP_VTAB)
18896 ** only works for non-virtual tables (ordinary tables and views) and is
18901 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
18902 # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
18904 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
18913 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
18914 #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
18916 /* Macro is true if the SQLITE_ALLOW_ROWID_IN_VIEW (mis-)feature is
18926 ** Each foreign key constraint is an instance of the following structure.
18938 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
18941 ** from-table == child-table
18942 ** to-table == parent-table
18944 ** Each REFERENCES clause generates an instance of the following structure
18945 ** which is attached to the from-table. The to-table need not exist when
18946 ** the from-table is created. The existence of the to-table is not checked.
18960 /* EV: R-30323-21917 */
18970 /* The size (in bytes) of an FKey object holding N columns. The answer
18981 ** the operation in progress stops and returns an error code. But prior
18989 ** is omitted and the DO UPDATE clause of an upsert is run instead.
19011 #define OE_Update 6 /* Process as a DO UPDATE in an upsert */
19020 ** An instance of the following structure is passed as the first
19025 ** are nField slots for the columns of an index then one extra slot
19030 u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
19051 ** A record is an object that contains one or more fields of data.
19053 ** the key of an index. A blob encoding of a record is created by
19057 ** An instance of this object serves as a "key" for doing a search on
19058 ** an index b+tree. The goal of the search is to find the entry that
19061 ** pKeyInfo->nField.
19065 ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
19069 ** an equals comparison. default_rc can be -1, 0, or +1. If there are
19070 ** multiple entries in the b-tree with the same key (when only looking
19071 ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
19076 ** get and equal results when comparing this structure to a b-tree record.
19079 ** eqSeen field will indicate whether or not an exact match exists in the
19080 ** b-tree.
19083 KeyInfo *pKeyInfo; /* Collation and sort-order information */
19095 u8 eqSeen; /* True if an equality comparison has been seen */
19100 ** Each SQL index is represented in memory by an
19114 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
19115 ** The second column to be indexed (c1) has an index of 0 in
19122 ** algorithm to employ when an attempt is made to insert a non-unique
19126 ** for a fast test to see if an index can serve as a covering index.
19129 ** "colUsed & colNotIdxed" will be non-zero if the index is not a
19131 ** be true (note-20221022-a). If a column beyond the 63rd column of the
19132 ** table is used, the "colUsed & colNotIdxed" test will always be non-zero
19134 ** an alternative (slower) algorithm to determine whether or not
19138 ** generate VDBE code (as opposed to parsing one read from an sqlite_schema
19139 ** table as part of parsing an existing database schema), transient instances
19142 ** number (it cannot - the database page is not allocated until the VDBE
19167 unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
19172 unsigned bHasExpr:1; /* Index contains an expression, either a literal
19179 IndexSample *aSample; /* Samples of the left-most key */
19180 tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
19181 tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
19195 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
19198 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
19203 #define XN_ROWID (-1) /* Indexed column is the rowid */
19204 #define XN_EXPR (-2) /* Indexed column is an expression */
19226 ** Each token coming out of the lexer is an instance of
19227 ** this structure. Tokens are also used as part of an expression.
19236 const char *z; /* Text of the token. Not NULL-terminated! */
19241 ** An instance of this structure contains information needed to generate
19260 int sortingIdxPTab; /* Cursor number of pseudo-table */
19295 ** assignAggregateRegisters() that computes the value of pAggInfo->iFirstReg.
19299 #define AggInfoColumnReg(A,I) (assert((A)->iFirstReg),(A)->iFirstReg+(I))
19301 (assert((A)->iFirstReg),(A)->iFirstReg+(A)->nColumn+(I))
19303 #define AggInfoColumnReg(A,I) ((A)->iFirstReg+(I))
19305 ((A)->iFirstReg+(A)->nColumn+(I))
19309 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
19310 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
19311 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
19316 ** the option is available (at compile-time).
19325 ** Each node of an expression in the parse tree is an instance
19329 ** as opcodes here. For example, the parser defines TK_GE to be an integer
19331 ** to represent the greater-than-or-equal-to operator in the expression
19334 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
19337 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
19343 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
19344 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
19345 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
19350 ** An expression of the form ID or ID.ID refers to a column in a table.
19354 ** expression is used as a result in an aggregate SELECT, then the
19358 ** If the expression is an unbound variable marker (a question mark
19362 ** If the expression is a subquery then Expr.iColumn holds an integer
19364 ** subquery gives a constant result, then iTable is -1. If the subquery
19369 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
19375 ** help reduce memory requirements, sometimes an Expr object will be
19381 ** an Expr object is truncated. When EP_Reduced is set, then all
19400 int iValue; /* Non-negative integer value if EP_IntValue */
19404 ** space is allocated for the fields below this point. An attempt to
19416 ** space is allocated for the fields below this point. An attempt to
19425 ** TK_TRIGGER: 1 -> new, 0 -> old
19430 ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
19433 i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
19441 ** for a column of an index on an expression */
19458 #define EP_InnerON 0x000002 /* Originates in ON/USING of an inner join */
19465 #define EP_InfixFunc 0x000100 /* True for an infix function: LIKE, GLOB, etc */
19498 #define ExprHasProperty(E,P) (((E)->flags&(u32)(P))!=0)
19499 #define ExprHasAllProperty(E,P) (((E)->flags&(u32)(P))==(u32)(P))
19500 #define ExprSetProperty(E,P) (E)->flags|=(u32)(P)
19501 #define ExprClearProperty(E,P) (E)->flags&=~(u32)(P)
19502 #define ExprAlwaysTrue(E) (((E)->flags&(EP_OuterON|EP_IsTrue))==EP_IsTrue)
19503 #define ExprAlwaysFalse(E) (((E)->flags&(EP_OuterON|EP_IsFalse))==EP_IsFalse)
19504 #define ExprIsFullSize(E) (((E)->flags&(EP_Reduced|EP_TokenOnly))==0)
19509 #define ExprUseUToken(E) (((E)->flags&EP_IntValue)==0)
19510 #define ExprUseUValue(E) (((E)->flags&EP_IntValue)!=0)
19511 #define ExprUseWOfst(E) (((E)->flags&(EP_InnerON|EP_OuterON))==0)
19512 #define ExprUseWJoin(E) (((E)->flags&(EP_InnerON|EP_OuterON))!=0)
19513 #define ExprUseXList(E) (((E)->flags&EP_xIsSelect)==0)
19514 #define ExprUseXSelect(E) (((E)->flags&EP_xIsSelect)!=0)
19515 #define ExprUseYTab(E) (((E)->flags&(EP_WinFunc|EP_Subrtn))==0)
19516 #define ExprUseYWin(E) (((E)->flags&EP_WinFunc)!=0)
19517 #define ExprUseYSub(E) (((E)->flags&EP_Subrtn)!=0)
19526 ** processes but is a no-op for delivery.
19529 # define ExprSetVVAProperty(E,P) (E)->vvaFlags|=(P)
19530 # define ExprHasVVAProperty(E,P) (((E)->vvaFlags&(P))!=0)
19531 # define ExprClearVVAProperties(E) (E)->vvaFlags = 0
19540 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
19541 ** and an Expr struct with the EP_TokenOnly flag set.
19551 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
19554 ** True if the expression passed as an argument was a function with
19555 ** an OVER() clause (a window function).
19561 ExprHasProperty((p), EP_WinFunc) && p->y.pWin->eFrmType!=TK_FILTER \
19567 ** name. An expr/name combination can be used in several ways, such
19569 ** list of "ID = expr" items in an UPDATE. A list of expressions can
19577 ** ---------- -------------------------
19579 ** (2) COLUMN= of an UPDATE
19602 unsigned bNoExpand: 1; /* Term is an auxiliary in NestedFrom and should
19616 /* The size (in bytes) of an ExprList object that is big enough to hold
19630 ** An instance of this structure can hold a simple list of identifiers,
19638 ** column names after a table name in an INSERT statement. In the statement
19642 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
19651 /* The size (in bytes) of an IdList object that can hold up to N IDs. */
19660 #define EU4_EXPR 2 /* Uses IdList.a.u4.pExpr -- NOT CURRENTLY USED */
19669 int regResult; /* Registers holding results of a co-routine */
19674 ** The SrcList object is mostly an array of SrcItems.
19681 ** In the colUsed field, the high-order bit (bit 63) is set if the table
19682 ** contains more than 63 columns and the 64-th or later column is used.
19687 ** always be checked, either by an if-statement or by an assert().
19690 ** --------------- -----------------------------------
19712 Table *pSTab; /* Table object for zName. Mnemonic: Srcitem-TABle */
19716 unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
19718 unsigned isTabFunc :1; /* True if table-valued-function syntax */
19719 unsigned isCorrelated :1; /* True if sub-query is correlated */
19721 unsigned viaCoroutine :1; /* Implemented as a co-routine */
19727 unsigned isOn :1; /* u3.pOn was once valid and non-NULL */
19738 ExprList *pFuncArg; /* Arguments to table-valued-function */
19757 ** The OnOrUsing object represents either an ON clause or a USING clause.
19767 ** content for an SQL statement. For example, a single SrcList object
19806 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
19809 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
19812 #define WHERE_OR_SUBCLAUSE 0x0020 /* Processing a sub-WHERE as part of
19821 #define WHERE_KEEP_ALL_JOINS 0x2000 /* Do not do the omit-noop-join opt */
19841 ** NameContexts can be nested. When resolving names, the inner-most
19857 ExprList *pEList; /* Optional list of result-set columns */
19859 Upsert *pUpsert; /* ON CONFLICT clause information from an upsert */
19897 #define NC_InAggFunc 0x020000 /* True if analyzing arguments to an agg func */
19899 #define NC_NoSelect 0x080000 /* Do not descend into sub-selects */
19901 #define NC_OrderAgg 0x8000000 /* Has an aggregate other than count/min/max */
19904 ** An instance of the following object describes a single ON CONFLICT
19905 ** clause in an upsert.
19908 ** conflict-target clause. (In "ON CONFLICT(a,b)" the "(a,b)" is the
19909 ** conflict-target clause.) The pUpsertTargetWhere is the optional
19920 ExprList *pUpsertSet; /* The SET clause from an ON CONFLICT UPDATE */
19941 ** An instance of the following structure contains all information
20014 #define SF_PushDown 0x1000000 /* Modified by WHERE-clause push-down opt */
20023 ((X)->fg.isSubquery && \
20024 ((X)->u4.pSubq->pSelect->selFlags&SF_NestedFrom)!=0)
20032 ** identified by pDest->iSDParm.
20034 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
20036 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
20041 ** the side-effects of functions.
20048 ** in register pDest->iSDParm then abandon the rest
20052 ** row of result as the key in table pDest->iSDParm.
20053 ** Apply the affinity pDest->affSdst before storing
20054 ** results. if pDest->iSDParm2 is positive, then it is
20057 ** pDest->iSDParm table. This SRT is used to
20060 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
20066 ** SRT_Coroutine Generate a co-routine that returns a new row of
20068 ** of the co-routine is stored in register pDest->iSDParm
20069 ** and the result row is stored in pDest->nDest registers
20070 ** starting with pDest->iSdst.
20072 ** SRT_Table Store results in temporary table pDest->iSDParm.
20078 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
20079 ** But also use temporary table pDest->iSDParm+1 as
20083 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
20084 ** an index). Append a sequence number so that all entries
20087 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
20089 ** index at pDest->iSDParm+1 hold all prior stores.
20092 ** pDest->iSDParm. If (pDest->iSDParm<0), then the temp
20093 ** table is an intkey table - in this case the first
20095 ** key. If (pDest->iSDParm>0), then the table is an index
20096 ** table. (pDest->iSDParm) is the number of key columns in
20099 #define SRT_Union 1 /* Store result as keys in an index */
20108 #define IgnorableDistinct(X) ((X->eDest)<=SRT_DistQueue)
20110 #define SRT_Queue 7 /* Store result in an queue */
20111 #define SRT_Fifo 8 /* Store result as data with an automatic rowid */
20114 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Fifo)
20118 #define SRT_Set 11 /* Store results as keys in an index */
20121 #define SRT_Table 14 /* Store result as data with an automatic rowid */
20125 ** An instance of this object describes where to put of the results of
20142 ** the code generator needs. We have to keep per-table autoincrement
20156 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
20161 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
20200 ** For each index X that has as one of its arguments either an expression
20203 ** there is an instance of this object on the Parse.pIdxExpr list.
20214 u8 bMaybeNullRow; /* True if we need an OP_IfNullRow check */
20223 ** An instance of the ParseCleanup object specifies an operation that
20234 ** An SQL parser context. A copy of this structure is passed through
20243 ** The nTableLock and aTableLock variables are only used if the shared-cache
20244 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
20245 ** used to store the set of table-locks required by the statement being
20251 char *zErrMsg; /* An error message */
20252 Vdbe *pVdbe; /* An engine for executing database bytecode */
20258 u8 mayAbort; /* True if statement may throw an ABORT exception */
20279 bft checkSchema :1; /* Causes schema cookie check after an error */
20286 int iSelfTab; /* Table associated with an index on expr, or negative
20287 ** of the base register during check-constraint eval */
20303 TableLock *aTableLock; /* Required table locks for shared-cache mode */
20350 int nHeight; /* Expression tree height of current sub-select */
20356 Index *pNewIndex; /* An index being constructed by CREATE INDEX.
20360 const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
20382 #define PARSE_HDR_SZ (offsetof(Parse,aTempReg)-offsetof(Parse,zErrMsg)) /* Recursive part w/o aColC…
20384 #define PARSE_TAIL_SZ (sizeof(Parse)-PARSE_RECURSE_SZ) /* Non-recursive part */
20388 ** Return true if currently inside an sqlite3_declare_vtab() call.
20393 #define IN_DECLARE_VTAB (pParse->eParseMode==PARSE_MODE_DECLARE_VTAB)
20399 #define IN_RENAME_OBJECT (pParse->eParseMode>=PARSE_MODE_RENAME)
20405 #define IN_SPECIAL_PARSE (pParse->eParseMode!=PARSE_MODE_NORMAL)
20409 ** An instance of the following structure can be declared on a stack and used
20429 #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
20433 #define OPFLAG_LASTROWID 0x20 /* Set to update db->lastRowid */
20434 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
20435 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
20437 #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
20452 ** Each trigger present in the database schema is stored as an instance of
20473 IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
20474 the <column-list> is stored here */
20482 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
20492 ** An instance of struct TriggerStep is used to store a single SQL statement
20493 ** that is a part of a trigger-program.
20498 ** the first step of the trigger-program.
20505 ** orconf -> stores the ON CONFLICT algorithm
20506 ** pSelect -> The content to be inserted - either a SELECT statement or
20508 ** zTarget -> Dequoted name of the table to insert into.
20509 ** pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
20510 ** statement, then this stores the column-names to be
20512 ** pUpsert -> The ON CONFLICT clauses for an Upsert
20515 ** zTarget -> Dequoted name of the table to delete from.
20516 ** pWhere -> The WHERE clause of the DELETE statement if one is specified.
20520 ** zTarget -> Dequoted name of the table to update.
20521 ** pWhere -> The WHERE clause of the UPDATE statement if one is specified.
20523 ** pExprList -> A list of the columns to update and the expressions to update
20528 ** pSelect -> The SELECT statement
20531 ** pExprList -> The list of expressions that follow the RETURNING keyword.
20545 Upsert *pUpsert; /* Upsert clauses on an INSERT */
20547 TriggerStep *pNext; /* Next in the link-list */
20548 TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
20566 ** An object used to accumulate the text of a string where we
20578 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
20582 #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
20585 ** The following object is the header for an "RCStr" or "reference-counted
20586 ** string". An RCStr is passed around and used like any other char*
20593 ** 2. Use sqlite3RCStrUnref() to free an RCStr string rather than
20596 ** 3. Make a (read-only) copy of a read-only RCStr string using
20599 ** "String" is in the name, but an RCStr object can also be used to hold
20627 #define INITFLAG_AlterAdd 0x0003 /* Reparse after an ADD COLUMN */
20630 ** on debug-builds of the CLI using ".testctrl tune ID VALUE". Tuning
20633 ** be used on trunk check-ins. They are a temporary mechanism available
20638 #define SQLITE_NTUNE 6 /* Should be zero for all trunk check-ins */
20640 # define Tuning(X) (sqlite3Config.aTune[(X)-1])
20655 u8 bUseCis; /* Use covering indices for full-scans */
20659 u8 bJsonSelfcheck; /* Double-check JSON parsing */
20662 int neverCorrupt; /* Database is always well-formed */
20665 int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
20666 sqlite3_mem_methods m; /* Low-level memory allocation interface */
20667 sqlite3_mutex_methods mutex; /* Low-level mutex interface */
20668 sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
20678 int sharedCacheEnabled; /* true if shared-cache mode enabled */
20680 /* The above might be initialized to non-zero. The following need to always
20716 u32 szSorterRef; /* Min size in bytes to use sorter-refs */
20718 /* vvvv--- must be last ---vvv */
20726 ** the assert is only valid on a well-formed database. Instead of:
20738 ** things that are always true for well-formed databases.
20743 ** Context pointer passed down through the tree-walk.
20752 u16 mWFlags; /* Use-dependent flags */
20786 const char *zType; /* Type of the container - used for error messages */
20787 const Token *pName; /* Name of the container - used for error messages */
20815 ** Return code from the parse-tree walking primitives and their
20842 ** An instance of the With object represents a WITH clause containing
20888 ** that is N bytes long, including the zero-terminator. */
20893 ** An instance of the TreeView object is used for printing the content of
20894 ** data structures on sqlite3DebugPrintf() using a tree-like view.
20907 ** the Expr.y.pWin field for each window function in an expression tree.
20911 ** (2) All window functions in a single SELECT form a linked-list
20918 ** (4) For an aggregate function with a FILTER clause, an instance
20984 ** Assuming zIn points to the first byte of a UTF-8 character,
20985 ** advance zIn to point to the first byte of the next UTF-8 character.
20996 ** routines that report the line-number on which the error originated
21032 ** FTS4 is really an extension for FTS3. It is enabled using the
21034 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
21168 # define MAN754 ((((u64)1)<<52)-1)
21180 ** An instance of the following structure holds information about SQL
21190 ** An instance of this object receives the decoding of a floating point
21191 ** value into an approximate decimal representation.
21194 char sign; /* '+' or '-' */
21335 # define sqlite3TableColumnToStorage(T,X) (X) /* No-op pass-through */
21336 # define sqlite3StorageColumnToTable(T,X) (X) /* No-op pass-through */
21345 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
21612 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
21613 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
21677 ** Routines to read and write variable-length integers. These used to
21905 ** The interface to the LEMON-generated parser
21966 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
22043 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
22045 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
22047 ** provided (enforcement of FK constraints requires the triggers sub-system).
22098 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
22152 ** sqlite3IoTrace is a pointer to a printf-like routine used to
22169 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
22181 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
22185 ** passed back to non-lookaside free() routines. Asserts such as the
22186 ** example above are placed on the non-lookaside free() routines to verify
22189 ** All of this is no-op for a production build. It only comes into
22190 ** play when the SQLITE_MEMDEBUG compile-time option is used.
22197 # define sqlite3MemdebugSetType(X,Y) /* no-op */
22241 # define IS_STMT_SCANSTATUS(db) (db->flags & SQLITE_StmtScanStatus)
22263 ** all of the platform-specific files (os_*.c) and is #included into those
22275 ** switch. The following code should catch this problem at compile-time.
22290 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
22314 || sqlite3_io_error_pending-- == 1 ) \
22329 sqlite3_diskfull_pending--; \
22372 ** This file implements routines used to report what compile-time options
22375 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* IMP: R-16824-07538 */
22379 ** autoconf-based build
22393 ** comma. e.g. (-DSQLITE_DEFAULT_LOOKASIDE="100,100") */
22399 ** An array of names of all compile-time options. This array should
22400 ** be sorted A-Z.
22403 ** only a handful of compile-time options, so most times this array is usually
22444 "COMPILER=clang-" CTIMEOPT_VAL(__clang_major__) "."
22448 "COMPILER=msvc-" CTIMEOPT_VAL(_MSC_VER),
22450 "COMPILER=gcc-" __VERSION__,
23176 /* An array to map all upper-case characters into their corresponding
23177 ** lower-case character.
23179 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
23219 /* All of the upper-to-lower conversion data is above. The following
23236 ** index (here shown as [256-OP_Ne]) would be out-of-bounds and thus
23237 ** be undefined behavior. That's goofy, but the C-standards people thought
23245 SQLITE_PRIVATE const unsigned char *sqlite3aLTb = &sqlite3UpperToLower[256-OP_Ne];
23246 SQLITE_PRIVATE const unsigned char *sqlite3aEQb = &sqlite3UpperToLower[256+6-OP_Ne];
23247 SQLITE_PRIVATE const unsigned char *sqlite3aGTb = &sqlite3UpperToLower[256+12-OP_Ne];
23250 ** The following 256 byte lookup table is used to support SQLites built-in
23259 ** SQLite identifier character 0x40 $, _, or non-ascii
23263 ** case. i.e. if the character is a lower-case ASCII character.
23264 ** If x is a lower-case ASCII character, then its upper-case equivalent
23265 ** is (x - 0x20). Therefore toupper() can be implemented as:
23272 ** Bit 0x40 is set if the character is non-alphanumeric and can be used in an
23274 ** non-ASCII UTF character. Hence the test for whether or not a character is
23275 ** part of an identifier is 0x46.
23283 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
23315 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
23319 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
23320 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
23322 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
23330 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
23331 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
23332 ** that compile-time option is omitted.
23338 # error "Compile-time disabling of covering index scan using the\
23339 -DSQLITE_ALLOW_COVERING_INDEX_SCAN=0 option is deprecated.\
23355 ** before 3.12.0). -1 means always keep the entire statement journal in
23365 ** The default lookaside-configuration, the format "SZ,N". SZ is the
23367 ** and N is the number of slots. The lookaside-configuration can be
23368 ** changed as start-time using sqlite3_config(SQLITE_CONFIG_LOOKASIDE)
23369 ** or at run-time for an individual database connection using
23372 ** With the two-size-lookaside enhancement, less lookaside is required.
23373 ** The default configuration of 1200,40 actually provides 30 1200-byte slots
23374 ** and 93 128-byte slots, which is more lookaside than is available
23375 ** using the older 1200,100 configuration without two-size-lookaside.
23386 /* The default maximum size of an in-memory database created using
23451 0, /* mNoVisibleRowid. 0 == allow rowid-in-view */
23464 ** Hash table for global functions - functions common to all
23466 ** read-only.
23485 ** sqlite3Hwtime() for profiling. This is a no-op on standard builds.
23492 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
23504 ** 0x40000000 results in an incompatible database file format!
23624 ** executed by a virtual machine. Each instruction is an instance
23650 ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
23652 ** * A b-tree cursor
23653 ** - In the main database or in an ephemeral database
23654 ** - On either an index or a table
23657 ** * A one-row "pseudotable" stored in a single register
23662 i8 iDb; /* Index of cursor database in db->aDb[] */
23670 Bool isEphemeral:1; /* True for an ephemeral table */
23671 Bool useRandomRowid:1; /* Generate new record numbers semi-randomly */
23674 Bool colCache:1; /* pCache pointer is initialized and non-NULL */
23690 ** on this cursor" and "the most recent seek was an exact match".
23723 ** The size (in bytes) of a VdbeCursor object that has an nField value of N
23730 /* Return true if P is a null-only cursor
23733 ((P)->eCurType==CURTYPE_PSEUDO && (P)->nullRow && (P)->seekResult==0)
23755 ** When a sub-program is executed (OP_Program), a structure of this type
23758 ** values stored in the Vdbe struct. When the sub-program is finished,
23760 ** restoring the state of the VM to as it was before the sub-program
23796 i64 nDbChange; /* Value of db->nChange */
23831 void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
23848 ** * MEM_Null An SQL NULL value
23850 ** * MEM_Null|MEM_Zero An SQL NULL with the virtual table
23851 ** UPDATE no-change flag set
23853 ** * MEM_Null|MEM_Term| An SQL NULL, but also contains a
23857 ** * MEM_Null|MEM_Cleared Special SQL NULL that compares non-equal
23861 ** length Mem.n. Zero-terminated if
23878 ** * MEM_IntReal Real stored as an integer in Mem.u.i.
23880 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
23893 #define MEM_Int 0x0004 /* Value is an integer */
23914 #define MEM_Ephem 0x4000 /* Mem.z points to an ephemeral string */
23915 #define MEM_Agg 0x8000 /* Mem.z points to an agg function context */
23917 /* Return TRUE if Mem X contains dynamically allocated content - anything
23921 (((X)->flags&(MEM_Agg|MEM_Dyn))!=0)
23927 ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
23930 ** True if Mem X is a NULL-nochng type.
23933 (((X)->flags&MEM_TypeMask)==(MEM_Null|MEM_Zero) \
23934 && (X)->n==0 && (X)->u.nZero==0)
23945 #define memIsValid(M) ((M)->flags & MEM_AffMask)!=0
23950 ** implementation calling sqlite3_set_auxdata() is stored in an instance
23964 ** The "context" argument for an installable function. A pointer to an
23990 ** The size (in bytes) of an sqlite3_context object that holds N
24002 ** notes that make an SQLITE_SCANSTAT_NCYCLE value available. It is
24003 ** an array of up to 3 ranges of VM addresses for which the Vdbe.anCycle[]
24006 ** instructions. A start value of 0 indicates an empty range.
24014 int iSelectID; /* The "Select-ID" for this loop */
24019 /* The DblquoteStr object holds the text of a double-quoted
24022 ** When computing a normalized SQL statement for an SQL statement, that
24023 ** list is consulted for each double-quoted identifier to see if the
24033 ** An instance of the virtual machine. This structure contains the complete
24037 ** is really a pointer to an instance of this structure.
24071 i64 startTime; /* Time when query started - used for profiling */
24080 u8 errorAction; /* Recovery action to do in case of an error */
24086 bft changeCntOn:1; /* True to update the change-counter */
24091 yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
24097 DblquoteStr *pDblStr; /* List of double-quoted string literals */
24104 SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
24145 ** An instance of this object is used to pass an vector of values into
24147 ** set of values on the right-hand side of an IN constraint.
24149 ** The value as passed into xFilter is an sqlite3_value with a "pointer"
24158 BtCursor *pCsr; /* An ephemeral table holding all values */
24163 ** single-byte varint.
24321 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
24366 ** we have to locate the state vector at run-time. In the more common
24396 ** The value of N is added to the current status value and the high-water
24400 ** mark is unchanged. N must be non-negative for StatusDown().
24420 wsdStat.nowValue[op] -= N; in sqlite3StatusDown()
24492 p = p->pNext; in countLookasideSlots()
24502 u32 nInit = countLookasideSlots(db->lookaside.pInit); in sqlite3LookasideUsed()
24503 u32 nFree = countLookasideSlots(db->lookaside.pFree); in sqlite3LookasideUsed()
24505 nInit += countLookasideSlots(db->lookaside.pSmallInit); in sqlite3LookasideUsed()
24506 nFree += countLookasideSlots(db->lookaside.pSmallFree); in sqlite3LookasideUsed()
24508 assert( db->lookaside.nSlot >= nInit+nFree ); in sqlite3LookasideUsed()
24509 if( pHighwater ) *pHighwater = (int)(db->lookaside.nSlot - nInit); in sqlite3LookasideUsed()
24510 return (int)(db->lookaside.nSlot - (nInit+nFree)); in sqlite3LookasideUsed()
24520 int *pHighwater, /* Write high-water mark here */ in sqlite3_db_status()
24521 int resetFlag /* Reset high-water mark if true */ in sqlite3_db_status()
24529 sqlite3_mutex_enter(db->mutex); in sqlite3_db_status()
24534 LookasideSlot *p = db->lookaside.pFree; in sqlite3_db_status()
24536 while( p->pNext ) p = p->pNext; in sqlite3_db_status()
24537 p->pNext = db->lookaside.pInit; in sqlite3_db_status()
24538 db->lookaside.pInit = db->lookaside.pFree; in sqlite3_db_status()
24539 db->lookaside.pFree = 0; in sqlite3_db_status()
24542 p = db->lookaside.pSmallFree; in sqlite3_db_status()
24544 while( p->pNext ) p = p->pNext; in sqlite3_db_status()
24545 p->pNext = db->lookaside.pSmallInit; in sqlite3_db_status()
24546 db->lookaside.pSmallInit = db->lookaside.pSmallFree; in sqlite3_db_status()
24547 db->lookaside.pSmallFree = 0; in sqlite3_db_status()
24560 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 ); in sqlite3_db_status()
24561 assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 ); in sqlite3_db_status()
24563 *pHighwater = (int)db->lookaside.anStat[op-SQLITE_DBSTATUS_LOOKASIDE_HIT]; in sqlite3_db_status()
24565 db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0; in sqlite3_db_status()
24571 ** Return an approximation for the amount of memory currently used in sqlite3_db_status()
24580 for(i=0; i<db->nDb; i++){ in sqlite3_db_status()
24581 Btree *pBt = db->aDb[i].pBt; in sqlite3_db_status()
24598 ** *pCurrent gets an accurate estimate of the amount of memory used in sqlite3_db_status()
24607 db->pnBytesFreed = &nByte; in sqlite3_db_status()
24608 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd ); in sqlite3_db_status()
24609 db->lookaside.pEnd = db->lookaside.pStart; in sqlite3_db_status()
24610 for(i=0; i<db->nDb; i++){ in sqlite3_db_status()
24611 Schema *pSchema = db->aDb[i].pSchema; in sqlite3_db_status()
24616 pSchema->tblHash.count in sqlite3_db_status()
24617 + pSchema->trigHash.count in sqlite3_db_status()
24618 + pSchema->idxHash.count in sqlite3_db_status()
24619 + pSchema->fkeyHash.count in sqlite3_db_status()
24621 nByte += sqlite3_msize(pSchema->tblHash.ht); in sqlite3_db_status()
24622 nByte += sqlite3_msize(pSchema->trigHash.ht); in sqlite3_db_status()
24623 nByte += sqlite3_msize(pSchema->idxHash.ht); in sqlite3_db_status()
24624 nByte += sqlite3_msize(pSchema->fkeyHash.ht); in sqlite3_db_status()
24626 for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){ in sqlite3_db_status()
24629 for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){ in sqlite3_db_status()
24634 db->pnBytesFreed = 0; in sqlite3_db_status()
24635 db->lookaside.pEnd = db->lookaside.pTrueEnd; in sqlite3_db_status()
24644 ** *pCurrent gets an accurate estimate of the amount of memory used in sqlite3_db_status()
24652 db->pnBytesFreed = &nByte; in sqlite3_db_status()
24653 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd ); in sqlite3_db_status()
24654 db->lookaside.pEnd = db->lookaside.pStart; in sqlite3_db_status()
24655 for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pVNext){ in sqlite3_db_status()
24658 db->lookaside.pEnd = db->lookaside.pTrueEnd; in sqlite3_db_status()
24659 db->pnBytesFreed = 0; in sqlite3_db_status()
24661 *pHighwater = 0; /* IMP: R-64479-57858 */ in sqlite3_db_status()
24683 for(i=0; i<db->nDb; i++){ in sqlite3_db_status()
24684 if( db->aDb[i].pBt ){ in sqlite3_db_status()
24685 Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt); in sqlite3_db_status()
24689 *pHighwater = 0; /* IMP: R-42420-56072 */ in sqlite3_db_status()
24690 /* IMP: R-54100-20147 */ in sqlite3_db_status()
24691 /* IMP: R-29431-39229 */ in sqlite3_db_status()
24696 /* Set *pCurrent to non-zero if there are unresolved deferred foreign in sqlite3_db_status()
24701 *pHighwater = 0; /* IMP: R-11967-56545 */ in sqlite3_db_status()
24702 *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0; in sqlite3_db_status()
24710 sqlite3_mutex_leave(db->mutex); in sqlite3_db_status()
24730 ** There is only one exported symbol in this file - the function
24739 ** 1970-01-01 00:00:00 is JD 2440587.5
24740 ** 2000-01-01 00:00:00 is JD 2451544.5
24742 ** This implementation requires years to be expressed as a 4-digit number
24743 ** which means that only dates between 0000-01-01 and 9999-12-31 can
24749 ** use the julian calendar for dates prior to 1582-10-15 and for some
24757 ** ISBN 0-943396-61-1
24758 ** Willmann-Bell, Inc
24793 unsigned isError : 1; /* An overflow has occurred */
24806 ** of a four-character format specifiers ABCD is:
24820 ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
24821 ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
24822 ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
24823 ** the 2-digit day which is the last integer in the set.
24836 char N = zFormat[0] - '0'; in getDigits()
24837 char min = zFormat[1] - '0'; in getDigits()
24842 max = aMx[zFormat[2] - 'a']; in getDigits()
24845 while( N-- ){ in getDigits()
24849 val = val*10 + *zDate - '0'; in getDigits()
24866 ** Parse a timezone extension on the end of a date-time.
24869 ** (+/-)HH:MM
24876 ** of change in p->tz and return 0. If a parser error occurs,
24877 ** return non-zero.
24879 ** A missing specifier is not considered an error.
24886 p->tz = 0; in parseTimezone()
24888 if( c=='-' ){ in parseTimezone()
24889 sgn = -1; in parseTimezone()
24894 p->isLocal = 0; in parseTimezone()
24895 p->isUtc = 1; in parseTimezone()
24905 p->tz = sgn*(nMn + nHr*60); in parseTimezone()
24935 ms = ms*10.0 + *zDate - '0'; in parseHhMmSs()
24940 /* Truncate to avoid problems with sub-milliseconds in parseHhMmSs()
24947 p->validJD = 0; in parseHhMmSs()
24948 p->rawS = 0; in parseHhMmSs()
24949 p->validHMS = 1; in parseHhMmSs()
24950 p->h = h; in parseHhMmSs()
24951 p->m = m; in parseHhMmSs()
24952 p->s = s + ms; in parseHhMmSs()
24962 p->isError = 1; in datetimeError()
24966 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
24967 ** that the YYYY-MM-DD is according to the Gregorian calendar.
24974 if( p->validJD ) return; in computeJD()
24975 if( p->validYMD ){ in computeJD()
24976 Y = p->Y; in computeJD()
24977 M = p->M; in computeJD()
24978 D = p->D; in computeJD()
24980 Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */ in computeJD()
24984 if( Y<-4713 || Y>9999 || p->rawS ){ in computeJD()
24989 Y--; in computeJD()
24993 B = 38 - A + (A/4); in computeJD()
24996 p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000); in computeJD()
24997 p->validJD = 1; in computeJD()
24998 if( p->validHMS ){ in computeJD()
24999 p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000 + 0.5); in computeJD()
25000 if( p->tz ){ in computeJD()
25001 p->iJD -= p->tz*60000; in computeJD()
25002 p->validYMD = 0; in computeJD()
25003 p->validHMS = 0; in computeJD()
25004 p->tz = 0; in computeJD()
25005 p->isUtc = 1; in computeJD()
25006 p->isLocal = 0; in computeJD()
25012 ** Given the YYYY-MM-DD information current in p, determine if there
25013 ** is day-of-month overflow and set nFloor to the number of days that
25018 assert( p->validYMD || p->isError ); in computeFloor()
25019 assert( p->D>=0 && p->D<=31 ); in computeFloor()
25020 assert( p->M>=0 && p->M<=12 ); in computeFloor()
25021 if( p->D<=28 ){ in computeFloor()
25022 p->nFloor = 0; in computeFloor()
25023 }else if( (1<<p->M) & 0x15aa ){ in computeFloor()
25024 p->nFloor = 0; in computeFloor()
25025 }else if( p->M!=2 ){ in computeFloor()
25026 p->nFloor = (p->D==31); in computeFloor()
25027 }else if( p->Y%4!=0 || (p->Y%100==0 && p->Y%400!=0) ){ in computeFloor()
25028 p->nFloor = p->D - 28; in computeFloor()
25030 p->nFloor = p->D - 29; in computeFloor()
25037 ** YYYY-MM-DD HH:MM:SS.FFF
25038 ** YYYY-MM-DD HH:MM:SS
25039 ** YYYY-MM-DD HH:MM
25040 ** YYYY-MM-DD
25043 ** on success and 1 if the input string is not a well-formed
25049 if( zDate[0]=='-' ){ in parseYyyyMmDd()
25055 if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){ in parseYyyyMmDd()
25063 p->validHMS = 0; in parseYyyyMmDd()
25067 p->validJD = 0; in parseYyyyMmDd()
25068 p->validYMD = 1; in parseYyyyMmDd()
25069 p->Y = neg ? -Y : Y; in parseYyyyMmDd()
25070 p->M = M; in parseYyyyMmDd()
25071 p->D = D; in parseYyyyMmDd()
25073 if( p->tz ){ in parseYyyyMmDd()
25088 p->iJD = sqlite3StmtCurrentTime(context); in setDateTimeToCurrent()
25089 if( p->iJD>0 ){ in setDateTimeToCurrent()
25090 p->validJD = 1; in setDateTimeToCurrent()
25091 p->isUtc = 1; in setDateTimeToCurrent()
25092 p->isLocal = 0; in setDateTimeToCurrent()
25104 ** If the value is a valid unix timestamp, put it in p->s and set p->rawS.
25107 p->s = r; in setRawDateNumber()
25108 p->rawS = 1; in setRawDateNumber()
25110 p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5); in setRawDateNumber()
25111 p->validJD = 1; in setRawDateNumber()
25121 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
25125 ** In the first form, the +/-HH:MM is always optional. The fractional
25149 p->useSubsec = 1; in parseDateOrTime()
25155 /* The julian day number for 9999-12-31 23:59:59.999 is 5373484.4999999.
25178 if( p->validYMD ) return; in computeYMD()
25179 if( !p->validJD ){ in computeYMD()
25180 p->Y = 2000; in computeYMD()
25181 p->M = 1; in computeYMD()
25182 p->D = 1; in computeYMD()
25183 }else if( !validJulianDay(p->iJD) ){ in computeYMD()
25187 Z = (int)((p->iJD + 43200000)/86400000); in computeYMD()
25188 alpha = (int)((Z + 32044.75)/36524.25) - 52; in computeYMD()
25189 A = Z + 1 + alpha - ((alpha+100)/4) + 25; in computeYMD()
25191 C = (int)((B - 122.1)/365.25); in computeYMD()
25193 E = (int)((B-D)/30.6001); in computeYMD()
25195 p->D = B - D - X1; in computeYMD()
25196 p->M = E<14 ? E-1 : E-13; in computeYMD()
25197 p->Y = p->M>2 ? C - 4716 : C - 4715; in computeYMD()
25199 p->validYMD = 1; in computeYMD()
25207 if( p->validHMS ) return; in computeHMS()
25209 day_ms = (int)((p->iJD + 43200000) % 86400000); in computeHMS()
25210 p->s = (day_ms % 60000)/1000.0; in computeHMS()
25212 p->m = day_min % 60; in computeHMS()
25213 p->h = day_min / 60; in computeHMS()
25214 p->rawS = 0; in computeHMS()
25215 p->validHMS = 1; in computeHMS()
25230 p->validYMD = 0; in clearYMD_HMS_TZ()
25231 p->validHMS = 0; in clearYMD_HMS_TZ()
25232 p->tz = 0; in clearYMD_HMS_TZ()
25242 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
25245 ** already, check for an MSVC build environment that provides
25256 ** using whatever operating-system specific localtime facility that
25258 ** non-zero on any kind of error.
25260 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is non-zero then this
25263 ** invoked in place of the OS-defined localtime() function.
25265 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
25331 if( p->iJD<2108667600*(i64)100000 /* 1970-01-01 */ in toLocaltime()
25332 || p->iJD>2130141456*(i64)100000 /* 2038-01-18 */ in toLocaltime()
25334 /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only in toLocaltime()
25336 ** SQLite attempts to map the year into an equivalent year within this in toLocaltime()
25341 iYearDiff = (2000 + x.Y%4) - x.Y; in toLocaltime()
25345 t = (time_t)(x.iJD/1000 - 21086676*(i64)10000); in toLocaltime()
25348 t = (time_t)(p->iJD/1000 - 21086676*(i64)10000); in toLocaltime()
25351 sqlite3_result_error(pCtx, "local time unavailable", -1); in toLocaltime()
25354 p->Y = sLocal.tm_year + 1900 - iYearDiff; in toLocaltime()
25355 p->M = sLocal.tm_mon + 1; in toLocaltime()
25356 p->D = sLocal.tm_mday; in toLocaltime()
25357 p->h = sLocal.tm_hour; in toLocaltime()
25358 p->m = sLocal.tm_min; in toLocaltime()
25359 p->s = sLocal.tm_sec + (p->iJD%1000)*0.001; in toLocaltime()
25360 p->validYMD = 1; in toLocaltime()
25361 p->validHMS = 1; in toLocaltime()
25362 p->validJD = 0; in toLocaltime()
25363 p->rawS = 0; in toLocaltime()
25364 p->tz = 0; in toLocaltime()
25365 p->isError = 0; in toLocaltime()
25375 ** Where NNN is an arbitrary floating-point number and "days" can be one
25398 if( !p->rawS || p->validJD ){ in autoAdjustDate()
25399 p->rawS = 0; in autoAdjustDate()
25400 }else if( p->s>=-21086676*(i64)10000 /* -4713-11-24 12:00:00 */ in autoAdjustDate()
25401 && p->s<=(25340230*(i64)10000)+799 /* 9999-12-31 23:59:59 */ in autoAdjustDate()
25403 double r = p->s*1000.0 + 210866760000000.0; in autoAdjustDate()
25405 p->iJD = (sqlite3_int64)(r + 0.5); in autoAdjustDate()
25406 p->validJD = 1; in autoAdjustDate()
25407 p->rawS = 0; in autoAdjustDate()
25412 ** Process a modifier to a date-time stamp. The modifiers are
25421 ** +/-YYYY-MM-DD HH:MM:SS.SSS
25437 ** is in a system call (i.e. localtime()), then an error message is written
25438 ** to context pCtx. If the error is an unrecognized modifier, no error is
25459 if( idx>1 ) return 1; /* IMP: R-33611-57934 */ in parseModifier()
25469 ** Resolve day-of-month overflow by rolling forward into the next in parseModifier()
25471 ** a no-op that is only included for symmetry. See "floor". in parseModifier()
25477 p->nFloor = 0; in parseModifier()
25485 ** Resolve day-of-month overflow by rolling back to the end of the in parseModifier()
25490 p->iJD -= p->nFloor*86400000; in parseModifier()
25500 ** Always interpret the prior number as a julian-day value. If this in parseModifier()
25506 if( idx>1 ) return 1; /* IMP: R-31176-64601 */ in parseModifier()
25507 if( p->validJD && p->rawS ){ in parseModifier()
25509 p->rawS = 0; in parseModifier()
25522 rc = p->isLocal ? SQLITE_OK : toLocaltime(p, pCtx); in parseModifier()
25523 p->isUtc = 0; in parseModifier()
25524 p->isLocal = 1; in parseModifier()
25533 ** Treat the current value of p->s as the number of in parseModifier()
25536 if( sqlite3_stricmp(z, "unixepoch")==0 && p->rawS ){ in parseModifier()
25537 if( idx>1 ) return 1; /* IMP: R-49255-55373 */ in parseModifier()
25538 r = p->s*1000.0 + 210866760000000.0; in parseModifier()
25541 p->iJD = (sqlite3_int64)(r + 0.5); in parseModifier()
25542 p->validJD = 1; in parseModifier()
25543 p->rawS = 0; in parseModifier()
25549 if( p->isUtc==0 ){ in parseModifier()
25556 iGuess = iOrigJD = p->iJD; in parseModifier()
25561 iGuess -= iErr; in parseModifier()
25567 iErr = new.iJD - iOrigJD; in parseModifier()
25570 p->iJD = iGuess; in parseModifier()
25571 p->validJD = 1; in parseModifier()
25572 p->isUtc = 1; in parseModifier()
25573 p->isLocal = 0; in parseModifier()
25586 ** date is already on the appropriate weekday, this is a no-op. in parseModifier()
25593 p->tz = 0; in parseModifier()
25594 p->validJD = 0; in parseModifier()
25596 Z = ((p->iJD + 129600000)/86400000) % 7; in parseModifier()
25597 if( Z>n ) Z -= 7; in parseModifier()
25598 p->iJD += (n - Z)*86400000; in parseModifier()
25621 p->useSubsec = 1; in parseModifier()
25626 if( !p->validJD && !p->validYMD && !p->validHMS ) break; in parseModifier()
25629 p->validHMS = 1; in parseModifier()
25630 p->h = p->m = 0; in parseModifier()
25631 p->s = 0.0; in parseModifier()
25632 p->rawS = 0; in parseModifier()
25633 p->tz = 0; in parseModifier()
25634 p->validJD = 0; in parseModifier()
25636 p->D = 1; in parseModifier()
25639 p->M = 1; in parseModifier()
25640 p->D = 1; in parseModifier()
25648 case '-': in parseModifier()
25667 if( z[n]=='-' ){ in parseModifier()
25676 if( z[n]=='-' ){ in parseModifier()
25677 /* A modifier of the form (+|-)YYYY-MM-DD adds or subtracts the in parseModifier()
25679 ** the range 0-11 and DD is limited to 0-30. in parseModifier()
25681 if( z0!='+' && z0!='-' ) break; /* Must start with +/- */ in parseModifier()
25683 if( getDigits(&z[1], "40f-20a-20d", &Y, &M, &D)!=3 ) break; in parseModifier()
25686 if( getDigits(&z[1], "50f-20a-20d", &Y, &M, &D)!=3 ) break; in parseModifier()
25692 p->validJD = 0; in parseModifier()
25693 if( z0=='-' ){ in parseModifier()
25694 p->Y -= Y; in parseModifier()
25695 p->M -= M; in parseModifier()
25696 D = -D; in parseModifier()
25698 p->Y += Y; in parseModifier()
25699 p->M += M; in parseModifier()
25701 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; in parseModifier()
25702 p->Y += x; in parseModifier()
25703 p->M -= x*12; in parseModifier()
25706 p->validHMS = 0; in parseModifier()
25707 p->validYMD = 0; in parseModifier()
25708 p->iJD += (i64)D*86400000; in parseModifier()
25723 /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the in parseModifier()
25735 tx.iJD -= 43200000; in parseModifier()
25737 tx.iJD -= day*86400000; in parseModifier()
25738 if( z0=='-' ) tx.iJD = -tx.iJD; in parseModifier()
25741 p->iJD += tx.iJD; in parseModifier()
25752 if( sqlite3UpperToLower[(u8)z[n-1]]=='s' ) n--; in parseModifier()
25755 rRounder = r<0 ? -0.5 : +0.5; in parseModifier()
25756 p->nFloor = 0; in parseModifier()
25760 && r>-aXformType[i].rLimit && r<aXformType[i].rLimit in parseModifier()
25766 p->M += (int)r; in parseModifier()
25767 x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12; in parseModifier()
25768 p->Y += x; in parseModifier()
25769 p->M -= x*12; in parseModifier()
25771 p->validJD = 0; in parseModifier()
25772 r -= (int)r; in parseModifier()
25779 assert( p->M>=0 && p->M<=12 ); in parseModifier()
25780 p->Y += y; in parseModifier()
25782 p->validJD = 0; in parseModifier()
25783 r -= (int)r; in parseModifier()
25788 p->iJD += (sqlite3_int64)(r*1000.0*aXformType[i].rXform + rRounder); in parseModifier()
25804 ** Process time function arguments. argv[0] is a date-time stamp.
25841 if( p->isError || !validJulianDay(p->iJD) ) return 1; in isDate()
25842 if( argc==1 && p->validYMD && p->D>28 ){ in isDate()
25843 /* Make sure a YYYY-MM-DD is normalized. in isDate()
25844 ** Example: 2023-02-31 -> 2023-03-03 */ in isDate()
25845 assert( p->validJD ); in isDate()
25846 p->validYMD = 0; in isDate()
25878 ** the unix epoch of 1970-01-01 00:00:00 GMT.
25889 sqlite3_result_double(context, (x.iJD - 21086676*(i64)10000000)/1000.0); in unixepochFunc()
25891 sqlite3_result_int64(context, x.iJD/1000 - 21086676*(i64)10000); in unixepochFunc()
25899 ** Return YYYY-MM-DD HH:MM:SS
25912 if( Y<0 ) Y = -Y; in datetimeFunc()
25917 zBuf[5] = '-'; in datetimeFunc()
25920 zBuf[8] = '-'; in datetimeFunc()
25948 zBuf[0] = '-'; in datetimeFunc()
25951 sqlite3_result_text(context, &zBuf[1], n-1, SQLITE_TRANSIENT); in datetimeFunc()
26001 ** Return YYYY-MM-DD
26014 if( Y<0 ) Y = -Y; in dateFunc()
26019 zBuf[5] = '-'; in dateFunc()
26022 zBuf[8] = '-'; in dateFunc()
26027 zBuf[0] = '-'; in dateFunc()
26038 ** In other words, compute the zero-based day number for the
26048 assert( pDate->validJD ); in daysAfterJan01()
26053 return (int)((pDate->iJD-jan01.iJD+43200000)/86400000); in daysAfterJan01()
26065 assert( pDate->validJD ); in daysAfterMonday()
26066 return (int)((pDate->iJD+43200000)/86400000) % 7; in daysAfterMonday()
26078 assert( pDate->validJD ); in daysAfterSunday()
26079 return (int)((pDate->iJD+129600000)/86400000) % 7; in daysAfterSunday()
26087 ** %d day of month 01-31
26088 ** %e day of month 1-31
26090 ** %F ISO date. YYYY-MM-DD
26091 ** %G ISO year corresponding to %V 0000-9999.
26092 ** %g 2-digit ISO year corresponding to %V 00-99
26093 ** %H hour 00-24
26094 ** %k hour 0-24 (leading zero converted to space)
26095 ** %I hour 01-12
26096 ** %j day of year 001-366
26098 ** %l hour 1-12 (leading zero converted to space)
26099 ** %m month 01-12
26100 ** %M minute 00-59
26104 ** %s seconds since 1970-01-01
26105 ** %S seconds 00-59
26107 ** %u day of week 1-7 Monday==1, Sunday==7
26108 ** %w day of week 0-6 Sunday==0, Monday==1
26109 ** %U week of year 00-53 (First Sunday is start of week 01)
26110 ** %V week of year 01-53 (First week containing Thursday is week 01)
26111 ** %W week of year 00-53 (First Monday is start of week 01)
26112 ** %Y year 0000-9999
26129 if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return; in strftimeFunc()
26131 sqlite3StrAccumInit(&sRes, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]); in strftimeFunc()
26138 if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j)); in strftimeFunc()
26148 case 'f': { /* Fractional seconds. (Non-standard) */ in strftimeFunc()
26155 sqlite3_str_appendf(&sRes, "%04d-%02d-%02d", x.Y, x.M, x.D); in strftimeFunc()
26163 y.iJD += (3 - daysAfterMonday(&x))*86400000; in strftimeFunc()
26181 if( h>12 ) h -= 12; in strftimeFunc()
26190 case 'J': { /* Julian day number. (Non-standard) */ in strftimeFunc()
26218 (x.iJD - 21086676*(i64)10000000)/1000.0); in strftimeFunc()
26220 i64 iS = (i64)(x.iJD/1000 - 21086676*(i64)10000); in strftimeFunc()
26240 case 'U': { /* Week num. 00-53. First Sun of the year is week 01 */ in strftimeFunc()
26242 (daysAfterJan01(&x)-daysAfterSunday(&x)+7)/7); in strftimeFunc()
26245 case 'V': { /* Week num. 01-53. First week with a Thur is week 01 */ in strftimeFunc()
26249 y.iJD += (3 - daysAfterMonday(&x))*86400000; in strftimeFunc()
26255 case 'W': { /* Week num. 00-53. First Mon of the year is week 01 */ in strftimeFunc()
26257 (daysAfterJan01(&x)-daysAfterMonday(&x)+7)/7); in strftimeFunc()
26274 if( j<i ) sqlite3_str_append(&sRes, zFmt+j, (int)(i-j)); in strftimeFunc()
26312 ** +YYYY-MM-DD HH:MM:SS.SSS
26314 ** The initial "+" becomes "-" if DATE1 occurs before DATE2. For
26319 ** Both DATE arguments must be either a julian day number, or an
26320 ** ISO-8601 string. The unix timestamps are not supported by this
26339 Y = d1.Y - d2.Y; in timediffFunc()
26345 M = d1.M - d2.M; in timediffFunc()
26347 Y--; in timediffFunc()
26356 M--; in timediffFunc()
26359 Y--; in timediffFunc()
26361 d2.M--; in timediffFunc()
26364 d2.Y--; in timediffFunc()
26369 d1.iJD -= d2.iJD; in timediffFunc()
26372 sign = '-'; in timediffFunc()
26373 Y = d2.Y - d1.Y; in timediffFunc()
26379 M = d2.M - d1.M; in timediffFunc()
26381 Y--; in timediffFunc()
26390 M--; in timediffFunc()
26393 Y--; in timediffFunc()
26403 d1.iJD = d2.iJD - d1.iJD; in timediffFunc()
26409 sqlite3_str_appendf(&sRes, "%c%04d-%02d-%02d %02d:%02d:%06.3f", in timediffFunc()
26410 sign, Y, M, d1.D-1, d1.h, d1.m, d1.s); in timediffFunc()
26432 ** If the library is compiled to omit the full-scale date and time
26438 ** This function uses the C-library functions time(), gmtime()
26440 ** as the user-data for the function.
26459 t = iT/1000 - 10000*(sqlite3_int64)21086676; in currentTimeFunc()
26470 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT); in currentTimeFunc()
26499 sqlite3_result_text(context, zJson, -1, sqlite3_free); in datedebugFunc()
26513 PURE_DATE(julianday, -1, 0, 0, juliandayFunc ), in sqlite3RegisterDateTimeFunctions()
26514 PURE_DATE(unixepoch, -1, 0, 0, unixepochFunc ), in sqlite3RegisterDateTimeFunctions()
26515 PURE_DATE(date, -1, 0, 0, dateFunc ), in sqlite3RegisterDateTimeFunctions()
26516 PURE_DATE(time, -1, 0, 0, timeFunc ), in sqlite3RegisterDateTimeFunctions()
26517 PURE_DATE(datetime, -1, 0, 0, datetimeFunc ), in sqlite3RegisterDateTimeFunctions()
26518 PURE_DATE(strftime, -1, 0, 0, strftimeFunc ), in sqlite3RegisterDateTimeFunctions()
26521 PURE_DATE(datedebug, -1, 0, 0, datedebugFunc ), in sqlite3RegisterDateTimeFunctions()
26528 STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc), in sqlite3RegisterDateTimeFunctions()
26529 STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc), in sqlite3RegisterDateTimeFunctions()
26561 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
26579 ** from within OsOpen()), but some third-party implementations may.
26619 if( pId->pMethods ){ in sqlite3OsClose()
26620 pId->pMethods->xClose(pId); in sqlite3OsClose()
26621 pId->pMethods = 0; in sqlite3OsClose()
26626 return id->pMethods->xRead(id, pBuf, amt, offset); in sqlite3OsRead()
26630 return id->pMethods->xWrite(id, pBuf, amt, offset); in sqlite3OsWrite()
26633 return id->pMethods->xTruncate(id, size); in sqlite3OsTruncate()
26637 return flags ? id->pMethods->xSync(id, flags) : SQLITE_OK; in sqlite3OsSync()
26641 return id->pMethods->xFileSize(id, pSize); in sqlite3OsFileSize()
26646 return id->pMethods->xLock(id, lockType); in sqlite3OsLock()
26650 return id->pMethods->xUnlock(id, lockType); in sqlite3OsUnlock()
26654 return id->pMethods->xCheckReservedLock(id, pResOut); in sqlite3OsCheckReservedLock()
26666 if( id->pMethods==0 ) return SQLITE_NOTFOUND; in sqlite3OsFileControl()
26676 ** confuses the test scripts - the COMMIT command returns SQLITE_NOMEM in sqlite3OsFileControl()
26680 ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably in sqlite3OsFileControl()
26681 ** means the commit really has failed and an error should be returned in sqlite3OsFileControl()
26684 ** The CKPT_DONE and CKPT_START file-controls are write-only signals in sqlite3OsFileControl()
26691 return id->pMethods->xFileControl(id, op, pArg); in sqlite3OsFileControl()
26694 if( id->pMethods ) (void)id->pMethods->xFileControl(id, op, pArg); in sqlite3OsFileControlHint()
26698 int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize; in sqlite3OsSectorSize()
26702 if( NEVER(id->pMethods==0) ) return 0; in sqlite3OsDeviceCharacteristics()
26703 return id->pMethods->xDeviceCharacteristics(id); in sqlite3OsDeviceCharacteristics()
26707 return id->pMethods->xShmLock(id, offset, n, flags); in sqlite3OsShmLock()
26710 id->pMethods->xShmBarrier(id); in sqlite3OsShmBarrier()
26713 return id->pMethods->xShmUnmap(id, deleteFlag); in sqlite3OsShmUnmap()
26723 return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp); in sqlite3OsShmMap()
26731 return id->pMethods->xFetch(id, iOff, iAmt, pp); in sqlite3OsFetch()
26734 return id->pMethods->xUnfetch(id, iOff, p); in sqlite3OsUnfetch()
26737 /* No-op stubs to use when memory-mapped I/O is disabled */
26765 rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x1087f7f, pFlagsOut); in sqlite3OsOpen()
26766 assert( rc==SQLITE_OK || pFile->pMethods==0 ); in sqlite3OsOpen()
26772 return pVfs->xDelete!=0 ? pVfs->xDelete(pVfs, zPath, dirSync) : SQLITE_OK; in sqlite3OsDelete()
26781 return pVfs->xAccess(pVfs, zPath, flags, pResOut); in sqlite3OsAccess()
26791 return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut); in sqlite3OsFullPathname()
26796 assert( strlen(zPath)<=SQLITE_MAX_PATHLEN ); /* tag-20210611-1 */ in sqlite3OsDlOpen()
26797 return pVfs->xDlOpen(pVfs, zPath); in sqlite3OsDlOpen()
26800 pVfs->xDlError(pVfs, nByte, zBufOut); in sqlite3OsDlError()
26803 return pVfs->xDlSym(pVfs, pHdle, zSym); in sqlite3OsDlSym()
26806 pVfs->xDlClose(pVfs, pHandle); in sqlite3OsDlClose()
26816 return pVfs->xRandomness(pVfs, nByte, zBufOut); in sqlite3OsRandomness()
26821 return pVfs->xSleep(pVfs, nMicro); in sqlite3OsSleep()
26824 return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0; in sqlite3OsGetLastError()
26828 /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64() in sqlite3OsCurrentTimeInt64()
26834 if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ in sqlite3OsCurrentTimeInt64()
26835 rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut); in sqlite3OsCurrentTimeInt64()
26838 rc = pVfs->xCurrentTime(pVfs, &r); in sqlite3OsCurrentTimeInt64()
26853 pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile); in sqlite3OsOpenMalloc()
26878 ** ability to simulate a malloc failure, so that the handling of an
26911 for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){ in sqlite3_vfs_find()
26913 if( strcmp(zVfs, pVfs->zName)==0 ) break; in sqlite3_vfs_find()
26925 /* No-op */ in vfsUnlink()
26927 vfsList = pVfs->pNext; in vfsUnlink()
26930 while( p->pNext && p->pNext!=pVfs ){ in vfsUnlink()
26931 p = p->pNext; in vfsUnlink()
26933 if( p->pNext==pVfs ){ in vfsUnlink()
26934 p->pNext = pVfs->pNext; in vfsUnlink()
26958 pVfs->pNext = vfsList; in sqlite3_vfs_register()
26961 pVfs->pNext = vfsList->pNext; in sqlite3_vfs_register()
26962 vfsList->pNext = pVfs; in sqlite3_vfs_register()
27004 ** Most malloc failures are non-benign. After they occur, SQLite
27005 ** abandons the current operation and returns an error code (usually
27028 ** we have to locate the state vector at run-time. In the more common
27058 ** indicates that subsequent malloc failures are non-benign.
27089 ** This file contains a no-op memory allocation drivers for use when
27099 ** used when no other memory allocator is specified using compile-time
27105 ** No-op versions of all memory allocation routines
27118 ** Populate the low-level memory allocation function pointers in
27151 ** This file contains low-level memory allocation drivers for when
27152 ** SQLite will use the standard C-library malloc/realloc/free interface
27155 ** This file contains implementations of the low-level memory allocation
27163 ** C-preprocessor macro summary:
27169 ** If an equivalent interface exists by
27170 ** a different name, using a separate -D
27186 ** used when no other memory allocator is specified using compile-time
27206 (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
27211 ** Use standard C library malloc and free on non-Apple systems.
27228 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
27262 ** For this low-level routine, we are guaranteed that nByte>0 because
27296 ** For this low-level routine, we already know that pPrior!=0 since
27298 ** by higher-level routines.
27306 p--; in sqlite3MemFree()
27323 p--; in sqlite3MemSize()
27329 ** Like realloc(). Resize an allocation previously obtained from
27332 ** For this low-level interface, we know that pPrior!=0. Cases where
27333 ** pPrior==0 while have been intercepted by higher-level routine and
27335 ** cases where nByte<=0 will have been intercepted by higher-level
27351 assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */ in sqlite3MemRealloc()
27352 p--; in sqlite3MemRealloc()
27412 ** Populate the low-level memory allocation function pointers in
27445 ** This file contains low-level memory allocation drivers for when
27446 ** SQLite will use the standard C-library malloc/realloc/free interface
27451 ** This file contains implementations of the low-level memory allocation
27477 ** ------------------------------------------------------------------------
27479 ** ------------------------------------------------------------------------
27563 if( i>NCSIZE-1 ){ in adjustStats()
27564 i = NCSIZE - 1; in adjustStats()
27573 mem.nCurrent[i]--; in adjustStats()
27579 ** Given an allocation, find the MemBlockHdr for that allocation.
27591 p--; in sqlite3MemsysGetHeader()
27592 assert( p->iForeGuard==(int)FOREGUARD ); in sqlite3MemsysGetHeader()
27593 nReserve = ROUND8(p->iSize); in sqlite3MemsysGetHeader()
27598 ** to rounding up to an 8 byte boundary to ensure in sqlite3MemsysGetHeader()
27601 while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 ); in sqlite3MemsysGetHeader()
27614 return (int)pHdr->iSize; in sqlite3MemSize()
27647 ** Fill a buffer with pseudo-random bytes. This is used to preset
27656 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); in randomFill()
27661 nByte -= 4; in randomFill()
27663 while( nByte-- > 0 ){ in randomFill()
27664 x = (x>>1) ^ (-(int)(x&1) & 0xd0000001); in randomFill()
27692 pHdr->pNext = 0; in sqlite3MemMalloc()
27693 pHdr->pPrev = mem.pLast; in sqlite3MemMalloc()
27695 mem.pLast->pNext = pHdr; in sqlite3MemMalloc()
27700 pHdr->iForeGuard = FOREGUARD; in sqlite3MemMalloc()
27701 pHdr->eType = MEMTYPE_HEAP; in sqlite3MemMalloc()
27702 pHdr->nBacktraceSlots = mem.nBacktrace; in sqlite3MemMalloc()
27703 pHdr->nTitle = mem.nTitle; in sqlite3MemMalloc()
27706 pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1; in sqlite3MemMalloc()
27707 memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*)); in sqlite3MemMalloc()
27710 mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]); in sqlite3MemMalloc()
27713 pHdr->nBacktrace = 0; in sqlite3MemMalloc()
27718 pHdr->iSize = nByte; in sqlite3MemMalloc()
27723 memset(((char*)pInt)+nByte, 0x65, nReserve-nByte); in sqlite3MemMalloc()
27741 pBt -= pHdr->nBacktraceSlots; in sqlite3MemFree()
27743 if( pHdr->pPrev ){ in sqlite3MemFree()
27744 assert( pHdr->pPrev->pNext==pHdr ); in sqlite3MemFree()
27745 pHdr->pPrev->pNext = pHdr->pNext; in sqlite3MemFree()
27748 mem.pFirst = pHdr->pNext; in sqlite3MemFree()
27750 if( pHdr->pNext ){ in sqlite3MemFree()
27751 assert( pHdr->pNext->pPrev==pHdr ); in sqlite3MemFree()
27752 pHdr->pNext->pPrev = pHdr->pPrev; in sqlite3MemFree()
27755 mem.pLast = pHdr->pPrev; in sqlite3MemFree()
27758 z -= pHdr->nTitle; in sqlite3MemFree()
27759 adjustStats((int)pHdr->iSize, -1); in sqlite3MemFree()
27760 randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) + in sqlite3MemFree()
27761 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle); in sqlite3MemFree()
27767 ** Change the size of an existing memory allocation.
27779 assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */ in sqlite3MemRealloc()
27783 memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize)); in sqlite3MemRealloc()
27784 if( nByte>pOldHdr->iSize ){ in sqlite3MemRealloc()
27785 randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize); in sqlite3MemRealloc()
27793 ** Populate the low-level memory allocation function pointers in
27811 ** Set the "type" of an allocation.
27817 assert( pHdr->iForeGuard==FOREGUARD ); in sqlite3MemdebugSetType()
27818 pHdr->eType = eType; in sqlite3MemdebugSetType()
27826 ** This routine is designed for use within an assert() statement, to
27827 ** verify the type of an allocation. For example:
27836 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ in sqlite3MemdebugHasType()
27837 if( (pHdr->eType&eType)==0 ){ in sqlite3MemdebugHasType()
27848 ** This routine is designed for use within an assert() statement, to
27849 ** verify the type of an allocation. For example:
27858 assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */ in sqlite3MemdebugNoType()
27859 if( (pHdr->eType&eType)!=0 ){ in sqlite3MemdebugNoType()
27888 if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1; in sqlite3MemdebugSettitle()
27897 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ in sqlite3MemdebugSync()
27899 pBt -= pHdr->nBacktraceSlots; in sqlite3MemdebugSync()
27900 mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]); in sqlite3MemdebugSync()
27919 for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){ in sqlite3MemdebugDump()
27921 z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle; in sqlite3MemdebugDump()
27923 pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???"); in sqlite3MemdebugDump()
27924 if( pHdr->nBacktrace ){ in sqlite3MemdebugDump()
27927 pBt -= pHdr->nBacktraceSlots; in sqlite3MemdebugDump()
27928 backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out)); in sqlite3MemdebugDump()
27933 for(i=0; i<NCSIZE-1; i++){ in sqlite3MemdebugDump()
27939 if( mem.nAlloc[NCSIZE-1] ){ in sqlite3MemdebugDump()
27941 NCSIZE*8-8, mem.nAlloc[NCSIZE-1], in sqlite3MemdebugDump()
27942 mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]); in sqlite3MemdebugDump()
27994 ** mean that the library will use a memory-pool by default, just that
28030 ** the chunk. In this way, the first chunk has an index of 1.
28035 ** two fields form a double-linked list of chunks of related sizes.
28072 ** True if we are evaluating an out-of-memory callback.
28100 u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
28133 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 ); in memsys3Unlink()
28135 size = mem3.aPool[i-1].u.hdr.size4x/4; in memsys3Unlink()
28136 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); in memsys3Unlink()
28139 memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]); in memsys3Unlink()
28168 assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 ); in memsys3Link()
28169 size = mem3.aPool[i-1].u.hdr.size4x/4; in memsys3Link()
28170 assert( size==mem3.aPool[i+size-1].u.hdr.prevSize ); in memsys3Link()
28173 memsys3LinkIntoList(i, &mem3.aiSmall[size-2]); in memsys3Link()
28196 ** Called when we are unable to satisfy an allocation of nBytes.
28212 ** size parameters for check-out and return a pointer to the
28219 assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ); in memsys3Checkout()
28220 assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock ); in memsys3Checkout()
28221 x = mem3.aPool[i-1].u.hdr.size4x; in memsys3Checkout()
28222 mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2); in memsys3Checkout()
28223 mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock; in memsys3Checkout()
28224 mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2; in memsys3Checkout()
28236 if( nBlock>=mem3.szKeyBlk-1 ){ in memsys3FromKeyBlk()
28246 newi = mem3.iKeyBlk + mem3.szKeyBlk - nBlock; in memsys3FromKeyBlk()
28248 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = nBlock; in memsys3FromKeyBlk()
28249 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x |= 2; in memsys3FromKeyBlk()
28250 mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1; in memsys3FromKeyBlk()
28251 mem3.szKeyBlk -= nBlock; in memsys3FromKeyBlk()
28252 mem3.aPool[newi-1].u.hdr.prevSize = mem3.szKeyBlk; in memsys3FromKeyBlk()
28253 x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2; in memsys3FromKeyBlk()
28254 mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x; in memsys3FromKeyBlk()
28264 ** or same size hash. In other words, *pRoot is an entry in either
28284 size = mem3.aPool[i-1].u.hdr.size4x; in memsys3Merge()
28288 assert( i > mem3.aPool[i-1].u.hdr.prevSize ); in memsys3Merge()
28289 prev = i - mem3.aPool[i-1].u.hdr.prevSize; in memsys3Merge()
28294 size = i + size/4 - prev; in memsys3Merge()
28295 x = mem3.aPool[prev-1].u.hdr.size4x & 2; in memsys3Merge()
28296 mem3.aPool[prev-1].u.hdr.size4x = size*4 | x; in memsys3Merge()
28297 mem3.aPool[prev+size-1].u.hdr.prevSize = size; in memsys3Merge()
28332 ** Look for an entry of the correct size in either the small in memsys3MallocUnsafe()
28337 i = mem3.aiSmall[nBlock-2]; in memsys3MallocUnsafe()
28339 memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]); in memsys3MallocUnsafe()
28345 if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){ in memsys3MallocUnsafe()
28378 for(i=0; i<MX_SMALL-1; i++){ in memsys3MallocUnsafe()
28394 ** Free an outstanding memory allocation.
28405 i = p - mem3.aPool; in memsys3FreeUnsafe()
28406 assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 ); in memsys3FreeUnsafe()
28407 size = mem3.aPool[i-1].u.hdr.size4x/4; in memsys3FreeUnsafe()
28409 mem3.aPool[i-1].u.hdr.size4x &= ~1; in memsys3FreeUnsafe()
28410 mem3.aPool[i+size-1].u.hdr.prevSize = size; in memsys3FreeUnsafe()
28411 mem3.aPool[i+size-1].u.hdr.size4x &= ~2; in memsys3FreeUnsafe()
28416 while( (mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x&2)==0 ){ in memsys3FreeUnsafe()
28417 size = mem3.aPool[mem3.iKeyBlk-1].u.hdr.prevSize; in memsys3FreeUnsafe()
28418 mem3.iKeyBlk -= size; in memsys3FreeUnsafe()
28421 x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2; in memsys3FreeUnsafe()
28422 mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x; in memsys3FreeUnsafe()
28423 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk; in memsys3FreeUnsafe()
28425 x = mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x & 2; in memsys3FreeUnsafe()
28426 while( (mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x&1)==0 ){ in memsys3FreeUnsafe()
28428 mem3.szKeyBlk += mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.size4x/4; in memsys3FreeUnsafe()
28429 mem3.aPool[mem3.iKeyBlk-1].u.hdr.size4x = mem3.szKeyBlk*4 | x; in memsys3FreeUnsafe()
28430 mem3.aPool[mem3.iKeyBlk+mem3.szKeyBlk-1].u.hdr.prevSize = mem3.szKeyBlk; in memsys3FreeUnsafe()
28436 ** Return the size of an outstanding allocation, in bytes. The
28437 ** size returned omits the 8-byte header overhead. This only
28444 assert( (pBlock[-1].u.hdr.size4x&1)!=0 ); in memsys3Size()
28445 return (pBlock[-1].u.hdr.size4x&~3)*2 - 4; in memsys3Size()
28455 return ((n+11)&~7) - 4; in memsys3Roundup()
28482 ** Change the size of an existing memory allocation
28495 if( nBytes<=nOld && nBytes>=nOld-128 ){ in memsys3Realloc()
28524 mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2; in memsys3Init()
28570 size = mem3.aPool[i-1].u.hdr.size4x; in sqlite3Memsys3Dump()
28576 if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){ in sqlite3Memsys3Dump()
28581 if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){ in sqlite3Memsys3Dump()
28587 fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8); in sqlite3Memsys3Dump()
28589 fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8, in sqlite3Memsys3Dump()
28593 for(i=0; i<MX_SMALL-1; i++){ in sqlite3Memsys3Dump()
28598 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); in sqlite3Memsys3Dump()
28607 (mem3.aPool[j-1].u.hdr.size4x/4)*8-8); in sqlite3Memsys3Dump()
28612 fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szKeyBlk*8); in sqlite3Memsys3Dump()
28613 fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnKeyBlk*8); in sqlite3Memsys3Dump()
28629 ** Populate the low-level memory allocation function pointers in
28690 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
28699 ** N >= M*(1 + log2(n)/2) - n + 1
28702 ** that an application can, at any time, verify this constraint.
28713 ** A minimum allocation is an instance of the following structure.
28714 ** Larger allocations are an array of these structures where the
28728 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
28763 u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
28793 ** Assuming mem5.zPool is divided up into an array of Mem5Link
28794 ** structures, return a pointer to the idx-th such link.
28808 next = MEM5LINK(i)->next; in memsys5Unlink()
28809 prev = MEM5LINK(i)->prev; in memsys5Unlink()
28813 MEM5LINK(prev)->next = next; in memsys5Unlink()
28816 MEM5LINK(next)->prev = prev; in memsys5Unlink()
28831 x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize]; in memsys5Link()
28832 MEM5LINK(i)->prev = -1; in memsys5Link()
28835 MEM5LINK(x)->prev = i; in memsys5Link()
28851 ** Return the size of an outstanding allocation, in bytes.
28857 i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom); in memsys5Size()
28912 iBin--; in memsys5MallocUnsafe()
28923 mem5.totalExcess += iFullSz - nByte; in memsys5MallocUnsafe()
28941 ** Free an outstanding memory allocation.
28950 iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom); in memsys5FreeUnsafe()
28952 /* Check that the pointer pOld points to a valid, non-free block. */ in memsys5FreeUnsafe()
28954 assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 ); in memsys5FreeUnsafe()
28959 assert( iBlock+size-1<(u32)mem5.nBlock ); in memsys5FreeUnsafe()
28962 mem5.aCtrl[iBlock+size-1] |= CTRL_FREE; in memsys5FreeUnsafe()
28967 mem5.currentCount--; in memsys5FreeUnsafe()
28968 mem5.currentOut -= size*mem5.szAtom; in memsys5FreeUnsafe()
28977 iBuddy = iBlock - size; in memsys5FreeUnsafe()
29033 ** Change the size of an existing memory allocation.
29039 ** memsys5Round(). Hence nBytes is always a non-negative power
29040 ** of two. If nBytes==0 that means that an oversize allocation
29041 ** (an allocation larger than 0x40000000) was requested and this
29048 assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */ in memsys5Realloc()
29071 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
29093 ** Examples: memsys5Log(1) -> 0
29094 ** memsys5Log(2) -> 1
29095 ** memsys5Log(4) -> 2
29096 ** memsys5Log(5) -> 3
29097 ** memsys5Log(8) -> 3
29098 ** memsys5Log(9) -> 4
29102 for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++); in memsys5Log()
29117 int iOffset; /* An offset into mem5.aCtrl[] */ in memsys5Init()
29127 assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 ); in memsys5Init()
29145 mem5.aiFreelist[ii] = -1; in memsys5Init()
29149 for(ii=LOGMAX; ii>=0; ii--){ in memsys5Init()
29199 for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){} in sqlite3Memsys5Dump()
29262 ** and uninitialized so that we can assert() if there is an attempt to
29290 ** to the type of mutex requested - SQLITE_MUTEX_RECURSIVE, SQLITE_MUTEX_FAST
29301 #define SQLITE_MUTEX_WARNONCONTENTION (-1)
29311 return pGlobalMutexMethods->xMutexHeld(((CheckMutex*)p)->mutex); in checkMutexHeld()
29314 return pGlobalMutexMethods->xMutexNotheld(((CheckMutex*)p)->mutex); in checkMutexNotheld()
29345 p->iType = iType; in checkMutexAlloc()
29348 if( iType-2>=ArraySize(staticMutexes) ){ in checkMutexAlloc()
29353 p = &staticMutexes[iType-2]; in checkMutexAlloc()
29356 if( p->mutex==0 ){ in checkMutexAlloc()
29357 p->mutex = pGlobalMutexMethods->xMutexAlloc(iType); in checkMutexAlloc()
29358 if( p->mutex==0 ){ in checkMutexAlloc()
29378 if( ((CheckMutex*)p)->iType<2 ) in checkMutexFree()
29382 pGlobalMutexMethods->xMutexFree(pCheck->mutex); in checkMutexFree()
29397 if( pCheck->iType==SQLITE_MUTEX_WARNONCONTENTION ){ in checkMutexEnter()
29398 if( SQLITE_OK==pGlobalMutexMethods->xMutexTry(pCheck->mutex) ){ in checkMutexEnter()
29402 "illegal multi-threaded access to database connection" in checkMutexEnter()
29405 pGlobalMutexMethods->xMutexEnter(pCheck->mutex); in checkMutexEnter()
29413 return pGlobalMutexMethods->xMutexTry(pCheck->mutex); in checkMutexTry()
29421 pGlobalMutexMethods->xMutexLeave(pCheck->mutex); in checkMutexLeave()
29451 assert( pCheck->iType==SQLITE_MUTEX_RECURSIVE ); in sqlite3MutexWarnOnContention()
29452 pCheck->iType = SQLITE_MUTEX_WARNONCONTENTION; in sqlite3MutexWarnOnContention()
29480 pTo->xMutexInit = pFrom->xMutexInit; in sqlite3MutexInit()
29481 pTo->xMutexEnd = pFrom->xMutexEnd; in sqlite3MutexInit()
29482 pTo->xMutexFree = pFrom->xMutexFree; in sqlite3MutexInit()
29483 pTo->xMutexEnter = pFrom->xMutexEnter; in sqlite3MutexInit()
29484 pTo->xMutexTry = pFrom->xMutexTry; in sqlite3MutexInit()
29485 pTo->xMutexLeave = pFrom->xMutexLeave; in sqlite3MutexInit()
29486 pTo->xMutexHeld = pFrom->xMutexHeld; in sqlite3MutexInit()
29487 pTo->xMutexNotheld = pFrom->xMutexNotheld; in sqlite3MutexInit()
29489 pTo->xMutexAlloc = pFrom->xMutexAlloc; in sqlite3MutexInit()
29577 ** is not currently entered. If a NULL pointer is passed as an argument
29578 ** this function is a no-op.
29592 ** Because these routines raise false-positive alerts in TSAN, disable
29635 ** here are place-holders. Applications can substitute working
29636 ** mutex routines at start-time using the
29709 return p==0 || p->cnt>0; in debugMutexHeld()
29713 return p==0 || p->cnt==0; in debugMutexNotheld()
29728 static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1]; in debugMutexAlloc()
29735 pNew->id = id; in debugMutexAlloc()
29736 pNew->cnt = 0; in debugMutexAlloc()
29742 if( id-2<0 || id-2>=ArraySize(aStatic) ){ in debugMutexAlloc()
29747 pNew = &aStatic[id-2]; in debugMutexAlloc()
29748 pNew->id = id; in debugMutexAlloc()
29760 assert( p->cnt==0 ); in debugMutexFree()
29761 if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){ in debugMutexFree()
29777 ** mutex must be exited an equal number of times before another thread
29783 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); in debugMutexEnter()
29784 p->cnt++; in debugMutexEnter()
29788 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); in debugMutexTry()
29789 p->cnt++; in debugMutexTry()
29802 p->cnt--; in debugMutexLeave()
29803 assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) ); in debugMutexLeave()
29825 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
29826 ** is used regardless of the run-time threadsafety setting.
29866 ** home-grown mutexes. Encapsulate these conditions into a single #define.
29875 ** Each recursive mutex is an instance of the following structure.
29902 ** not an atomic operation, then these routines might delivery
29909 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
29915 return (p->nRef!=0 && pthread_equal(p->owner, pthread_self())); in pthreadMutexHeld()
29918 return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0; in pthreadMutexNotheld()
29945 ** will unwind its stack and return an error. The argument
29971 ** cases where it really needs one. If a faster non-recursive mutex
30012 pthread_mutex_init(&p->mutex, 0); in pthreadMutexAlloc()
30018 pthread_mutex_init(&p->mutex, &recursiveAttr); in pthreadMutexAlloc()
30022 p->id = SQLITE_MUTEX_RECURSIVE; in pthreadMutexAlloc()
30030 pthread_mutex_init(&p->mutex, 0); in pthreadMutexAlloc()
30032 p->id = SQLITE_MUTEX_FAST; in pthreadMutexAlloc()
30039 if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){ in pthreadMutexAlloc()
30044 p = &staticMutexes[iType-2]; in pthreadMutexAlloc()
30049 assert( p==0 || p->id==iType ); in pthreadMutexAlloc()
30061 assert( p->nRef==0 ); in pthreadMutexFree()
30063 if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ) in pthreadMutexFree()
30066 pthread_mutex_destroy(&p->mutex); in pthreadMutexFree()
30083 ** mutex must be exited an equal number of times before another thread
30088 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); in pthreadMutexEnter()
30093 ** is atomic - that it cannot be deceived into thinking self in pthreadMutexEnter()
30094 ** and p->owner are equal if p->owner changes between two values in pthreadMutexEnter()
30096 ** This implementation also assumes a coherent cache - that in pthreadMutexEnter()
30103 if( p->nRef>0 && pthread_equal(p->owner, self) ){ in pthreadMutexEnter()
30104 p->nRef++; in pthreadMutexEnter()
30106 pthread_mutex_lock(&p->mutex); in pthreadMutexEnter()
30107 assert( p->nRef==0 ); in pthreadMutexEnter()
30108 p->owner = self; in pthreadMutexEnter()
30109 p->nRef = 1; in pthreadMutexEnter()
30113 /* Use the built-in recursive mutexes if they are available. in pthreadMutexEnter()
30115 pthread_mutex_lock(&p->mutex); in pthreadMutexEnter()
30117 assert( p->nRef>0 || p->owner==0 ); in pthreadMutexEnter()
30118 p->owner = pthread_self(); in pthreadMutexEnter()
30119 p->nRef++; in pthreadMutexEnter()
30124 if( p->trace ){ in pthreadMutexEnter()
30125 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); in pthreadMutexEnter()
30131 assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) ); in pthreadMutexTry()
30136 ** is atomic - that it cannot be deceived into thinking self in pthreadMutexTry()
30137 ** and p->owner are equal if p->owner changes between two values in pthreadMutexTry()
30139 ** This implementation also assumes a coherent cache - that in pthreadMutexTry()
30146 if( p->nRef>0 && pthread_equal(p->owner, self) ){ in pthreadMutexTry()
30147 p->nRef++; in pthreadMutexTry()
30149 }else if( pthread_mutex_trylock(&p->mutex)==0 ){ in pthreadMutexTry()
30150 assert( p->nRef==0 ); in pthreadMutexTry()
30151 p->owner = self; in pthreadMutexTry()
30152 p->nRef = 1; in pthreadMutexTry()
30159 /* Use the built-in recursive mutexes if they are available. in pthreadMutexTry()
30161 if( pthread_mutex_trylock(&p->mutex)==0 ){ in pthreadMutexTry()
30163 p->owner = pthread_self(); in pthreadMutexTry()
30164 p->nRef++; in pthreadMutexTry()
30173 if( rc==SQLITE_OK && p->trace ){ in pthreadMutexTry()
30174 printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); in pthreadMutexTry()
30189 p->nRef--; in pthreadMutexLeave()
30190 if( p->nRef==0 ) p->owner = 0; in pthreadMutexLeave()
30192 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); in pthreadMutexLeave()
30195 if( p->nRef==0 ){ in pthreadMutexLeave()
30196 pthread_mutex_unlock(&p->mutex); in pthreadMutexLeave()
30199 pthread_mutex_unlock(&p->mutex); in pthreadMutexLeave()
30203 if( p->trace ){ in pthreadMutexLeave()
30204 printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef); in pthreadMutexLeave()
30311 ** Determine if we are dealing with Windows CE - which has a much reduced
30339 ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
30362 ** Each recursive mutex is an instance of the following structure.
30394 return p->nRef!=0 && p->owner==GetCurrentThreadId(); in winMutexHeld()
30398 return p->nRef==0 || p->owner!=tid; in winMutexNotheld2()
30443 static int winMutex_isNt = -1; /* <0 means "need to query" */
30495 ** will unwind its stack and return an error. The argument
30521 ** cases where it really needs one. If a faster non-recursive mutex
30547 p->id = iType; in winMutexAlloc()
30550 p->trace = 1; in winMutexAlloc()
30554 InitializeCriticalSectionEx(&p->mutex, 0, 0); in winMutexAlloc()
30556 InitializeCriticalSection(&p->mutex); in winMutexAlloc()
30563 if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){ in winMutexAlloc()
30568 p = &winMutex_staticMutexes[iType-2]; in winMutexAlloc()
30571 InterlockedCompareExchange(&p->trace, 1, 0); in winMutexAlloc()
30577 assert( p==0 || p->id==iType ); in winMutexAlloc()
30589 assert( p->nRef==0 && p->owner==0 ); in winMutexFree()
30590 if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){ in winMutexFree()
30591 DeleteCriticalSection(&p->mutex); in winMutexFree()
30607 ** mutex must be exited an equal number of times before another thread
30617 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); in winMutexEnter()
30622 EnterCriticalSection(&p->mutex); in winMutexEnter()
30624 assert( p->nRef>0 || p->owner==0 ); in winMutexEnter()
30625 p->owner = tid; in winMutexEnter()
30626 p->nRef++; in winMutexEnter()
30627 if( p->trace ){ in winMutexEnter()
30628 OSTRACE(("ENTER-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n", in winMutexEnter()
30629 tid, p->id, p, p->trace, p->nRef)); in winMutexEnter()
30640 assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) ); in winMutexTry()
30643 ** is used it is merely an optimization. So it is OK for it to always in winMutexTry()
30654 assert( winMutex_isNt>=-1 && winMutex_isNt<=1 ); in winMutexTry()
30659 if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){ in winMutexTry()
30661 p->owner = tid; in winMutexTry()
30662 p->nRef++; in winMutexTry()
30670 if( p->trace ){ in winMutexTry()
30671 OSTRACE(("TRY-MUTEX tid=%lu, mutex(%d)=%p (%d), owner=%lu, nRef=%d, rc=%s\n", in winMutexTry()
30672 tid, p->id, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc))); in winMutexTry()
30690 assert( p->nRef>0 ); in winMutexLeave()
30691 assert( p->owner==tid ); in winMutexLeave()
30692 p->nRef--; in winMutexLeave()
30693 if( p->nRef==0 ) p->owner = 0; in winMutexLeave()
30694 assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE ); in winMutexLeave()
30697 LeaveCriticalSection(&p->mutex); in winMutexLeave()
30699 if( p->trace ){ in winMutexLeave()
30700 OSTRACE(("LEAVE-MUTEX tid=%lu, mutex(%d)=%p (%d), nRef=%d\n", in winMutexLeave()
30701 tid, p->id, p, p->trace, p->nRef)); in winMutexLeave()
30748 ** Attempt to release up to n bytes of non-essential memory currently
30749 ** held by SQLite. An example of non-essential memory is memory used to
30756 /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine in sqlite3_release_memory()
30757 ** is a no-op returning zero if SQLite is not compiled with in sqlite3_release_memory()
30797 ** Deprecated external interface. It used to set an alarm callback
30799 ** no-op.
30814 ** Set the soft heap-size limit for the library. An argument of
30815 ** zero disables the limit. A negative argument is a no-op used to
30830 if( rc ) return -1; in sqlite3_soft_heap_limit64()
30845 excess = sqlite3_memory_used() - n; in sqlite3_soft_heap_limit64()
30855 ** Set the hard heap-size limit for the library. An argument of zero
30856 ** disables the hard heap limit. A negative argument is a no-op used
30870 if( rc ) return -1; in sqlite3_hard_heap_limit64()
30905 ** Return true if the heap is currently under memory pressure - in other
30955 ** This routine is called whenever an out-of-memory condition is seen,
30957 ** code debuggers when working on out-of-memory conditions, for example
30968 # define test_oom_breakpoint(X) /* No-op for production builds */
30981 /* In Firefox (circa 2017-02-08), xRoundup() is remapped to an internal in mallocWithAlarm()
30991 if( nUsed >= mem0.alarmThreshold - nFull ){ in mallocWithAlarm()
30996 if( nUsed >= mem0.hardLimit - nFull ){ in mallocWithAlarm()
31028 ** This provides a 256-byte safety margin for defense against 32-bit
31031 ** further for an even larger safety margin. 0x3fffffff or 0x0fffffff
31057 assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */ in sqlite3Malloc()
31084 return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pTrueEnd); in isLookaside()
31100 return p<db->lookaside.pMiddle ? db->lookaside.szTrue : LOOKASIDE_SMALL; in lookasideMallocSize()
31102 return db->lookaside.szTrue; in lookasideMallocSize()
31117 if( ((uptr)p)<(uptr)(db->lookaside.pTrueEnd) ){ in sqlite3DbMallocSize()
31119 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){ in sqlite3DbMallocSize()
31120 assert( sqlite3_mutex_held(db->mutex) ); in sqlite3DbMallocSize()
31124 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){ in sqlite3DbMallocSize()
31125 assert( sqlite3_mutex_held(db->mutex) ); in sqlite3DbMallocSize()
31126 return db->lookaside.szTrue; in sqlite3DbMallocSize()
31142 if( p==0 ) return; /* IMP: R-49053-54554 */ in sqlite3_free()
31158 ** *db->pnBytesFreed.
31161 *db->pnBytesFreed += sqlite3DbMallocSize(db,p); in measureAllocationSize()
31166 ** connection. Calling sqlite3DbFree(D,X) for X==0 is a harmless no-op.
31167 ** The sqlite3DbFreeNN(D,X) version requires that X be non-NULL.
31170 assert( db==0 || sqlite3_mutex_held(db->mutex) ); in sqlite3DbFreeNN()
31173 if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){ in sqlite3DbFreeNN()
31175 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){ in sqlite3DbFreeNN()
31177 assert( db->pnBytesFreed==0 ); in sqlite3DbFreeNN()
31181 pBuf->pNext = db->lookaside.pSmallFree; in sqlite3DbFreeNN()
31182 db->lookaside.pSmallFree = pBuf; in sqlite3DbFreeNN()
31186 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){ in sqlite3DbFreeNN()
31188 assert( db->pnBytesFreed==0 ); in sqlite3DbFreeNN()
31190 memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */ in sqlite3DbFreeNN()
31192 pBuf->pNext = db->lookaside.pFree; in sqlite3DbFreeNN()
31193 db->lookaside.pFree = pBuf; in sqlite3DbFreeNN()
31197 if( db->pnBytesFreed ){ in sqlite3DbFreeNN()
31210 assert( sqlite3_mutex_held(db->mutex) ); in sqlite3DbNNFreeNN()
31212 if( ((uptr)p)<(uptr)(db->lookaside.pEnd) ){ in sqlite3DbNNFreeNN()
31214 if( ((uptr)p)>=(uptr)(db->lookaside.pMiddle) ){ in sqlite3DbNNFreeNN()
31216 assert( db->pnBytesFreed==0 ); in sqlite3DbNNFreeNN()
31220 pBuf->pNext = db->lookaside.pSmallFree; in sqlite3DbNNFreeNN()
31221 db->lookaside.pSmallFree = pBuf; in sqlite3DbNNFreeNN()
31225 if( ((uptr)p)>=(uptr)(db->lookaside.pStart) ){ in sqlite3DbNNFreeNN()
31227 assert( db->pnBytesFreed==0 ); in sqlite3DbNNFreeNN()
31229 memset(p, 0xaa, db->lookaside.szTrue); /* Trash freed content */ in sqlite3DbNNFreeNN()
31231 pBuf->pNext = db->lookaside.pFree; in sqlite3DbNNFreeNN()
31232 db->lookaside.pFree = pBuf; in sqlite3DbNNFreeNN()
31236 if( db->pnBytesFreed ){ in sqlite3DbNNFreeNN()
31246 assert( db==0 || sqlite3_mutex_held(db->mutex) ); in sqlite3DbFree()
31251 ** Change the size of an existing memory allocation
31259 return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */ in sqlite3Realloc()
31262 sqlite3_free(pOld); /* IMP: R-26507-47431 */ in sqlite3Realloc()
31270 /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second in sqlite3Realloc()
31280 nDiff = nNew - nOld; in sqlite3Realloc()
31282 mem0.alarmThreshold-nDiff ){ in sqlite3Realloc()
31284 if( mem0.hardLimit>0 && nUsed >= mem0.hardLimit - nDiff ){ in sqlite3Realloc()
31299 sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld); in sqlite3Realloc()
31305 assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */ in sqlite3Realloc()
31317 if( n<0 ) n = 0; /* IMP: R-26507-47431 */ in sqlite3_realloc()
31361 (db->lookaside.bDisable==0) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP); in dbMallocRawFinish()
31370 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
31374 ** This is an important assumption. There are many places in the
31398 assert( sqlite3_mutex_held(db->mutex) ); in sqlite3DbMallocRawNN()
31399 assert( db->pnBytesFreed==0 ); in sqlite3DbMallocRawNN()
31400 if( n>db->lookaside.sz ){ in sqlite3DbMallocRawNN()
31401 if( !db->lookaside.bDisable ){ in sqlite3DbMallocRawNN()
31402 db->lookaside.anStat[1]++; in sqlite3DbMallocRawNN()
31403 }else if( db->mallocFailed ){ in sqlite3DbMallocRawNN()
31410 if( (pBuf = db->lookaside.pSmallFree)!=0 ){ in sqlite3DbMallocRawNN()
31411 db->lookaside.pSmallFree = pBuf->pNext; in sqlite3DbMallocRawNN()
31412 db->lookaside.anStat[0]++; in sqlite3DbMallocRawNN()
31414 }else if( (pBuf = db->lookaside.pSmallInit)!=0 ){ in sqlite3DbMallocRawNN()
31415 db->lookaside.pSmallInit = pBuf->pNext; in sqlite3DbMallocRawNN()
31416 db->lookaside.anStat[0]++; in sqlite3DbMallocRawNN()
31421 if( (pBuf = db->lookaside.pFree)!=0 ){ in sqlite3DbMallocRawNN()
31422 db->lookaside.pFree = pBuf->pNext; in sqlite3DbMallocRawNN()
31423 db->lookaside.anStat[0]++; in sqlite3DbMallocRawNN()
31425 }else if( (pBuf = db->lookaside.pInit)!=0 ){ in sqlite3DbMallocRawNN()
31426 db->lookaside.pInit = pBuf->pNext; in sqlite3DbMallocRawNN()
31427 db->lookaside.anStat[0]++; in sqlite3DbMallocRawNN()
31430 db->lookaside.anStat[2]++; in sqlite3DbMallocRawNN()
31434 assert( sqlite3_mutex_held(db->mutex) ); in sqlite3DbMallocRawNN()
31435 assert( db->pnBytesFreed==0 ); in sqlite3DbMallocRawNN()
31436 if( db->mallocFailed ){ in sqlite3DbMallocRawNN()
31453 assert( sqlite3_mutex_held(db->mutex) ); in sqlite3DbRealloc()
31454 if( ((uptr)p)<(uptr)db->lookaside.pEnd ){ in sqlite3DbRealloc()
31456 if( ((uptr)p)>=(uptr)db->lookaside.pMiddle ){ in sqlite3DbRealloc()
31460 if( ((uptr)p)>=(uptr)db->lookaside.pStart ){ in sqlite3DbRealloc()
31461 if( n<=db->lookaside.szTrue ) return p; in sqlite3DbRealloc()
31470 if( db->mallocFailed==0 ){ in dbReallocFinish()
31486 (db->lookaside.bDisable==0 ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP)); in dbReallocFinish()
31547 ** at least one non-space character */ in sqlite3DbSpanDup()
31551 n = (int)(zEnd - zStart); in sqlite3DbSpanDup()
31552 while( sqlite3Isspace(zStart[n-1]) ) n--; in sqlite3DbSpanDup()
31566 ** Call this routine to record the fact that an OOM (out-of-memory) error
31567 ** has happened. This routine will set db->mallocFailed, and also
31579 if( db->mallocFailed==0 && db->bBenignMalloc==0 ){ in sqlite3OomFault()
31580 db->mallocFailed = 1; in sqlite3OomFault()
31581 if( db->nVdbeExec>0 ){ in sqlite3OomFault()
31582 AtomicStore(&db->u1.isInterrupted, 1); in sqlite3OomFault()
31585 if( db->pParse ){ in sqlite3OomFault()
31587 sqlite3ErrorMsg(db->pParse, "out of memory"); in sqlite3OomFault()
31588 db->pParse->rc = SQLITE_NOMEM_BKPT; in sqlite3OomFault()
31589 for(pParse=db->pParse->pOuterParse; pParse; pParse = pParse->pOuterParse){ in sqlite3OomFault()
31590 pParse->nErr++; in sqlite3OomFault()
31591 pParse->rc = SQLITE_NOMEM; in sqlite3OomFault()
31600 ** db->mallocFailed flag as necessary.
31606 if( db->mallocFailed && db->nVdbeExec==0 ){ in sqlite3OomClear()
31607 db->mallocFailed = 0; in sqlite3OomClear()
31608 AtomicStore(&db->u1.isInterrupted, 0); in sqlite3OomClear()
31609 assert( db->lookaside.bDisable>0 ); in sqlite3OomClear()
31615 ** Take actions at the end of an API call to deal with error codes.
31618 if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){ in apiHandleError()
31623 return rc & db->errMask; in apiHandleError()
31635 ** If an OOM as occurred, then the connection error-code (the value
31640 ** Otherwise the read (and possible write) of db->mallocFailed in sqlite3ApiExit()
31644 assert( sqlite3_mutex_held(db->mutex) ); in sqlite3ApiExit()
31645 if( db->mallocFailed || rc ){ in sqlite3ApiExit()
31659 ** This file contains code for a set of "printf"-like routines. These
31670 #define etRADIX 0 /* non-decimal integer types. %x %o */
31686 #define etESCAPE_w 14 /* %w -> Strings with '\"' doubled */
31687 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
31694 ** An "etByte" is an 8-bit unsigned value.
31700 ** by an instance of the following structure
31723 static const char aPrefix[] = "-x0\000X0";
31761 ** Set the StrAccum object to an error mode.
31765 p->accError = eError; in sqlite3StrAccumSetError()
31766 if( p->mxAlloc ) sqlite3_str_reset(p); in sqlite3StrAccumSetError()
31767 if( eError==SQLITE_TOOBIG ) sqlite3ErrorToParser(p->db, eError); in sqlite3StrAccumSetError()
31774 if( p->nArg<=p->nUsed ) return 0; in getIntArg()
31775 return sqlite3_value_int64(p->apArg[p->nUsed++]); in getIntArg()
31778 if( p->nArg<=p->nUsed ) return 0.0; in getDoubleArg()
31779 return sqlite3_value_double(p->apArg[p->nUsed++]); in getDoubleArg()
31782 if( p->nArg<=p->nUsed ) return 0; in getTextArg()
31783 return (char*)sqlite3_value_text(p->apArg[p->nUsed++]); in getTextArg()
31790 ** of the output buffer in pAccum, then cause an SQLITE_TOOBIG error.
31797 if( pAccum->accError ) return 0; in printfTempBuf()
31798 if( n>pAccum->nAlloc && n>pAccum->mxAlloc ){ in printfTempBuf()
31802 z = sqlite3DbMallocRaw(pAccum->db, n); in printfTempBuf()
31819 ** Hard limit on the precision of floating-point conversions.
31839 etByte flag_leftjustify; /* True if "-" flag is present */ in sqlite3_str_vappendf()
31849 char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */ in sqlite3_str_vappendf()
31863 /* pAccum never starts out with an empty buffer that was obtained from in sqlite3_str_vappendf()
31866 assert( pAccum->nChar>0 || (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 ); in sqlite3_str_vappendf()
31869 if( (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC)!=0 ){ in sqlite3_str_vappendf()
31883 sqlite3_str_append(pAccum, bufpt, (int)(fmt - bufpt)); in sqlite3_str_vappendf()
31896 precision = -1; in sqlite3_str_vappendf()
31899 case '-': flag_leftjustify = 1; break; in sqlite3_str_vappendf()
31919 unsigned wx = c - '0'; in sqlite3_str_vappendf()
31921 wx = wx*10 + c - '0'; in sqlite3_str_vappendf()
31933 fmt--; in sqlite3_str_vappendf()
31945 width = width >= -2147483647 ? -width : 0; in sqlite3_str_vappendf()
31967 precision = precision >= -2147483647 ? -precision : -1; in sqlite3_str_vappendf()
31973 px = px*10 + c - '0'; in sqlite3_str_vappendf()
31985 --fmt; in sqlite3_str_vappendf()
32000 xtype = infop->type; in sqlite3_str_vappendf()
32011 ** flag_leftjustify TRUE if a '-' is present or if the in sqlite3_str_vappendf()
32016 ** always non-negative. Zero is the default. in sqlite3_str_vappendf()
32018 ** is -1. in sqlite3_str_vappendf()
32023 assert( precision>=(-1) ); in sqlite3_str_vappendf()
32034 if( infop->flags & FLAG_SIGNED ){ in sqlite3_str_vappendf()
32049 testcase( v==(-1) ); in sqlite3_str_vappendf()
32052 prefix = '-'; in sqlite3_str_vappendf()
32072 if( flag_zeropad && precision<width-(prefix!=0) ){ in sqlite3_str_vappendf()
32073 precision = width-(prefix!=0); in sqlite3_str_vappendf()
32075 if( precision<etBUFSIZE-10-etBUFSIZE/3 ){ in sqlite3_str_vappendf()
32086 bufpt = &zOut[nOut-1]; in sqlite3_str_vappendf()
32093 *(--bufpt) = zOrd[x*2+1]; in sqlite3_str_vappendf()
32094 *(--bufpt) = zOrd[x*2]; in sqlite3_str_vappendf()
32097 const char *cset = &aDigits[infop->charset]; in sqlite3_str_vappendf()
32098 u8 base = infop->base; in sqlite3_str_vappendf()
32100 *(--bufpt) = cset[longvalue%base]; in sqlite3_str_vappendf()
32104 length = (int)(&zOut[nOut-1]-bufpt); in sqlite3_str_vappendf()
32106 *(--bufpt) = '0'; /* Zero pad */ in sqlite3_str_vappendf()
32110 int nn = (length - 1)/3; /* Number of "," to insert */ in sqlite3_str_vappendf()
32111 int ix = (length - 1)%3 + 1; in sqlite3_str_vappendf()
32112 bufpt -= nn; in sqlite3_str_vappendf()
32115 ix--; in sqlite3_str_vappendf()
32118 nn--; in sqlite3_str_vappendf()
32123 if( prefix ) *(--bufpt) = prefix; /* Add sign */ in sqlite3_str_vappendf()
32124 if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */ in sqlite3_str_vappendf()
32127 pre = &aPrefix[infop->prefix]; in sqlite3_str_vappendf()
32128 for(; (x=(*pre))!=0; pre++) *(--bufpt) = x; in sqlite3_str_vappendf()
32130 length = (int)(&zOut[nOut-1]-bufpt); in sqlite3_str_vappendf()
32151 iRound = -precision; in sqlite3_str_vappendf()
32169 memcpy(buf, "-Inf", 5); in sqlite3_str_vappendf()
32171 if( s.sign=='-' ){ in sqlite3_str_vappendf()
32172 /* no-op */ in sqlite3_str_vappendf()
32182 if( s.sign=='-' ){ in sqlite3_str_vappendf()
32183 prefix = '-'; in sqlite3_str_vappendf()
32188 exp = s.iDP-1; in sqlite3_str_vappendf()
32196 precision--; in sqlite3_str_vappendf()
32198 if( exp<-4 || exp>precision ){ in sqlite3_str_vappendf()
32201 precision = precision - exp; in sqlite3_str_vappendf()
32210 e2 = s.iDP - 1; in sqlite3_str_vappendf()
32233 for(; e2>=0; e2--){ in sqlite3_str_vappendf()
32244 for(e2++; e2<0 && precision>0; precision--, e2++){ in sqlite3_str_vappendf()
32248 while( (precision--)>0 ){ in sqlite3_str_vappendf()
32253 while( bufpt[-1]=='0' ) *(--bufpt) = 0; in sqlite3_str_vappendf()
32255 if( bufpt[-1]=='.' ){ in sqlite3_str_vappendf()
32259 *(--bufpt) = 0; in sqlite3_str_vappendf()
32265 exp = s.iDP - 1; in sqlite3_str_vappendf()
32266 *(bufpt++) = aDigits[infop->charset]; in sqlite3_str_vappendf()
32268 *(bufpt++) = '-'; exp = -exp; in sqlite3_str_vappendf()
32284 length = (int)(bufpt-zOut); in sqlite3_str_vappendf()
32291 int nPad = width - length; in sqlite3_str_vappendf()
32292 for(i=width; i>=nPad; i--){ in sqlite3_str_vappendf()
32293 bufpt[i] = bufpt[i-nPad]; in sqlite3_str_vappendf()
32296 while( nPad-- ) bufpt[i++] = '0'; in sqlite3_str_vappendf()
32303 *(va_arg(ap,int*)) = pAccum->nChar; in sqlite3_str_vappendf()
32332 width -= precision-1; in sqlite3_str_vappendf()
32334 sqlite3_str_appendchar(pAccum, width-1, ' '); in sqlite3_str_vappendf()
32338 precision--; in sqlite3_str_vappendf()
32341 if( nPrior > precision-1 ) nPrior = precision - 1; in sqlite3_str_vappendf()
32343 if( nCopyBytes + pAccum->nChar >= pAccum->nAlloc ){ in sqlite3_str_vappendf()
32346 if( pAccum->accError ) break; in sqlite3_str_vappendf()
32348 &pAccum->zText[pAccum->nChar-nCopyBytes], nCopyBytes); in sqlite3_str_vappendf()
32349 precision -= nPrior; in sqlite3_str_vappendf()
32367 if( pAccum->nChar==0 in sqlite3_str_vappendf()
32368 && pAccum->mxAlloc in sqlite3_str_vappendf()
32371 && pAccum->accError==0 in sqlite3_str_vappendf()
32374 ** Extend an existing memory allocation rather than creating in sqlite3_str_vappendf()
32376 assert( (pAccum->printfFlags&SQLITE_PRINTF_MALLOCED)==0 ); in sqlite3_str_vappendf()
32377 pAccum->zText = bufpt; in sqlite3_str_vappendf()
32378 pAccum->nAlloc = sqlite3DbMallocSize(pAccum->db, bufpt); in sqlite3_str_vappendf()
32379 pAccum->nChar = 0x7fffffff & (int)strlen(bufpt); in sqlite3_str_vappendf()
32380 pAccum->printfFlags |= SQLITE_PRINTF_MALLOCED; in sqlite3_str_vappendf()
32391 while( precision-- > 0 && z[0] ){ in sqlite3_str_vappendf()
32394 length = (int)(z - (unsigned char*)bufpt); in sqlite3_str_vappendf()
32403 /* Adjust width to account for extra bytes in UTF-8 characters */ in sqlite3_str_vappendf()
32404 int ii = length - 1; in sqlite3_str_vappendf()
32405 while( ii>=0 ) if( (bufpt[ii--] & 0xc0)==0x80 ) width++; in sqlite3_str_vappendf()
32439 for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){ in sqlite3_str_vappendf()
32446 /* For %#q, do unistr()-style backslash escapes for in sqlite3_str_vappendf()
32494 bufpt[j-1] = '\\'; in sqlite3_str_vappendf()
32517 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return; in sqlite3_str_vappendf()
32519 /* %#T means an Expr pointer that uses Expr.u.zToken */ in sqlite3_str_vappendf()
32522 sqlite3_str_appendall(pAccum, (const char*)pExpr->u.zToken); in sqlite3_str_vappendf()
32523 sqlite3RecordErrorOffsetOfExpr(pAccum->db, pExpr); in sqlite3_str_vappendf()
32529 if( pToken && pToken->n ){ in sqlite3_str_vappendf()
32530 sqlite3_str_append(pAccum, (const char*)pToken->z, pToken->n); in sqlite3_str_vappendf()
32531 sqlite3RecordErrorByteOffset(pAccum->db, pToken->z); in sqlite3_str_vappendf()
32539 if( (pAccum->printfFlags & SQLITE_PRINTF_INTERNAL)==0 ) return; in sqlite3_str_vappendf()
32542 if( pItem->zAlias && !flag_altform2 ){ in sqlite3_str_vappendf()
32543 sqlite3_str_appendall(pAccum, pItem->zAlias); in sqlite3_str_vappendf()
32544 }else if( pItem->zName ){ in sqlite3_str_vappendf()
32545 if( pItem->fg.fixedSchema==0 in sqlite3_str_vappendf()
32546 && pItem->fg.isSubquery==0 in sqlite3_str_vappendf()
32547 && pItem->u4.zDatabase!=0 in sqlite3_str_vappendf()
32549 sqlite3_str_appendall(pAccum, pItem->u4.zDatabase); in sqlite3_str_vappendf()
32552 sqlite3_str_appendall(pAccum, pItem->zName); in sqlite3_str_vappendf()
32553 }else if( pItem->zAlias ){ in sqlite3_str_vappendf()
32554 sqlite3_str_appendall(pAccum, pItem->zAlias); in sqlite3_str_vappendf()
32555 }else if( ALWAYS(pItem->fg.isSubquery) ){/* Because of tag-20240424-1 */ in sqlite3_str_vappendf()
32556 Select *pSel = pItem->u4.pSubq->pSelect; in sqlite3_str_vappendf()
32558 if( pSel->selFlags & SF_NestedFrom ){ in sqlite3_str_vappendf()
32559 sqlite3_str_appendf(pAccum, "(join-%u)", pSel->selId); in sqlite3_str_vappendf()
32560 }else if( pSel->selFlags & SF_MultiValue ){ in sqlite3_str_vappendf()
32561 assert( !pItem->fg.isTabFunc && !pItem->fg.isIndexedBy ); in sqlite3_str_vappendf()
32562 sqlite3_str_appendf(pAccum, "%u-ROW VALUES CLAUSE", in sqlite3_str_vappendf()
32563 pItem->u1.nRow); in sqlite3_str_vappendf()
32565 sqlite3_str_appendf(pAccum, "(subquery-%u)", pSel->selId); in sqlite3_str_vappendf()
32584 width -= length; in sqlite3_str_vappendf()
32594 sqlite3DbFree(pAccum->db, zExtra); in sqlite3_str_vappendf()
32603 ** associated with an error. If db does not already have an error
32613 if( db->errByteOffset!=(-2) ) return; in sqlite3RecordErrorByteOffset()
32614 pParse = db->pParse; in sqlite3RecordErrorByteOffset()
32616 zText =pParse->zTail; in sqlite3RecordErrorByteOffset()
32620 db->errByteOffset = (int)(z-zText); in sqlite3RecordErrorByteOffset()
32630 && (ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) || pExpr->w.iOfst<=0) in sqlite3RecordErrorOffsetOfExpr()
32632 pExpr = pExpr->pLeft; in sqlite3RecordErrorOffsetOfExpr()
32636 db->errByteOffset = pExpr->w.iOfst; in sqlite3RecordErrorOffsetOfExpr()
32648 assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */ in sqlite3StrAccumEnlarge()
32649 if( p->accError ){ in sqlite3StrAccumEnlarge()
32650 testcase(p->accError==SQLITE_TOOBIG); in sqlite3StrAccumEnlarge()
32651 testcase(p->accError==SQLITE_NOMEM); in sqlite3StrAccumEnlarge()
32654 if( p->mxAlloc==0 ){ in sqlite3StrAccumEnlarge()
32656 return p->nAlloc - p->nChar - 1; in sqlite3StrAccumEnlarge()
32658 char *zOld = isMalloced(p) ? p->zText : 0; in sqlite3StrAccumEnlarge()
32659 i64 szNew = p->nChar + N + 1; in sqlite3StrAccumEnlarge()
32660 if( szNew+p->nChar<=p->mxAlloc ){ in sqlite3StrAccumEnlarge()
32663 szNew += p->nChar; in sqlite3StrAccumEnlarge()
32665 if( szNew > p->mxAlloc ){ in sqlite3StrAccumEnlarge()
32670 p->nAlloc = (int)szNew; in sqlite3StrAccumEnlarge()
32672 if( p->db ){ in sqlite3StrAccumEnlarge()
32673 zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc); in sqlite3StrAccumEnlarge()
32675 zNew = sqlite3Realloc(zOld, p->nAlloc); in sqlite3StrAccumEnlarge()
32678 assert( p->zText!=0 || p->nChar==0 ); in sqlite3StrAccumEnlarge()
32679 if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar); in sqlite3StrAccumEnlarge()
32680 p->zText = zNew; in sqlite3StrAccumEnlarge()
32681 p->nAlloc = sqlite3DbMallocSize(p->db, zNew); in sqlite3StrAccumEnlarge()
32682 p->printfFlags |= SQLITE_PRINTF_MALLOCED; in sqlite3StrAccumEnlarge()
32697 testcase( p->nChar + (i64)N > 0x7fffffff ); in sqlite3_str_appendchar()
32698 if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){ in sqlite3_str_appendchar()
32701 while( (N--)>0 ) p->zText[p->nChar++] = c; in sqlite3_str_appendchar()
32708 ** This is a helper routine to sqlite3_str_append() that does special-case
32715 memcpy(&p->zText[p->nChar], z, N); in enlargeAndAppend()
32716 p->nChar += N; in enlargeAndAppend()
32726 assert( p->zText!=0 || p->nChar==0 || p->accError ); in sqlite3_str_append()
32728 assert( p->accError==0 || p->nAlloc==0 || p->mxAlloc==0 ); in sqlite3_str_append()
32729 if( p->nChar+N >= p->nAlloc ){ in sqlite3_str_append()
32732 assert( p->zText ); in sqlite3_str_append()
32733 p->nChar += N; in sqlite3_str_append()
32734 memcpy(&p->zText[p->nChar-N], z, N); in sqlite3_str_append()
32739 ** Append the complete text of zero-terminated string z[] to the p string.
32747 ** Finish off a string by making sure it is zero-terminated.
32753 assert( p->mxAlloc>0 && !isMalloced(p) ); in strAccumFinishRealloc()
32754 zText = sqlite3DbMallocRaw(p->db, 1+(u64)p->nChar ); in strAccumFinishRealloc()
32756 memcpy(zText, p->zText, p->nChar+1); in strAccumFinishRealloc()
32757 p->printfFlags |= SQLITE_PRINTF_MALLOCED; in strAccumFinishRealloc()
32761 p->zText = zText; in strAccumFinishRealloc()
32765 if( p->zText ){ in sqlite3StrAccumFinish()
32766 p->zText[p->nChar] = 0; in sqlite3StrAccumFinish()
32767 if( p->mxAlloc>0 && !isMalloced(p) ){ in sqlite3StrAccumFinish()
32771 return p->zText; in sqlite3StrAccumFinish()
32776 ** as the result of an SQL function.
32779 if( p->accError ){ in sqlite3ResultStrAccum()
32780 sqlite3_result_error_code(pCtx, p->accError); in sqlite3ResultStrAccum()
32783 sqlite3_result_text(pCtx, p->zText, p->nChar, SQLITE_DYNAMIC); in sqlite3ResultStrAccum()
32791 ** This singleton is an sqlite3_str object that is returned if
32794 ** an SQLITE_NOMEM error.
32815 return p ? p->accError : SQLITE_NOMEM; in sqlite3_str_errcode()
32820 return p ? p->nChar : 0; in sqlite3_str_length()
32825 if( p==0 || p->nChar==0 ) return 0; in sqlite3_str_value()
32826 p->zText[p->nChar] = 0; in sqlite3_str_value()
32827 return p->zText; in sqlite3_str_value()
32831 ** Reset an StrAccum string. Reclaim all malloced memory.
32835 sqlite3DbFree(p->db, p->zText); in sqlite3_str_reset()
32836 p->printfFlags &= ~SQLITE_PRINTF_MALLOCED; in sqlite3_str_reset()
32838 p->nAlloc = 0; in sqlite3_str_reset()
32839 p->nChar = 0; in sqlite3_str_reset()
32840 p->zText = 0; in sqlite3_str_reset()
32848 ** memory is used if not NULL. db->mallocFailed is set appropriately
32850 ** zBase: An initial buffer. May be NULL in which case the initial buffer
32858 p->zText = zBase; in sqlite3StrAccumInit()
32859 p->db = db; in sqlite3StrAccumInit()
32860 p->nAlloc = n; in sqlite3StrAccumInit()
32861 p->mxAlloc = mx; in sqlite3StrAccumInit()
32862 p->nChar = 0; in sqlite3StrAccumInit()
32863 p->accError = 0; in sqlite3StrAccumInit()
32864 p->printfFlags = 0; in sqlite3StrAccumInit()
32872 db ? db->aLimit[SQLITE_LIMIT_LENGTH] : SQLITE_MAX_LENGTH); in sqlite3_str_new()
32881 ** %-conversion extensions.
32889 db->aLimit[SQLITE_LIMIT_LENGTH]); in sqlite3VMPrintf()
32901 ** %-conversion extensions.
32914 ** %-conversion extensions.
32938 ** %-conversion extensions.
32999 /* Maximum size of an sqlite3_log() message. */
33011 ** stack space on small-stack systems when logging is disabled.
33073 ** variable-argument wrapper around sqlite3_str_vappendf(). The bFlags argument
33096 p--; in sqlite3RCStrRef()
33097 p->nRCRef++; in sqlite3RCStrRef()
33108 p--; in sqlite3RCStrUnref()
33109 assert( p->nRCRef>0 ); in sqlite3RCStrUnref()
33110 if( p->nRCRef>=2 ){ in sqlite3RCStrUnref()
33111 p->nRCRef--; in sqlite3RCStrUnref()
33124 ** This routine returns 0 on an OOM.
33129 p->nRCRef = 1; in sqlite3RCStrNew()
33141 p--; in sqlite3RCStrResize()
33142 assert( p->nRCRef==1 ); in sqlite3RCStrResize()
33155 ** 2015-06-08
33187 p->iLevel++; in sqlite3TreeViewPush()
33190 if( p->iLevel<(int)sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow; in sqlite3TreeViewPush()
33199 p->iLevel--; in sqlite3TreeViewPop()
33200 if( p->iLevel<0 ){ in sqlite3TreeViewPop()
33217 for(i=0; i<p->iLevel && i<(int)sizeof(p->bLine)-1; i++){ in sqlite3TreeViewLine()
33218 sqlite3_str_append(&acc, p->bLine[i] ? "| " : " ", 4); in sqlite3TreeViewLine()
33220 sqlite3_str_append(&acc, p->bLine[i] ? "|-- " : "'-- ", 4); in sqlite3TreeViewLine()
33256 int colMoreToFollow = i<(nCol - 1); in sqlite3TreeViewColumnList()
33271 printf(" X-%s", z); in sqlite3TreeViewColumnList()
33279 if( flg & COLFLAG_NOEXPAND ) printf(" NO-EXPAND"); in sqlite3TreeViewColumnList()
33290 ** Generate a human-readable description of a WITH clause.
33295 if( pWith->nCte==0 ) return; in sqlite3TreeViewWith()
33296 if( pWith->pOuter ){ in sqlite3TreeViewWith()
33297 sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter); in sqlite3TreeViewWith()
33301 if( pWith->nCte>0 ){ in sqlite3TreeViewWith()
33303 for(i=0; i<pWith->nCte; i++){ in sqlite3TreeViewWith()
33306 const struct Cte *pCte = &pWith->a[i]; in sqlite3TreeViewWith()
33308 sqlite3_str_appendf(&x, "%s", pCte->zName); in sqlite3TreeViewWith()
33309 if( pCte->pCols && pCte->pCols->nExpr>0 ){ in sqlite3TreeViewWith()
33312 for(j=0; j<pCte->pCols->nExpr; j++){ in sqlite3TreeViewWith()
33313 sqlite3_str_appendf(&x, "%c%s", cSep, pCte->pCols->a[j].zEName); in sqlite3TreeViewWith()
33318 if( pCte->eM10d!=M10d_Any ){ in sqlite3TreeViewWith()
33320 pCte->eM10d==M10d_No ? "NOT " : ""); in sqlite3TreeViewWith()
33322 if( pCte->pUse ){ in sqlite3TreeViewWith()
33323 sqlite3_str_appendf(&x, " (pUse=0x%p, nUse=%d)", pCte->pUse, in sqlite3TreeViewWith()
33324 pCte->pUse->nUse); in sqlite3TreeViewWith()
33327 sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1); in sqlite3TreeViewWith()
33328 sqlite3TreeViewSelect(pView, pCte->pSelect, 0); in sqlite3TreeViewWith()
33336 ** Generate a human-readable description of a SrcList object.
33341 for(i=0; i<pSrc->nSrc; i++){ in sqlite3TreeViewSrcList()
33342 const SrcItem *pItem = &pSrc->a[i]; in sqlite3TreeViewSrcList()
33348 sqlite3_str_appendf(&x, "{%d:*} %!S", pItem->iCursor, pItem); in sqlite3TreeViewSrcList()
33349 if( pItem->pSTab ){ in sqlite3TreeViewSrcList()
33351 pItem->pSTab->zName, pItem->pSTab->nCol, pItem->pSTab, in sqlite3TreeViewSrcList()
33352 pItem->colUsed, in sqlite3TreeViewSrcList()
33353 pItem->fg.rowidUsed ? "+rowid" : ""); in sqlite3TreeViewSrcList()
33355 if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))==(JT_LEFT|JT_RIGHT) ){ in sqlite3TreeViewSrcList()
33356 sqlite3_str_appendf(&x, " FULL-OUTER-JOIN"); in sqlite3TreeViewSrcList()
33357 }else if( pItem->fg.jointype & JT_LEFT ){ in sqlite3TreeViewSrcList()
33358 sqlite3_str_appendf(&x, " LEFT-JOIN"); in sqlite3TreeViewSrcList()
33359 }else if( pItem->fg.jointype & JT_RIGHT ){ in sqlite3TreeViewSrcList()
33360 sqlite3_str_appendf(&x, " RIGHT-JOIN"); in sqlite3TreeViewSrcList()
33361 }else if( pItem->fg.jointype & JT_CROSS ){ in sqlite3TreeViewSrcList()
33362 sqlite3_str_appendf(&x, " CROSS-JOIN"); in sqlite3TreeViewSrcList()
33364 if( pItem->fg.jointype & JT_LTORJ ){ in sqlite3TreeViewSrcList()
33367 if( pItem->fg.fromDDL ){ in sqlite3TreeViewSrcList()
33370 if( pItem->fg.isCte ){ in sqlite3TreeViewSrcList()
33371 static const char *aMat[] = {",MAT", "", ",NO-MAT"}; in sqlite3TreeViewSrcList()
33373 pItem->u2.pCteUse->nUse, in sqlite3TreeViewSrcList()
33374 aMat[pItem->u2.pCteUse->eM10d]); in sqlite3TreeViewSrcList()
33376 if( pItem->fg.isOn || (pItem->fg.isUsing==0 && pItem->u3.pOn!=0) ){ in sqlite3TreeViewSrcList()
33379 if( pItem->fg.isTabFunc ) sqlite3_str_appendf(&x, " isTabFunc"); in sqlite3TreeViewSrcList()
33380 if( pItem->fg.isCorrelated ) sqlite3_str_appendf(&x, " isCorrelated"); in sqlite3TreeViewSrcList()
33381 if( pItem->fg.isMaterialized ) sqlite3_str_appendf(&x, " isMaterialized"); in sqlite3TreeViewSrcList()
33382 if( pItem->fg.viaCoroutine ) sqlite3_str_appendf(&x, " viaCoroutine"); in sqlite3TreeViewSrcList()
33383 if( pItem->fg.notCte ) sqlite3_str_appendf(&x, " notCte"); in sqlite3TreeViewSrcList()
33384 if( pItem->fg.isNestedFrom ) sqlite3_str_appendf(&x, " isNestedFrom"); in sqlite3TreeViewSrcList()
33385 if( pItem->fg.fixedSchema ) sqlite3_str_appendf(&x, " fixedSchema"); in sqlite3TreeViewSrcList()
33386 if( pItem->fg.hadSchema ) sqlite3_str_appendf(&x, " hadSchema"); in sqlite3TreeViewSrcList()
33387 if( pItem->fg.isSubquery ) sqlite3_str_appendf(&x, " isSubquery"); in sqlite3TreeViewSrcList()
33390 sqlite3TreeViewItem(pView, zLine, i<pSrc->nSrc-1); in sqlite3TreeViewSrcList()
33392 if( pItem->fg.isSubquery ) n++; in sqlite3TreeViewSrcList()
33393 if( pItem->fg.isTabFunc ) n++; in sqlite3TreeViewSrcList()
33394 if( pItem->fg.isUsing ) n++; in sqlite3TreeViewSrcList()
33395 if( pItem->fg.isUsing ){ in sqlite3TreeViewSrcList()
33396 sqlite3TreeViewIdList(pView, pItem->u3.pUsing, (--n)>0, "USING"); in sqlite3TreeViewSrcList()
33398 if( pItem->fg.isSubquery ){ in sqlite3TreeViewSrcList()
33400 if( pItem->pSTab ){ in sqlite3TreeViewSrcList()
33401 Table *pTab = pItem->pSTab; in sqlite3TreeViewSrcList()
33402 sqlite3TreeViewColumnList(pView, pTab->aCol, pTab->nCol, 1); in sqlite3TreeViewSrcList()
33404 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem) ); in sqlite3TreeViewSrcList()
33405 sqlite3TreeViewSelect(pView, pItem->u4.pSubq->pSelect, 0); in sqlite3TreeViewSrcList()
33407 if( pItem->fg.isTabFunc ){ in sqlite3TreeViewSrcList()
33408 sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:"); in sqlite3TreeViewSrcList()
33415 ** Generate a human-readable description of a Select object.
33421 sqlite3TreeViewLine(pView, "nil-SELECT"); in sqlite3TreeViewSelect()
33425 if( p->pWith ){ in sqlite3TreeViewSelect()
33426 sqlite3TreeViewWith(pView, p->pWith, 1); in sqlite3TreeViewSelect()
33431 if( p->selFlags & SF_WhereBegin ){ in sqlite3TreeViewSelect()
33436 ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""), in sqlite3TreeViewSelect()
33437 ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), in sqlite3TreeViewSelect()
33438 p->selId, p, p->selFlags, in sqlite3TreeViewSelect()
33439 (int)p->nSelectRow in sqlite3TreeViewSelect()
33443 if( p->pPrior ){ in sqlite3TreeViewSelect()
33447 if( p->pSrc && p->pSrc->nSrc && p->pSrc->nAlloc ) n++; in sqlite3TreeViewSelect()
33448 if( p->pWhere ) n++; in sqlite3TreeViewSelect()
33449 if( p->pGroupBy ) n++; in sqlite3TreeViewSelect()
33450 if( p->pHaving ) n++; in sqlite3TreeViewSelect()
33451 if( p->pOrderBy ) n++; in sqlite3TreeViewSelect()
33452 if( p->pLimit ) n++; in sqlite3TreeViewSelect()
33454 if( p->pWin ) n++; in sqlite3TreeViewSelect()
33455 if( p->pWinDefn ) n++; in sqlite3TreeViewSelect()
33458 if( p->pEList ){ in sqlite3TreeViewSelect()
33459 sqlite3TreeViewExprList(pView, p->pEList, n>0, "result-set"); in sqlite3TreeViewSelect()
33461 n--; in sqlite3TreeViewSelect()
33463 if( p->pWin ){ in sqlite3TreeViewSelect()
33465 sqlite3TreeViewPush(&pView, (n--)>0); in sqlite3TreeViewSelect()
33466 sqlite3TreeViewLine(pView, "window-functions"); in sqlite3TreeViewSelect()
33467 for(pX=p->pWin; pX; pX=pX->pNextWin){ in sqlite3TreeViewSelect()
33468 sqlite3TreeViewWinFunc(pView, pX, pX->pNextWin!=0); in sqlite3TreeViewSelect()
33473 if( p->pSrc && p->pSrc->nSrc && p->pSrc->nAlloc ){ in sqlite3TreeViewSelect()
33474 sqlite3TreeViewPush(&pView, (n--)>0); in sqlite3TreeViewSelect()
33476 sqlite3TreeViewSrcList(pView, p->pSrc); in sqlite3TreeViewSelect()
33479 if( p->pWhere ){ in sqlite3TreeViewSelect()
33480 sqlite3TreeViewItem(pView, "WHERE", (n--)>0); in sqlite3TreeViewSelect()
33481 sqlite3TreeViewExpr(pView, p->pWhere, 0); in sqlite3TreeViewSelect()
33484 if( p->pGroupBy ){ in sqlite3TreeViewSelect()
33485 sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY"); in sqlite3TreeViewSelect()
33487 if( p->pHaving ){ in sqlite3TreeViewSelect()
33488 sqlite3TreeViewItem(pView, "HAVING", (n--)>0); in sqlite3TreeViewSelect()
33489 sqlite3TreeViewExpr(pView, p->pHaving, 0); in sqlite3TreeViewSelect()
33493 if( p->pWinDefn ){ in sqlite3TreeViewSelect()
33495 sqlite3TreeViewItem(pView, "WINDOW", (n--)>0); in sqlite3TreeViewSelect()
33496 for(pX=p->pWinDefn; pX; pX=pX->pNextWin){ in sqlite3TreeViewSelect()
33497 sqlite3TreeViewWindow(pView, pX, pX->pNextWin!=0); in sqlite3TreeViewSelect()
33502 if( p->pOrderBy ){ in sqlite3TreeViewSelect()
33503 sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY"); in sqlite3TreeViewSelect()
33505 if( p->pLimit ){ in sqlite3TreeViewSelect()
33506 sqlite3TreeViewItem(pView, "LIMIT", (n--)>0); in sqlite3TreeViewSelect()
33507 sqlite3TreeViewExpr(pView, p->pLimit->pLeft, p->pLimit->pRight!=0); in sqlite3TreeViewSelect()
33508 if( p->pLimit->pRight ){ in sqlite3TreeViewSelect()
33510 sqlite3TreeViewExpr(pView, p->pLimit->pRight, 0); in sqlite3TreeViewSelect()
33515 if( p->pPrior ){ in sqlite3TreeViewSelect()
33517 switch( p->op ){ in sqlite3TreeViewSelect()
33524 p = p->pPrior; in sqlite3TreeViewSelect()
33568 ** Generate a human-readable explanation for a Window object
33573 if( pWin->pFilter ){ in sqlite3TreeViewWindow()
33575 sqlite3TreeViewExpr(pView, pWin->pFilter, 0); in sqlite3TreeViewWindow()
33577 if( pWin->eFrmType==TK_FILTER ) return; in sqlite3TreeViewWindow()
33580 if( pWin->zName ){ in sqlite3TreeViewWindow()
33581 sqlite3TreeViewLine(pView, "OVER %s (%p)", pWin->zName, pWin); in sqlite3TreeViewWindow()
33585 if( pWin->zBase ) nElement++; in sqlite3TreeViewWindow()
33586 if( pWin->pOrderBy ) nElement++; in sqlite3TreeViewWindow()
33587 if( pWin->eFrmType!=0 && pWin->eFrmType!=TK_FILTER ) nElement++; in sqlite3TreeViewWindow()
33588 if( pWin->eExclude ) nElement++; in sqlite3TreeViewWindow()
33589 if( pWin->zBase ){ in sqlite3TreeViewWindow()
33590 sqlite3TreeViewPush(&pView, (--nElement)>0); in sqlite3TreeViewWindow()
33591 sqlite3TreeViewLine(pView, "window: %s", pWin->zBase); in sqlite3TreeViewWindow()
33594 if( pWin->pPartition ){ in sqlite3TreeViewWindow()
33595 sqlite3TreeViewExprList(pView, pWin->pPartition, nElement>0,"PARTITION-BY"); in sqlite3TreeViewWindow()
33597 if( pWin->pOrderBy ){ in sqlite3TreeViewWindow()
33598 sqlite3TreeViewExprList(pView, pWin->pOrderBy, (--nElement)>0, "ORDER-BY"); in sqlite3TreeViewWindow()
33600 if( pWin->eFrmType!=0 && pWin->eFrmType!=TK_FILTER ){ in sqlite3TreeViewWindow()
33603 if( pWin->eFrmType==TK_RANGE ) zFrmType = "RANGE"; in sqlite3TreeViewWindow()
33604 if( pWin->eFrmType==TK_GROUPS ) zFrmType = "GROUPS"; in sqlite3TreeViewWindow()
33606 pWin->bImplicitFrame ? " (implied)" : ""); in sqlite3TreeViewWindow()
33607 sqlite3TreeViewItem(pView, zBuf, (--nElement)>0); in sqlite3TreeViewWindow()
33608 sqlite3TreeViewBound(pView, pWin->eStart, pWin->pStart, 1); in sqlite3TreeViewWindow()
33609 sqlite3TreeViewBound(pView, pWin->eEnd, pWin->pEnd, 0); in sqlite3TreeViewWindow()
33612 if( pWin->eExclude ){ in sqlite3TreeViewWindow()
33615 switch( pWin->eExclude ){ in sqlite3TreeViewWindow()
33621 sqlite3_snprintf(sizeof(zBuf),zBuf,"invalid(%d)", pWin->eExclude); in sqlite3TreeViewWindow()
33635 ** Generate a human-readable explanation for a Window Function object
33641 pWin->pWFunc->zName, pWin->pWFunc->nArg); in sqlite3TreeViewWinFunc()
33648 ** Generate a human-readable explanation of an expression tree.
33660 if( pExpr->flags || pExpr->affExpr || pExpr->vvaFlags || pExpr->pAggInfo ){ in sqlite3TreeViewExpr()
33664 pExpr->flags, pExpr->affExpr ? pExpr->affExpr : 'n'); in sqlite3TreeViewExpr()
33666 sqlite3_str_appendf(&x, " outer.iJoin=%d", pExpr->w.iJoin); in sqlite3TreeViewExpr()
33669 sqlite3_str_appendf(&x, " inner.iJoin=%d", pExpr->w.iJoin); in sqlite3TreeViewExpr()
33677 if( pExpr->pAggInfo!=0 ){ in sqlite3TreeViewExpr()
33678 sqlite3_str_appendf(&x, " agg-column[%d]", pExpr->iAgg); in sqlite3TreeViewExpr()
33684 switch( pExpr->op ){ in sqlite3TreeViewExpr()
33687 pExpr->iTable, pExpr->iColumn, zFlgs); in sqlite3TreeViewExpr()
33691 if( pExpr->iTable<0 ){ in sqlite3TreeViewExpr()
33694 if( pExpr->op2 ){ in sqlite3TreeViewExpr()
33695 sqlite3_snprintf(sizeof(zOp2),zOp2," op2=0x%02x",pExpr->op2); in sqlite3TreeViewExpr()
33700 pExpr->iColumn, zFlgs, zOp2); in sqlite3TreeViewExpr()
33704 pExpr->iTable, pExpr->iColumn, in sqlite3TreeViewExpr()
33705 pExpr->y.pTab, zFlgs); in sqlite3TreeViewExpr()
33708 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); in sqlite3TreeViewExpr()
33713 if( pExpr->flags & EP_IntValue ){ in sqlite3TreeViewExpr()
33714 sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue); in sqlite3TreeViewExpr()
33716 sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken); in sqlite3TreeViewExpr()
33723 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); in sqlite3TreeViewExpr()
33729 sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken); in sqlite3TreeViewExpr()
33744 sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken); in sqlite3TreeViewExpr()
33751 pExpr->u.zToken, pExpr->iColumn); in sqlite3TreeViewExpr()
33755 sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable); in sqlite3TreeViewExpr()
33760 sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken); in sqlite3TreeViewExpr()
33767 sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken); in sqlite3TreeViewExpr()
33768 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); in sqlite3TreeViewExpr()
33805 "IS-FALSE", "IS-TRUE", "IS-NOT-FALSE", "IS-NOT-TRUE" in sqlite3TreeViewExpr()
33807 assert( pExpr->op2==TK_IS || pExpr->op2==TK_ISNOT ); in sqlite3TreeViewExpr()
33808 assert( pExpr->pRight ); in sqlite3TreeViewExpr()
33809 assert( sqlite3ExprSkipCollateAndLikely(pExpr->pRight)->op in sqlite3TreeViewExpr()
33811 x = (pExpr->op2==TK_ISNOT)*2 + sqlite3ExprTruthValue(pExpr->pRight); in sqlite3TreeViewExpr()
33818 sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken); in sqlite3TreeViewExpr()
33819 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); in sqlite3TreeViewExpr()
33826 ** up in the treeview output as "SOFT-COLLATE". Explicit COLLATE in sqlite3TreeViewExpr()
33831 !ExprHasProperty(pExpr, EP_Collate) ? "SOFT-" : "", in sqlite3TreeViewExpr()
33832 pExpr->u.zToken, zFlgs); in sqlite3TreeViewExpr()
33833 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); in sqlite3TreeViewExpr()
33846 pFarg = pExpr->x.pList; in sqlite3TreeViewExpr()
33848 pWin = IsWindowFunc(pExpr) ? pExpr->y.pWin : 0; in sqlite3TreeViewExpr()
33854 if( pExpr->op==TK_AGG_FUNCTION ){ in sqlite3TreeViewExpr()
33856 pExpr->op2, pExpr->u.zToken, zFlgs, in sqlite3TreeViewExpr()
33857 pExpr->pAggInfo ? pExpr->pAggInfo->selId : 0, in sqlite3TreeViewExpr()
33858 pExpr->iAgg, pExpr->pAggInfo); in sqlite3TreeViewExpr()
33859 }else if( pExpr->op2!=0 ){ in sqlite3TreeViewExpr()
33862 sqlite3_snprintf(sizeof(zBuf),zBuf,"0x%02x",pExpr->op2); in sqlite3TreeViewExpr()
33864 if( pExpr->op2==NC_IsCheck ) zOp2 = "NC_IsCheck"; in sqlite3TreeViewExpr()
33865 if( pExpr->op2==NC_IdxExpr ) zOp2 = "NC_IdxExpr"; in sqlite3TreeViewExpr()
33866 if( pExpr->op2==NC_PartIdx ) zOp2 = "NC_PartIdx"; in sqlite3TreeViewExpr()
33867 if( pExpr->op2==NC_GenCol ) zOp2 = "NC_GenCol"; in sqlite3TreeViewExpr()
33869 pExpr->u.zToken, zFlgs, zOp2); in sqlite3TreeViewExpr()
33871 sqlite3TreeViewLine(pView, "FUNCTION %Q%s", pExpr->u.zToken, zFlgs); in sqlite3TreeViewExpr()
33874 sqlite3TreeViewExprList(pView, pFarg, pWin!=0 || pExpr->pLeft, 0); in sqlite3TreeViewExpr()
33875 if( pExpr->pLeft ){ in sqlite3TreeViewExpr()
33876 Expr *pOB = pExpr->pLeft; in sqlite3TreeViewExpr()
33877 assert( pOB->op==TK_ORDER ); in sqlite3TreeViewExpr()
33879 sqlite3TreeViewExprList(pView, pOB->x.pList, pWin!=0, "ORDERBY"); in sqlite3TreeViewExpr()
33890 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, "ORDERBY"); in sqlite3TreeViewExpr()
33896 sqlite3TreeViewLine(pView, "EXISTS-expr flags=0x%x", pExpr->flags); in sqlite3TreeViewExpr()
33897 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); in sqlite3TreeViewExpr()
33902 sqlite3TreeViewLine(pView, "subquery-expr flags=0x%x", pExpr->flags); in sqlite3TreeViewExpr()
33903 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); in sqlite3TreeViewExpr()
33909 sqlite3_str_appendf(pStr, "IN flags=0x%x", pExpr->flags); in sqlite3TreeViewExpr()
33910 if( pExpr->iTable ) sqlite3_str_appendf(pStr, " iTable=%d",pExpr->iTable); in sqlite3TreeViewExpr()
33913 pExpr->y.sub.regReturn, pExpr->y.sub.iAddr); in sqlite3TreeViewExpr()
33918 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); in sqlite3TreeViewExpr()
33920 sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0); in sqlite3TreeViewExpr()
33922 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); in sqlite3TreeViewExpr()
33935 ** X is stored in pExpr->pLeft. in sqlite3TreeViewExpr()
33936 ** Y is stored in pExpr->pList->a[0].pExpr. in sqlite3TreeViewExpr()
33937 ** Z is stored in pExpr->pList->a[1].pExpr. in sqlite3TreeViewExpr()
33941 pX = pExpr->pLeft; in sqlite3TreeViewExpr()
33943 assert( pExpr->x.pList->nExpr==2 ); in sqlite3TreeViewExpr()
33944 pY = pExpr->x.pList->a[0].pExpr; in sqlite3TreeViewExpr()
33945 pZ = pExpr->x.pList->a[1].pExpr; in sqlite3TreeViewExpr()
33954 ** to a column in the new.* or old.* pseudo-tables available to in sqlite3TreeViewExpr()
33956 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn in sqlite3TreeViewExpr()
33957 ** is set to the column of the pseudo-table to read, or to -1 to in sqlite3TreeViewExpr()
33961 pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn); in sqlite3TreeViewExpr()
33966 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); in sqlite3TreeViewExpr()
33968 sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0); in sqlite3TreeViewExpr()
33974 switch( pExpr->affExpr ){ in sqlite3TreeViewExpr()
33982 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); in sqlite3TreeViewExpr()
33988 pExpr->iTable, pExpr->iColumn, zFlgs); in sqlite3TreeViewExpr()
33989 sqlite3TreeViewExpr(pView, pExpr->pRight, 0); in sqlite3TreeViewExpr()
33995 sqlite3TreeViewBareExprList(pView, pExpr->x.pList, z); in sqlite3TreeViewExpr()
34000 sqlite3TreeViewLine(pView, "SELECT-COLUMN %d of [0..%d]%s", in sqlite3TreeViewExpr()
34001 pExpr->iColumn, pExpr->iTable-1, in sqlite3TreeViewExpr()
34002 pExpr->pRight==pExpr->pLeft ? " (SELECT-owner)" : ""); in sqlite3TreeViewExpr()
34003 assert( ExprUseXSelect(pExpr->pLeft) ); in sqlite3TreeViewExpr()
34004 sqlite3TreeViewSelect(pView, pExpr->pLeft->x.pSelect, 0); in sqlite3TreeViewExpr()
34008 sqlite3TreeViewLine(pView, "IF-NULL-ROW %d", pExpr->iTable); in sqlite3TreeViewExpr()
34009 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); in sqlite3TreeViewExpr()
34016 tmp.op = pExpr->op2; in sqlite3TreeViewExpr()
34021 if( pExpr->iColumn<=0 ){ in sqlite3TreeViewExpr()
34025 pExpr->iColumn-1); in sqlite3TreeViewExpr()
34030 sqlite3TreeViewLine(pView, "op=%d", pExpr->op); in sqlite3TreeViewExpr()
34036 sqlite3TreeViewExpr(pView, pExpr->pLeft, 1); in sqlite3TreeViewExpr()
34037 sqlite3TreeViewExpr(pView, pExpr->pRight, 0); in sqlite3TreeViewExpr()
34040 sqlite3TreeViewExpr(pView, pExpr->pLeft, 0); in sqlite3TreeViewExpr()
34047 ** Generate a human-readable explanation of an expression list.
34060 for(i=0; i<pList->nExpr; i++){ in sqlite3TreeViewBareExprList()
34061 int j = pList->a[i].u.x.iOrderByCol; in sqlite3TreeViewBareExprList()
34062 u8 sortFlags = pList->a[i].fg.sortFlags; in sqlite3TreeViewBareExprList()
34063 char *zName = pList->a[i].zEName; in sqlite3TreeViewBareExprList()
34064 int moreToFollow = i<pList->nExpr - 1; in sqlite3TreeViewBareExprList()
34070 switch( pList->a[i].fg.eEName ){ in sqlite3TreeViewBareExprList()
34075 fprintf(stdout, "TABLE-ALIAS-NAME(\"%s\") ", zName); in sqlite3TreeViewBareExprList()
34076 if( pList->a[i].fg.bUsed ) fprintf(stdout, "(used) "); in sqlite3TreeViewBareExprList()
34077 if( pList->a[i].fg.bUsingTerm ) fprintf(stdout, "(USING-term) "); in sqlite3TreeViewBareExprList()
34078 if( pList->a[i].fg.bNoExpand ) fprintf(stdout, "(NoExpand) "); in sqlite3TreeViewBareExprList()
34091 fprintf(stdout, "NULLS-LAST"); in sqlite3TreeViewBareExprList()
34096 sqlite3TreeViewExpr(pView, pList->a[i].pExpr, moreToFollow); in sqlite3TreeViewBareExprList()
34115 ** Generate a human-readable explanation of an id-list.
34128 for(i=0; i<pList->nId; i++){ in sqlite3TreeViewBareIdList()
34129 char *zName = pList->a[i].zName; in sqlite3TreeViewBareIdList()
34130 int moreToFollow = i<pList->nId - 1; in sqlite3TreeViewBareIdList()
34151 ** Generate a human-readable explanation of a list of Upsert objects
34162 sqlite3TreeViewPush(&pView, pUpsert->pNextUpsert!=0 || moreToFollow); in sqlite3TreeViewUpsert()
34164 pUpsert->isDoUpdate ? "UPDATE" : "NOTHING"); in sqlite3TreeViewUpsert()
34165 n = (pUpsert->pUpsertSet!=0) + (pUpsert->pUpsertWhere!=0); in sqlite3TreeViewUpsert()
34166 sqlite3TreeViewExprList(pView, pUpsert->pUpsertTarget, (n--)>0, "TARGET"); in sqlite3TreeViewUpsert()
34167 sqlite3TreeViewExprList(pView, pUpsert->pUpsertSet, (n--)>0, "SET"); in sqlite3TreeViewUpsert()
34168 if( pUpsert->pUpsertWhere ){ in sqlite3TreeViewUpsert()
34169 sqlite3TreeViewItem(pView, "WHERE", (n--)>0); in sqlite3TreeViewUpsert()
34170 sqlite3TreeViewExpr(pView, pUpsert->pUpsertWhere, 0); in sqlite3TreeViewUpsert()
34174 pUpsert = pUpsert->pNextUpsert; in sqlite3TreeViewUpsert()
34181 ** Generate a human-readable diagram of the data structure that go
34182 ** into generating an DELETE statement.
34203 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewDelete()
34208 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewDelete()
34214 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewDelete()
34220 sqlite3TreeViewExprList(pView, pOrderBy, (--n)>0, "ORDER-BY"); in sqlite3TreeViewDelete()
34223 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewDelete()
34229 sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1); in sqlite3TreeViewDelete()
34237 ** Generate a human-readable diagram of the data structure that go
34238 ** into generating an INSERT statement.
34270 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewInsert()
34275 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewInsert()
34281 sqlite3TreeViewIdList(pView, pColumnList, (--n)>0, "COLUMNS"); in sqlite3TreeViewInsert()
34284 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewInsert()
34285 sqlite3TreeViewLine(pView, "DATA-SOURCE"); in sqlite3TreeViewInsert()
34290 sqlite3TreeViewExprList(pView, pExprList, (--n)>0, "VALUES"); in sqlite3TreeViewInsert()
34293 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewInsert()
34299 sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1); in sqlite3TreeViewInsert()
34307 ** Generate a human-readable diagram of the data structure that go
34308 ** into generating an UPDATE statement.
34342 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewUpdate()
34347 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewUpdate()
34353 sqlite3TreeViewExprList(pView, pChanges, (--n)>0, "SET"); in sqlite3TreeViewUpdate()
34356 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewUpdate()
34362 sqlite3TreeViewExprList(pView, pOrderBy, (--n)>0, "ORDER-BY"); in sqlite3TreeViewUpdate()
34365 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewUpdate()
34371 sqlite3TreeViewPush(&pView, (--n)>0); in sqlite3TreeViewUpdate()
34377 sqlite3TreeViewTrigger(pView, pTrigger, (--n)>0, 1); in sqlite3TreeViewUpdate()
34385 ** Show a human-readable graph of a TriggerStep
34396 moreToFollow || (showFullList && pStep->pNext!=0)); in sqlite3TreeViewTriggerStep()
34398 if( cnt++ && pStep->pNext==0 ){ in sqlite3TreeViewTriggerStep()
34402 sqlite3TreeViewLine(pView, "%s", pStep->zSpan ? pStep->zSpan : "RETURNING"); in sqlite3TreeViewTriggerStep()
34403 }while( showFullList && (pStep = pStep->pNext)!=0 ); in sqlite3TreeViewTriggerStep()
34408 ** Show a human-readable graph of a Trigger
34419 moreToFollow || (showFullList && pTrigger->pNext!=0)); in sqlite3TreeViewTrigger()
34421 if( cnt++ && pTrigger->pNext==0 ){ in sqlite3TreeViewTrigger()
34425 sqlite3TreeViewLine(pView, "TRIGGER %s", pTrigger->zName); in sqlite3TreeViewTrigger()
34427 sqlite3TreeViewTriggerStep(pView, pTrigger->step_list, 0, 1); in sqlite3TreeViewTrigger()
34429 }while( showFullList && (pTrigger = pTrigger->pNext)!=0 ); in sqlite3TreeViewTrigger()
34436 ** These simplified versions of the tree-view routines omit unnecessary
34486 ** This file contains code to implement a pseudo-random number
34505 /* The RFC-7539 ChaCha20 block function
34507 #define ROTL(a,b) (((a) << (b)) | ((a) >> (32 - (b))))
34536 /* The "wsdPrng" macro will resolve to the pseudo-random number generator in sqlite3_randomness()
34538 ** we have to locate the state vector at run-time. In the more common in sqlite3_randomness()
34590 memcpy(zBuf, &wsdPrng.out[wsdPrng.n-N], N); in sqlite3_randomness()
34591 wsdPrng.n -= N; in sqlite3_randomness()
34596 N -= wsdPrng.n; in sqlite3_randomness()
34647 ** This file presents a simple cross-platform threading interface for
34660 ** single-threaded if desired.
34672 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
34695 /* This routine is never used in single-threaded mode */ in sqlite3ThreadCreate()
34702 p->xTask = xTask; in sqlite3ThreadCreate()
34703 p->pIn = pIn; in sqlite3ThreadCreate()
34711 rc = pthread_create(&p->tid, 0, xTask, pIn); in sqlite3ThreadCreate()
34714 p->done = 1; in sqlite3ThreadCreate()
34715 p->pOut = xTask(pIn); in sqlite3ThreadCreate()
34727 if( p->done ){ in sqlite3ThreadJoin()
34728 *ppOut = p->pOut; in sqlite3ThreadJoin()
34731 rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK; in sqlite3ThreadJoin()
34744 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
34770 assert( p->id==GetCurrentThreadId() ); in sqlite3ThreadProc()
34772 assert( p->xTask!=0 ); in sqlite3ThreadProc()
34773 p->pResult = p->xTask(p->pIn); in sqlite3ThreadProc()
34800 p->xTask = xTask; in sqlite3ThreadCreate()
34801 p->pIn = pIn; in sqlite3ThreadCreate()
34802 p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id); in sqlite3ThreadCreate()
34803 if( p->tid==0 ){ in sqlite3ThreadCreate()
34807 if( p->xTask==0 ){ in sqlite3ThreadCreate()
34808 p->id = GetCurrentThreadId(); in sqlite3ThreadCreate()
34809 p->pResult = xTask(pIn); in sqlite3ThreadCreate()
34824 if( p->xTask==0 ){ in sqlite3ThreadJoin()
34825 /* assert( p->id==GetCurrentThreadId() ); */ in sqlite3ThreadJoin()
34827 assert( p->tid==0 ); in sqlite3ThreadJoin()
34829 assert( p->id!=0 && p->id!=GetCurrentThreadId() ); in sqlite3ThreadJoin()
34830 rc = sqlite3Win32Wait((HANDLE)p->tid); in sqlite3ThreadJoin()
34832 bRc = CloseHandle((HANDLE)p->tid); in sqlite3ThreadJoin()
34835 if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult; in sqlite3ThreadJoin()
34844 /********************************* Single-Threaded **************************/
34873 p->xTask = xTask; in sqlite3ThreadCreate()
34874 p->pIn = pIn; in sqlite3ThreadCreate()
34876 p->xTask = 0; in sqlite3ThreadCreate()
34877 p->pResult = xTask(pIn); in sqlite3ThreadCreate()
34888 if( p->xTask ){ in sqlite3ThreadJoin()
34889 *ppOut = p->xTask(p->pIn); in sqlite3ThreadJoin()
34891 *ppOut = p->pResult; in sqlite3ThreadJoin()
34907 /****************************** End Single-Threaded *************************/
34923 ** This file contains routines used to translate between UTF-8,
34924 ** UTF-16, UTF-16BE, and UTF-16LE.
34926 ** Notes on UTF-8:
34928 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
34935 ** Notes on UTF-16: (with wwww+1==uuuuu)
34937 ** Word-0 Word-1 Value
34943 ** 0xff 0xfe little-endian utf-16 follows
34944 ** 0xfe 0xff big-endian utf-16 follows
34961 ** a multi-byte UTF8 character.
35000 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
35001 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
35012 *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
35013 *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
35049 ** Translate a single UTF-8 character. Return the unicode value.
35056 ** Notes On Invalid UTF-8:
35058 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
35059 ** be encoded as a multi-byte character. Any multi-byte character that
35063 ** If a multi-byte character attempts to encode a value between
35067 ** byte of a character are interpreted as single-byte characters
35071 ** * This routine accepts over-length UTF8 encodings
35072 ** for unicode values 0x80 and greater. It does not change over-length
35078 c = sqlite3Utf8Trans1[c-0xc0]; \
35092 ** For this routine, we assume the UTF8 string is always zero-terminated. in sqlite3Utf8Read()
35096 c = sqlite3Utf8Trans1[c-0xc0]; in sqlite3Utf8Read()
35109 ** more than n characters from the buffer. z[] is not zero-terminated.
35129 c = sqlite3Utf8Trans1[c-0xc0]; in sqlite3Utf8ReadLimited()
35150 ** desiredEnc. It is an error if the string is already of the desired
35161 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) ); in sqlite3VdbeMemTranslate()
35162 assert( pMem->flags&MEM_Str ); in sqlite3VdbeMemTranslate()
35163 assert( pMem->enc!=desiredEnc ); in sqlite3VdbeMemTranslate()
35164 assert( pMem->enc!=0 ); in sqlite3VdbeMemTranslate()
35165 assert( pMem->n>=0 ); in sqlite3VdbeMemTranslate()
35177 /* If the translation is between UTF-16 little and big endian, then in sqlite3VdbeMemTranslate()
35181 if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){ in sqlite3VdbeMemTranslate()
35189 zIn = (u8*)pMem->z; in sqlite3VdbeMemTranslate()
35190 zTerm = &zIn[pMem->n&~1]; in sqlite3VdbeMemTranslate()
35197 pMem->enc = desiredEnc; in sqlite3VdbeMemTranslate()
35203 /* When converting from UTF-16, the maximum growth results from in sqlite3VdbeMemTranslate()
35204 ** translating a 2-byte character to a 4-byte UTF-8 character. in sqlite3VdbeMemTranslate()
35206 ** nul-terminator. in sqlite3VdbeMemTranslate()
35208 pMem->n &= ~1; in sqlite3VdbeMemTranslate()
35209 len = 2 * (sqlite3_int64)pMem->n + 1; in sqlite3VdbeMemTranslate()
35211 /* When converting from UTF-8 to UTF-16 the maximum growth is caused in sqlite3VdbeMemTranslate()
35212 ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16 in sqlite3VdbeMemTranslate()
35214 ** nul-terminator. in sqlite3VdbeMemTranslate()
35216 len = 2 * (sqlite3_int64)pMem->n + 2; in sqlite3VdbeMemTranslate()
35225 zIn = (u8*)pMem->z; in sqlite3VdbeMemTranslate()
35226 zTerm = &zIn[pMem->n]; in sqlite3VdbeMemTranslate()
35227 zOut = sqlite3DbMallocRaw(pMem->db, len); in sqlite3VdbeMemTranslate()
35233 if( pMem->enc==SQLITE_UTF8 ){ in sqlite3VdbeMemTranslate()
35235 /* UTF-8 -> UTF-16 Little-endian */ in sqlite3VdbeMemTranslate()
35242 /* UTF-8 -> UTF-16 Big-endian */ in sqlite3VdbeMemTranslate()
35248 pMem->n = (int)(z - zOut); in sqlite3VdbeMemTranslate()
35252 if( pMem->enc==SQLITE_UTF16LE ){ in sqlite3VdbeMemTranslate()
35253 /* UTF-16 Little-endian -> UTF-8 */ in sqlite3VdbeMemTranslate()
35265 zIn -= 2; in sqlite3VdbeMemTranslate()
35282 /* UTF-16 Big-endian -> UTF-8 */ in sqlite3VdbeMemTranslate()
35294 zIn -= 2; in sqlite3VdbeMemTranslate()
35311 pMem->n = (int)(z - zOut); in sqlite3VdbeMemTranslate()
35314 assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len ); in sqlite3VdbeMemTranslate()
35316 c = MEM_Str|MEM_Term|(pMem->flags&(MEM_AffMask|MEM_Subtype)); in sqlite3VdbeMemTranslate()
35318 pMem->flags = c; in sqlite3VdbeMemTranslate()
35319 pMem->enc = desiredEnc; in sqlite3VdbeMemTranslate()
35320 pMem->z = (char*)zOut; in sqlite3VdbeMemTranslate()
35321 pMem->zMalloc = pMem->z; in sqlite3VdbeMemTranslate()
35322 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z); in sqlite3VdbeMemTranslate()
35340 ** This routine checks for a byte-order mark at the beginning of the
35341 ** UTF-16 string stored in *pMem. If one is present, it is removed and
35343 ** byte-swapping, it just sets Mem.enc appropriately.
35352 assert( pMem->n>=0 ); in sqlite3VdbeMemHandleBom()
35353 if( pMem->n>1 ){ in sqlite3VdbeMemHandleBom()
35354 u8 b1 = *(u8 *)pMem->z; in sqlite3VdbeMemHandleBom()
35355 u8 b2 = *(((u8 *)pMem->z) + 1); in sqlite3VdbeMemHandleBom()
35367 pMem->n -= 2; in sqlite3VdbeMemHandleBom()
35368 memmove(pMem->z, &pMem->z[2], pMem->n); in sqlite3VdbeMemHandleBom()
35369 pMem->z[pMem->n] = '\0'; in sqlite3VdbeMemHandleBom()
35370 pMem->z[pMem->n+1] = '\0'; in sqlite3VdbeMemHandleBom()
35371 pMem->flags |= MEM_Term; in sqlite3VdbeMemHandleBom()
35372 pMem->enc = bom; in sqlite3VdbeMemHandleBom()
35380 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
35393 zTerm = (const u8*)(-1); in sqlite3Utf8CharLen()
35403 /* This test function is not currently used by the automated test-suite.
35408 ** Translate UTF-8 to UTF-8.
35410 ** This has the effect of making sure that the string is well-formed
35411 ** UTF-8. Miscoded characters are removed.
35413 ** The translation is done in-place and aborted if the output
35428 return (int)(zOut - zStart); in sqlite3Utf8To8()
35434 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
35435 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
35438 ** NULL is returned if there is an allocation error.
35446 if( db->mallocFailed ){ in sqlite3Utf16to8()
35450 assert( (m.flags & MEM_Term)!=0 || db->mallocFailed ); in sqlite3Utf16to8()
35451 assert( (m.flags & MEM_Str)!=0 || db->mallocFailed ); in sqlite3Utf16to8()
35452 assert( m.z || db->mallocFailed ); in sqlite3Utf16to8()
35457 ** zIn is a UTF-16 encoded unicode string at least nByte bytes long.
35459 ** in pZ. nChar must be non-negative. Surrogate pairs count as a single
35465 unsigned char const *zEnd = &z[nByte-1]; in sqlite3Utf16ByteLen()
35475 return (int)(z-(unsigned char const *)zIn) in sqlite3Utf16ByteLen()
35476 - (SQLITE_UTF16NATIVE==SQLITE_UTF16LE); in sqlite3Utf16ByteLen()
35495 n = (int)(z-zBuf); in sqlite3UtfSelfTest()
35504 assert( (z-zBuf)==n ); in sqlite3UtfSelfTest()
35541 ** sqlite3FaultSim() function only returns non-zero during testing.
35543 ** During testing, if the test harness has set a fault-sim callback using
35545 ** each call to sqlite3FaultSim() is relayed to that application-supplied
35546 ** callback and the integer return value form the application-supplied
35584 ** Return true if the floating point value is NaN or +Inf or -Inf.
35597 ** lower 30 bits of a 32-bit signed integer.
35612 ** The column type is an extra string stored after the zero-terminator on
35616 if( pCol->colFlags & COLFLAG_HASTYPE ){ in sqlite3ColumnType()
35617 return pCol->zCnName + strlen(pCol->zCnName) + 1; in sqlite3ColumnType()
35618 }else if( pCol->eCType ){ in sqlite3ColumnType()
35619 assert( pCol->eCType<=SQLITE_N_STDTYPE ); in sqlite3ColumnType()
35620 return (char*)sqlite3StdType[pCol->eCType-1]; in sqlite3ColumnType()
35627 ** Helper function for sqlite3Error() - called rarely. Broken out into
35632 if( db->pErr ) sqlite3ValueSetNull(db->pErr); in sqlite3ErrorFinish()
35643 db->errCode = err_code; in sqlite3Error()
35644 if( err_code || db->pErr ){ in sqlite3Error()
35647 db->errByteOffset = -1; in sqlite3Error()
35657 db->errCode = SQLITE_OK; in sqlite3ErrorClear()
35658 db->errByteOffset = -1; in sqlite3ErrorClear()
35659 if( db->pErr ) sqlite3ValueSetNull(db->pErr); in sqlite3ErrorClear()
35663 ** Load the sqlite3.iSysErrno field if that is an appropriate thing
35673 for(ii=0; ii<db->nDb; ii++){ in sqlite3SystemError()
35674 if( db->aDb[ii].pBt ){ in sqlite3SystemError()
35675 iErr = sqlite3PagerWalSystemErrno(sqlite3BtreePager(db->aDb[ii].pBt)); in sqlite3SystemError()
35677 db->iSysErrno = iErr; in sqlite3SystemError()
35687 db->iSysErrno = sqlite3OsGetLastError(db->pVfs); in sqlite3SystemError()
35697 ** assumed to be encoded in UTF-8.
35705 db->errCode = err_code; in sqlite3ErrorWithMsg()
35709 }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){ in sqlite3ErrorWithMsg()
35715 sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC); in sqlite3ErrorWithMsg()
35723 sqlite3 *db = p->db; in sqlite3ProgressCheck()
35724 if( AtomicLoad(&db->u1.isInterrupted) ){ in sqlite3ProgressCheck()
35725 p->nErr++; in sqlite3ProgressCheck()
35726 p->rc = SQLITE_INTERRUPT; in sqlite3ProgressCheck()
35729 if( db->xProgress ){ in sqlite3ProgressCheck()
35730 if( p->rc==SQLITE_INTERRUPT ){ in sqlite3ProgressCheck()
35731 p->nProgressSteps = 0; in sqlite3ProgressCheck()
35732 }else if( (++p->nProgressSteps)>=db->nProgressOps ){ in sqlite3ProgressCheck()
35733 if( db->xProgress(db->pProgressArg) ){ in sqlite3ProgressCheck()
35734 p->nErr++; in sqlite3ProgressCheck()
35735 p->rc = SQLITE_INTERRUPT; in sqlite3ProgressCheck()
35737 p->nProgressSteps = 0; in sqlite3ProgressCheck()
35744 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
35747 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
35756 sqlite3 *db = pParse->db; in sqlite3ErrorMsg()
35758 assert( db->pParse==pParse || db->pParse->pToplevel==pParse ); in sqlite3ErrorMsg()
35759 db->errByteOffset = -2; in sqlite3ErrorMsg()
35763 if( db->errByteOffset<-1 ) db->errByteOffset = -1; in sqlite3ErrorMsg()
35764 if( db->suppressErr ){ in sqlite3ErrorMsg()
35766 if( db->mallocFailed ){ in sqlite3ErrorMsg()
35767 pParse->nErr++; in sqlite3ErrorMsg()
35768 pParse->rc = SQLITE_NOMEM; in sqlite3ErrorMsg()
35771 pParse->nErr++; in sqlite3ErrorMsg()
35772 sqlite3DbFree(db, pParse->zErrMsg); in sqlite3ErrorMsg()
35773 pParse->zErrMsg = zMsg; in sqlite3ErrorMsg()
35774 pParse->rc = SQLITE_ERROR; in sqlite3ErrorMsg()
35775 pParse->pWith = 0; in sqlite3ErrorMsg()
35786 if( db==0 || (pParse = db->pParse)==0 ) return errCode; in sqlite3ErrorToParser()
35787 pParse->rc = errCode; in sqlite3ErrorToParser()
35788 pParse->nErr++; in sqlite3ErrorToParser()
35793 ** Convert an SQL-style quoted string into a normal string by removing
35794 ** the quote characters. The conversion is done in-place. If the
35796 ** is a no-op.
35798 ** The input string must be zero-terminated. A new zero-terminator
35801 ** The return value is -1 if no dequoting occurs or the length of the
35805 ** 2002-02-14: This routine is extended to remove MS-Access style
35806 ** brackets from around identifiers. For example: "[a-b-c]" becomes
35807 ** "a-b-c".
35833 assert( sqlite3Isquote(p->u.zToken[0]) ); in sqlite3DequoteExpr()
35834 p->flags |= p->u.zToken[0]=='"' ? EP_Quoted|EP_DblQuoted : EP_Quoted; in sqlite3DequoteExpr()
35835 sqlite3Dequote(p->u.zToken); in sqlite3DequoteExpr()
35839 ** Expression p is a QNUMBER (quoted number). Dequote the value in p->u.zToken
35844 assert( p!=0 || pParse->db->mallocFailed ); in sqlite3DequoteNumber()
35846 const char *pIn = p->u.zToken; in sqlite3DequoteNumber()
35847 char *pOut = p->u.zToken; in sqlite3DequoteNumber()
35850 assert( p->op==TK_QNUMBER ); in sqlite3DequoteNumber()
35851 p->op = TK_INTEGER; in sqlite3DequoteNumber()
35855 if( *pIn=='e' || *pIn=='E' || *pIn=='.' ) p->op = TK_FLOAT; in sqlite3DequoteNumber()
35857 if( (bHex==0 && (!sqlite3Isdigit(pIn[-1]) || !sqlite3Isdigit(pIn[1]))) in sqlite3DequoteNumber()
35858 || (bHex==1 && (!sqlite3Isxdigit(pIn[-1]) || !sqlite3Isxdigit(pIn[1]))) in sqlite3DequoteNumber()
35860 sqlite3ErrorMsg(pParse, "unrecognized token: \"%s\"", p->u.zToken); in sqlite3DequoteNumber()
35864 if( bHex ) p->op = TK_INTEGER; in sqlite3DequoteNumber()
35866 /* tag-20240227-a: If after dequoting, the number is an integer that in sqlite3DequoteNumber()
35868 ** parts of the code expect this. See also tag-20240227-b. */ in sqlite3DequoteNumber()
35869 if( p->op==TK_INTEGER && sqlite3GetInt32(p->u.zToken, &iValue) ){ in sqlite3DequoteNumber()
35870 p->u.iValue = iValue; in sqlite3DequoteNumber()
35871 p->flags |= EP_IntValue; in sqlite3DequoteNumber()
35880 ** "abc" -> abc
35881 ** "ab""cd" -> (not possible because of the interior "")
35885 ** is always a no-op.
35889 if( p->n<2 ) return; in sqlite3DequoteToken()
35890 if( !sqlite3Isquote(p->z[0]) ) return; in sqlite3DequoteToken()
35891 for(i=1; i<p->n-1; i++){ in sqlite3DequoteToken()
35892 if( sqlite3Isquote(p->z[i]) ) return; in sqlite3DequoteToken()
35894 p->n -= 2; in sqlite3DequoteToken()
35895 p->z++; in sqlite3DequoteToken()
35902 p->z = z; in sqlite3TokenInit()
35903 p->n = sqlite3Strlen30(z); in sqlite3TokenInit()
35906 /* Convenient short-hand */
35913 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
35915 ** the contents of two buffers containing UTF-8 strings in a
35916 ** case-independent fashion, using the same definition of "case
35921 return zRight ? -1 : 0; in sqlite3_stricmp()
35938 c = (int)UpperToLower[c] - (int)UpperToLower[x]; in sqlite3StrICmp()
35949 return zRight ? -1 : 0; in sqlite3_strnicmp()
35955 while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; } in sqlite3_strnicmp()
35956 return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b]; in sqlite3_strnicmp()
35960 ** Compute an 8-bit hash on a string that is insensitive to case differences
35972 /* Double-Double multiplication. (x[0],x[1]) *= (y,yy)
35975 ** T. J. Dekker, "A Floating-Point Technique for Extending the
35976 ** Available Precision". 1971-07-26.
35982 ** binary64 rather than be carried around in an extended-precision in dekkerMul2()
35993 tx = x[0] - hx; in dekkerMul2()
35997 ty = y - hy; in dekkerMul2()
36001 cc = p - c + q + tx*ty; in dekkerMul2()
36004 x[1] = c - x[0]; in dekkerMul2()
36009 ** The string z[] is an text representation of a real number.
36013 ** uses the encoding enc. The string is not necessarily zero-terminated.
36021 ** -1 => Not a valid number, but has a valid prefix which
36022 ** includes a decimal point and/or an eNNN clause
36026 ** [+-]digits[E[+-]digits]
36027 ** [+-]digits.[digits][E[+-]digits]
36028 ** [+-].digits[E[+-]digits]
36050 int eValid = 1; /* True exponent is either not used or is well-formed */ in sqlite3AtoF()
36052 int eType = 1; /* 1: pure integer, 2+: fractional -1 or less: bad UTF16 */ in sqlite3AtoF()
36053 u64 s2; /* round-tripped significand */ in sqlite3AtoF()
36057 *pResult = 0.0; /* Default return value, in case of an error */ in sqlite3AtoF()
36070 for(i=3-enc; i<length && z[i]==0; i+=2){} in sqlite3AtoF()
36071 if( i<length ) eType = -100; in sqlite3AtoF()
36081 if( *z=='-' ){ in sqlite3AtoF()
36082 sign = -1; in sqlite3AtoF()
36090 s = s*10 + (*z - '0'); in sqlite3AtoF()
36092 if( s>=((LARGEST_UINT64-9)/10) ){ in sqlite3AtoF()
36093 /* skip non-significant significand digits in sqlite3AtoF()
36107 if( s<((LARGEST_UINT64-9)/10) ){ in sqlite3AtoF()
36108 s = s*10 + (*z - '0'); in sqlite3AtoF()
36109 d--; in sqlite3AtoF()
36126 if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/ in sqlite3AtoF()
36129 if( *z=='-' ){ in sqlite3AtoF()
36130 esign = -1; in sqlite3AtoF()
36137 e = e<10000 ? (e*10 + (*z - '0')) : 10000; in sqlite3AtoF()
36149 *pResult = sign<0 ? -0.0 : +0.0; in sqlite3AtoF()
36157 while( e>0 && s<((LARGEST_UINT64-0x7ff)/10) ){ in sqlite3AtoF()
36159 e--; in sqlite3AtoF()
36177 rr[1] = s>=s2 ? (double)(s - s2) : -(double)(s2 - s); in sqlite3AtoF()
36181 assert( rr[1]<=1.0e-10*rr[0] ); /* Equal only when rr[0]==0.0 */ in sqlite3AtoF()
36185 e -= 100; in sqlite3AtoF()
36186 dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83); in sqlite3AtoF()
36189 e -= 10; in sqlite3AtoF()
36193 e -= 1; in sqlite3AtoF()
36197 while( e<=-100 ){ in sqlite3AtoF()
36199 dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117); in sqlite3AtoF()
36201 while( e<=-10 ){ in sqlite3AtoF()
36203 dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27); in sqlite3AtoF()
36205 while( e<=-1 ){ in sqlite3AtoF()
36207 dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18); in sqlite3AtoF()
36212 if( sign<0 ) *pResult = -*pResult; in sqlite3AtoF()
36216 /* return true if number and no extra non-whitespace characters after */ in sqlite3AtoF()
36220 return -1; in sqlite3AtoF()
36233 ** Render an signed 64-bit integer as text. Store the result in zOut[] and
36245 x = (v==SMALLEST_INT64) ? ((u64)1)<<63 : (u64)-v; in sqlite3Int64ToText()
36249 i = sizeof(zTemp)-2; in sqlite3Int64ToText()
36250 zTemp[sizeof(zTemp)-1] = 0; in sqlite3Int64ToText()
36251 while( 1 /*exit-by-break*/ ){ in sqlite3Int64ToText()
36255 i--; in sqlite3Int64ToText()
36257 if( v<0 ) zTemp[--i] = '-'; in sqlite3Int64ToText()
36258 memcpy(zOut, &zTemp[i], sizeof(zTemp)-i); in sqlite3Int64ToText()
36259 return sizeof(zTemp)-1-i; in sqlite3Int64ToText()
36263 ** Compare the 19-character string zNum against the text representation
36274 ** will return -8.
36282 c = (zNum[i*incr]-pow63[i])*10; in compare2pow63()
36285 c = zNum[18*incr] - '8'; in compare2pow63()
36286 testcase( c==(-1) ); in compare2pow63()
36294 ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
36299 ** -1 Not even a prefix of the input text looks like an integer
36300 ** 0 Successful transformation. Fits in a 64-bit signed integer.
36301 ** 1 Excess non-space text after the integer value
36302 ** 2 Integer too large for a 64-bit signed integer or is malformed
36306 ** The string is not necessarily zero-terminated. The encoding is
36315 int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */ in sqlite3Atoi64()
36326 for(i=3-enc; i<length && zNum[i]==0; i+=2){} in sqlite3Atoi64()
36333 if( *zNum=='-' ){ in sqlite3Atoi64()
36343 u = u*10 + c - '0'; in sqlite3Atoi64()
36350 ** from clang and -fsanitize=undefined. This test and assignment make in sqlite3Atoi64()
36352 ** them, but we must appease the undefined-behavior pharisees. */ in sqlite3Atoi64()
36355 *pNum = -(i64)u; in sqlite3Atoi64()
36361 rc = -1; in sqlite3Atoi64()
36362 }else if( nonNum ){ /* UTF16 with high-order bytes non-zero */ in sqlite3Atoi64()
36368 rc = 1; /* Extra non-space text after the integer */ in sqlite3Atoi64()
36379 /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */ in sqlite3Atoi64()
36393 assert( u-1==LARGEST_INT64 ); in sqlite3Atoi64()
36401 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
36402 ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
36407 ** 0 Successful transformation. Fits in a 64-bit signed integer.
36409 ** 2 Integer too large for a 64-bit signed integer or is malformed
36424 if( k-i>16 ) return 2; in sqlite3DecOrHexToI64()
36430 int n = (int)(0x3fffffff&strspn(z,"+- \n\t0123456789")); in sqlite3DecOrHexToI64()
36437 ** If zNum represents an integer that will fit in 32-bits, then set
36442 ** Any non-numeric characters that following zNum are ignored.
36444 ** input number to be zero-terminated.
36450 if( zNum[0]=='-' ){ in sqlite3GetInt32()
36477 for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){ in sqlite3GetInt32()
36484 ** 2^31 -> 2147483648 in sqlite3GetInt32()
36490 testcase( v-neg==2147483647 ); in sqlite3GetInt32()
36491 if( v-neg>2147483647 ){ in sqlite3GetInt32()
36495 v = -v; in sqlite3GetInt32()
36502 ** Return a 32-bit integer value extracted from a string. If the
36503 ** string is not an integer, just return 0.
36512 ** Decode a floating-point value into an approximate decimal
36515 ** If iRound<=0 then round to -iRound significant digits to the
36524 ** stored in p->z[] which is a often (but not always) a pointer
36525 ** into the middle of p->zBuf[]. There are p->n significant digits.
36526 ** The p->z[] array is *not* zero-terminated.
36534 p->isSpecial = 0; in sqlite3FpDecode()
36535 p->z = p->zBuf; in sqlite3FpDecode()
36541 p->sign = '-'; in sqlite3FpDecode()
36542 r = -r; in sqlite3FpDecode()
36544 p->sign = '+'; in sqlite3FpDecode()
36545 p->n = 1; in sqlite3FpDecode()
36546 p->iDP = 1; in sqlite3FpDecode()
36547 p->z = "0"; in sqlite3FpDecode()
36550 p->sign = '+'; in sqlite3FpDecode()
36555 p->isSpecial = 1 + (v!=0x7ff0000000000000LL); in sqlite3FpDecode()
36556 p->n = 0; in sqlite3FpDecode()
36557 p->iDP = 0; in sqlite3FpDecode()
36564 ** Use Dekker-style double-double computation to increase the in sqlite3FpDecode()
36577 dekkerMul2(rr, 1.0e-100, -1.99918998026028836196e-117); in sqlite3FpDecode()
36581 dekkerMul2(rr, 1.0e-10, -3.6432197315497741579e-27); in sqlite3FpDecode()
36585 dekkerMul2(rr, 1.0e-01, -5.5511151231257827021e-18); in sqlite3FpDecode()
36588 while( rr[0]<9.223372036854774784e-83 ){ in sqlite3FpDecode()
36589 exp -= 100; in sqlite3FpDecode()
36590 dekkerMul2(rr, 1.0e+100, -1.5902891109759918046e+83); in sqlite3FpDecode()
36593 exp -= 10; in sqlite3FpDecode()
36597 exp -= 1; in sqlite3FpDecode()
36601 v = rr[1]<0.0 ? (u64)rr[0]-(u64)(-rr[1]) : (u64)rr[0]+(u64)rr[1]; in sqlite3FpDecode()
36604 i = sizeof(p->zBuf)-1; in sqlite3FpDecode()
36606 while( v ){ p->zBuf[i--] = (v%10) + '0'; v /= 10; } in sqlite3FpDecode()
36607 assert( i>=0 && i<sizeof(p->zBuf)-1 ); in sqlite3FpDecode()
36608 p->n = sizeof(p->zBuf) - 1 - i; in sqlite3FpDecode()
36609 assert( p->n>0 ); in sqlite3FpDecode()
36610 assert( p->n<sizeof(p->zBuf) ); in sqlite3FpDecode()
36611 p->iDP = p->n + exp; in sqlite3FpDecode()
36613 iRound = p->iDP - iRound; in sqlite3FpDecode()
36614 if( iRound==0 && p->zBuf[i+1]>='5' ){ in sqlite3FpDecode()
36616 p->zBuf[i--] = '0'; in sqlite3FpDecode()
36617 p->n++; in sqlite3FpDecode()
36618 p->iDP++; in sqlite3FpDecode()
36621 if( iRound>0 && (iRound<p->n || p->n>mxRound) ){ in sqlite3FpDecode()
36622 char *z = &p->zBuf[i+1]; in sqlite3FpDecode()
36624 p->n = iRound; in sqlite3FpDecode()
36626 int j = iRound-1; in sqlite3FpDecode()
36627 while( 1 /*exit-by-break*/ ){ in sqlite3FpDecode()
36632 p->z[i--] = '1'; in sqlite3FpDecode()
36633 p->n++; in sqlite3FpDecode()
36634 p->iDP++; in sqlite3FpDecode()
36637 j--; in sqlite3FpDecode()
36642 p->z = &p->zBuf[i+1]; in sqlite3FpDecode()
36643 assert( i+p->n < sizeof(p->zBuf) ); in sqlite3FpDecode()
36644 assert( p->n>0 ); in sqlite3FpDecode()
36645 while( p->z[p->n-1]=='0' ){ in sqlite3FpDecode()
36646 p->n--; in sqlite3FpDecode()
36647 assert( p->n>0 ); in sqlite3FpDecode()
36652 ** Try to convert z into an unsigned 32-bit integer. Return true on
36653 ** success and false if there is an error.
36661 v = v*10 + z[i] - '0'; in sqlite3GetUInt32()
36670 ** The variable-length integer encoding is as follows:
36677 ** 7 bits - A
36678 ** 14 bits - BA
36679 ** 21 bits - BBA
36680 ** 28 bits - BBBA
36681 ** 35 bits - BBBBA
36682 ** 42 bits - BBBBBA
36683 ** 49 bits - BBBBBBA
36684 ** 56 bits - BBBBBBBA
36685 ** 64 bits - BBBBBBBBC
36689 ** Write a 64-bit variable-length integer to memory starting at p[0].
36693 ** A variable-length integer consists of the lower 7 bits of each byte
36704 for(i=7; i>=0; i--){ in putVarint64()
36717 for(i=0, j=n-1; j>=0; j--, i++){ in putVarint64()
36749 ** Read a 64-bit variable-length integer from memory starting at p[0].
36892 b = p[-4]; in sqlite3GetVarint()
36903 ** Read a 32-bit variable-length integer from memory starting at p[0].
36906 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
36910 ** single-byte case. All code should use the MACRO version as
36911 ** this function assumes the single-byte case has already been handled.
36917 /* Assume that the single-byte case has already been handled by in sqlite3GetVarint32()
36922 /* This is the two-byte case */ in sqlite3GetVarint32()
36927 /* This is the three-byte case */ in sqlite3GetVarint32()
36944 ** 64-bit integer.
36954 ** Read or write a four-byte big-endian integer value.
36994 ** Translate a single byte of Hex into an integer.
37021 n--; in sqlite3HexToBlob()
37033 ** Log an error that is an API call on a connection pointer that should
37056 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
37064 eOpenState = db->eOpenState; in sqlite3SafetyCheckOk()
37077 eOpenState = db->eOpenState; in sqlite3SafetyCheckSickOrOk()
37090 ** Attempt to add, subtract, or multiply the 64-bit signed value iB against
37091 ** the other 64-bit signed integer at *pA and store the result in *pA.
37092 ** Return 0 on success. Or if the operation would have resulted in an
37101 testcase( iB==-1 ); testcase( iB==0 ); in sqlite3AddInt64()
37103 testcase( iA>0 && LARGEST_INT64 - iA == iB ); in sqlite3AddInt64()
37104 testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 ); in sqlite3AddInt64()
37105 if( iA>0 && LARGEST_INT64 - iA < iB ) return 1; in sqlite3AddInt64()
37107 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 ); in sqlite3AddInt64()
37108 testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 ); in sqlite3AddInt64()
37109 if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1; in sqlite3AddInt64()
37121 testcase( (*pA)==(-1) ); testcase( (*pA)==0 ); in sqlite3SubInt64()
37123 *pA -= iB; in sqlite3SubInt64()
37126 return sqlite3AddInt64(pA, -iB); in sqlite3SubInt64()
37144 if( -iA>LARGEST_INT64/-iB ) return 1; in sqlite3MulInt64()
37153 ** Compute the absolute value of a 32-bit signed integer, if possible. Or
37154 ** if the integer has a value of -2147483648, return +2147483647
37159 return -x; in sqlite3AbsInt32()
37164 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
37170 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
37175 ** test.db-journal => test.nal
37176 ** test.db-wal => test.wal
37177 ** test.db-shm => test.shm
37178 ** test.db-mj7f3319fa => test.9fa
37187 for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){} in sqlite3FileSuffix3()
37188 if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4); in sqlite3FileSuffix3()
37194 ** Find (an approximate) sum of two LogEst values. This computation is
37206 5, 5, 5, /* 12-14 */ in sqlite3LogEstAdd()
37207 4, 4, 4, 4, /* 15-18 */ in sqlite3LogEstAdd()
37208 3, 3, 3, 3, 3, 3, /* 19-24 */ in sqlite3LogEstAdd()
37209 2, 2, 2, 2, 2, 2, 2, /* 25-31 */ in sqlite3LogEstAdd()
37214 return a+x[a-b]; in sqlite3LogEstAdd()
37218 return b+x[b-a]; in sqlite3LogEstAdd()
37223 ** Convert an integer into a LogEst. In other words, compute an
37231 while( x<8 ){ y -= 10; x <<= 1; } in sqlite3LogEst()
37234 int i = 60 - __builtin_clzll(x); in sqlite3LogEst()
37238 while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/ in sqlite3LogEst()
37242 return a[x&7] + y - 10; in sqlite3LogEst()
37247 ** In other words, compute an approximation for 10*log2(x).
37256 e = (a>>52) - 1022; in sqlite3LogEstFromDouble()
37261 ** Convert a LogEst into an integer.
37267 if( n>=5 ) n -= 2; in sqlite3LogEstToInt()
37268 else if( n>=1 ) n -= 1; in sqlite3LogEstToInt()
37270 return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x); in sqlite3LogEstToInt()
37275 ** VList object be reallocated, so return the new VList. If an OOM
37277 ** db->mallocFailed flag is set.
37279 ** A VList is really just an array of integers. To destroy a VList,
37290 ** is always zero-terminated.
37305 ** VList are taken. When that happens, nAlloc is set to zero as an
37389 ** This is the implementation of generic hash-tables
37402 pNew->first = 0; in sqlite3HashInit()
37403 pNew->count = 0; in sqlite3HashInit()
37404 pNew->htsize = 0; in sqlite3HashInit()
37405 pNew->ht = 0; in sqlite3HashInit()
37416 elem = pH->first; in sqlite3HashClear()
37417 pH->first = 0; in sqlite3HashClear()
37418 sqlite3_free(pH->ht); in sqlite3HashClear()
37419 pH->ht = 0; in sqlite3HashClear()
37420 pH->htsize = 0; in sqlite3HashClear()
37422 HashElem *next_elem = elem->next; in sqlite3HashClear()
37426 pH->count = 0; in sqlite3HashClear()
37434 while( z[0] ){ /*OPTIMIZATION-IF-TRUE*/ in strHash()
37437 ** (2**32)*golden_ratio, where golden_ratio = (sqrt(5) - 1)/2. in strHash()
37463 pHead = pEntry->count ? pEntry->chain : 0; in insertElement()
37464 pEntry->count++; in insertElement()
37465 pEntry->chain = pNew; in insertElement()
37470 pNew->next = pHead; in insertElement()
37471 pNew->prev = pHead->prev; in insertElement()
37472 if( pHead->prev ){ pHead->prev->next = pNew; } in insertElement()
37473 else { pH->first = pNew; } in insertElement()
37474 pHead->prev = pNew; in insertElement()
37476 pNew->next = pH->first; in insertElement()
37477 if( pH->first ){ pH->first->prev = pNew; } in insertElement()
37478 pNew->prev = 0; in insertElement()
37479 pH->first = pNew; in insertElement()
37498 if( new_size==pH->htsize ) return 0; in rehash()
37514 sqlite3_free(pH->ht); in rehash()
37515 pH->ht = new_ht; in rehash()
37516 pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht); in rehash()
37518 for(elem=pH->first, pH->first=0; elem; elem = next_elem){ in rehash()
37519 next_elem = elem->next; in rehash()
37520 insertElement(pH, &new_ht[elem->h % new_size], elem); in rehash()
37525 /* This function (for internal use only) locates an element in an
37541 if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/ in findElementWithHash()
37543 pEntry = &pH->ht[h % pH->htsize]; in findElementWithHash()
37544 elem = pEntry->chain; in findElementWithHash()
37545 count = pEntry->count; in findElementWithHash()
37547 elem = pH->first; in findElementWithHash()
37548 count = pH->count; in findElementWithHash()
37553 if( h==elem->h && sqlite3StrICmp(elem->pKey,pKey)==0 ){ in findElementWithHash()
37556 elem = elem->next; in findElementWithHash()
37557 count--; in findElementWithHash()
37570 if( elem->prev ){ in removeElement()
37571 elem->prev->next = elem->next; in removeElement()
37573 pH->first = elem->next; in removeElement()
37575 if( elem->next ){ in removeElement()
37576 elem->next->prev = elem->prev; in removeElement()
37578 if( pH->ht ){ in removeElement()
37579 pEntry = &pH->ht[elem->h % pH->htsize]; in removeElement()
37580 if( pEntry->chain==elem ){ in removeElement()
37581 pEntry->chain = elem->next; in removeElement()
37583 assert( pEntry->count>0 ); in removeElement()
37584 pEntry->count--; in removeElement()
37587 pH->count--; in removeElement()
37588 if( pH->count==0 ){ in removeElement()
37589 assert( pH->first==0 ); in removeElement()
37590 assert( pH->count==0 ); in removeElement()
37595 /* Attempt to locate an element of the hash table pH with a key
37602 return findElementWithHash(pH, pKey, 0)->data; in sqlite3HashFind()
37605 /* Insert an element into the hash table pH. The key is pKey
37627 if( elem->data ){ in sqlite3HashInsert()
37628 void *old_data = elem->data; in sqlite3HashInsert()
37632 elem->data = data; in sqlite3HashInsert()
37633 elem->pKey = pKey; in sqlite3HashInsert()
37640 new_elem->pKey = pKey; in sqlite3HashInsert()
37641 new_elem->h = h; in sqlite3HashInsert()
37642 new_elem->data = data; in sqlite3HashInsert()
37643 pH->count++; in sqlite3HashInsert()
37644 if( pH->count>=5 && pH->count > 2*pH->htsize ){ in sqlite3HashInsert()
37645 rehash(pH, pH->count*3); in sqlite3HashInsert()
37647 insertElement(pH, pH->ht ? &pH->ht[new_elem->h % pH->htsize] : 0, new_elem); in sqlite3HashInsert()
37715 /* 50 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"), in sqlite3OpcodeName()
37725 /* 60 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]--, goto P2"), in sqlite3OpcodeName()
37726 /* 61 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"), in sqlite3OpcodeName()
37755 /* 90 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"), in sqlite3OpcodeName()
37773 /* 108 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"), in sqlite3OpcodeName()
37789 /* 124 */ "SeekScan" OpHelp("Scan-ahead up to P1 rows"), in sqlite3OpcodeName()
37825 /* 160 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"), in sqlite3OpcodeName()
37863 ** 2022-09-06
37874 ** This file contains an experimental VFS layer that operates on a
37906 ** VFS - the database and the rollback journal.
37915 sqlite3_int64 szDb; /* Database file size. -1 means unknown */
38030 /* Forward declarations for the low-level storage engine
38037 /* Expand the key name with an appropriate prefix and put the result
38046 sqlite3_snprintf(KVSTORAGE_KEY_SZ, zKeyOut, "kvvfs-%s-%s", zClass, zKeyIn); in kvstorageMakeKey()
38050 ** underlying key/value store to use - either "local" or "session".
38052 ** Both zKey and zData are zero-terminated pure text strings.
38066 SQLITE_KV_TRACE(("KVVFS-WRITE %-15s (%d) %.50s%s\n", zXKey, in kvstorageWrite()
38079 ** this routine is a no-op.
38085 SQLITE_KV_TRACE(("KVVFS-DELETE %-15s\n", zXKey)); in kvstorageDelete()
38096 ** not counting the final zero terminator. Return -1 if the key does
38116 SQLITE_KV_TRACE(("KVVFS-READ %-15s (-1)\n", zXKey)); in kvstorageRead()
38117 return -1; in kvstorageRead()
38123 SQLITE_KV_TRACE(("KVVFS-READ %-15s (%d)\n", zXKey, in kvstorageRead()
38132 SQLITE_KV_TRACE(("KVVFS-READ %-15s (-1)\n", zXKey)); in kvstorageRead()
38133 return -1; in kvstorageRead()
38135 sqlite3_int64 n = fread(zBuf, 1, nBuf-1, fd); in kvstorageRead()
38138 SQLITE_KV_TRACE(("KVVFS-READ %-15s (%lld) %.50s%s\n", zXKey, in kvstorageRead()
38145 ** An internal level of indirection which enables us to replace the
38150 ** concerns, so it does not need an iVersion member. This file is
38165 ** for JavaScript-side implementations in WASM builds. In such builds
38194 ** ---------------
38196 ** * Non-zero bytes are encoded as upper-case hexadecimal
38198 ** * A sequence of one or more zero-bytes that are not at the
38199 ** beginning of the buffer are encoded as a little-endian
38200 ** base-26 number using a..z. "a" means 0. "b" means 1,
38204 ** of hexadecimal and base-26 numbers, it is always clear where
38216 /* A sequence of 1 or more zeros is stored as a little-endian in kvvfsEncode()
38217 ** base-26 number using a..z as the digits. So one zero is "b". in kvvfsEncode()
38223 i += k-1; in kvvfsEncode()
38235 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38236 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38237 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38238 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
38239 -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38240 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38241 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38242 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38244 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38245 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38246 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38247 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38248 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38249 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38250 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
38251 -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
38274 n += (c - 'a')*mult; in kvvfsDecode()
38278 if( j+n>nOut ) return -1; in kvvfsDecode()
38294 ** Decode a complete journal file. Allocate space in pFile->aJrnl
38295 ** and store the decoding there. Or leave pFile->aJrnl set to NULL
38296 ** if an error is encountered.
38298 ** The first few characters of the text encoding will be a little-endian
38299 ** base-26 number (digits a..z) that is the total number of bytes
38300 ** in the decoded journal file image. This base-26 number is followed
38302 ** separator is required to act as a terminator for the base-26 number.
38305 KVVfsFile *pFile, /* Store decoding in pFile->aJrnl */ in kvvfsDecodeJournal()
38306 const char *zTxt, /* Text encoding. Zero-terminated */ in kvvfsDecodeJournal()
38314 n += (zTxt[i] - 'a')*mult; in kvvfsDecodeJournal()
38317 sqlite3_free(pFile->aJrnl); in kvvfsDecodeJournal()
38318 pFile->aJrnl = sqlite3_malloc64( n ); in kvvfsDecodeJournal()
38319 if( pFile->aJrnl==0 ){ in kvvfsDecodeJournal()
38320 pFile->nJrnl = 0; in kvvfsDecodeJournal()
38323 pFile->nJrnl = n; in kvvfsDecodeJournal()
38324 n = kvvfsDecode(zTxt+i, pFile->aJrnl, pFile->nJrnl); in kvvfsDecodeJournal()
38325 if( n<pFile->nJrnl ){ in kvvfsDecodeJournal()
38326 sqlite3_free(pFile->aJrnl); in kvvfsDecodeJournal()
38327 pFile->aJrnl = 0; in kvvfsDecodeJournal()
38328 pFile->nJrnl = 0; in kvvfsDecodeJournal()
38338 sqlite3KvvfsMethods.xRead(pFile->zClass, "sz", zData, sizeof(zData)-1); in kvvfsReadFileSize()
38344 return sqlite3KvvfsMethods.xWrite(pFile->zClass, "sz", zData); in kvvfsWriteFileSize()
38350 ** Close an kvvfs-file.
38355 SQLITE_KV_LOG(("xClose %s %s\n", pFile->zClass, in kvvfsClose()
38356 pFile->isJournal ? "journal" : "db")); in kvvfsClose()
38357 sqlite3_free(pFile->aJrnl); in kvvfsClose()
38358 sqlite3_free(pFile->aData); in kvvfsClose()
38363 ** Read from the -journal file.
38372 assert( pFile->isJournal ); in kvvfsReadJrnl()
38373 SQLITE_KV_LOG(("xRead('%s-journal',%d,%lld)\n", pFile->zClass, iAmt, iOfst)); in kvvfsReadJrnl()
38374 if( pFile->aJrnl==0 ){ in kvvfsReadJrnl()
38375 int szTxt = kvstorageRead(pFile->zClass, "jrnl", 0, 0); in kvvfsReadJrnl()
38382 kvstorageRead(pFile->zClass, "jrnl", aTxt, szTxt+1); in kvvfsReadJrnl()
38385 if( pFile->aJrnl==0 ) return SQLITE_IOERR; in kvvfsReadJrnl()
38387 if( iOfst+iAmt>pFile->nJrnl ){ in kvvfsReadJrnl()
38390 memcpy(zBuf, pFile->aJrnl+iOfst, iAmt); in kvvfsReadJrnl()
38407 char *aData = pFile->aData; in kvvfsReadDb()
38410 SQLITE_KV_LOG(("xRead('%s-db',%d,%lld)\n", pFile->zClass, iAmt, iOfst)); in kvvfsReadDb()
38415 if( (iAmt & (iAmt-1))!=0 || iAmt<512 || iAmt>65536 ){ in kvvfsReadDb()
38418 pFile->szPage = iAmt; in kvvfsReadDb()
38424 got = sqlite3KvvfsMethods.xRead(pFile->zClass, zKey, in kvvfsReadDb()
38425 aData, SQLITE_KVOS_SZ-1); in kvvfsReadDb()
38433 n = kvvfsDecode(aData, &aData[2000], SQLITE_KVOS_SZ-2000); in kvvfsReadDb()
38445 memset(zBuf+n, 0, iAmt-n); in kvvfsReadDb()
38453 ** Write into the -journal file.
38463 SQLITE_KV_LOG(("xWrite('%s-journal',%d,%lld)\n", pFile->zClass, iAmt, iOfst)); in kvvfsWriteJrnl()
38465 if( pFile->aJrnl==0 || pFile->nJrnl<iEnd ){ in kvvfsWriteJrnl()
38466 char *aNew = sqlite3_realloc(pFile->aJrnl, iEnd); in kvvfsWriteJrnl()
38470 pFile->aJrnl = aNew; in kvvfsWriteJrnl()
38471 if( pFile->nJrnl<iOfst ){ in kvvfsWriteJrnl()
38472 memset(pFile->aJrnl+pFile->nJrnl, 0, iOfst-pFile->nJrnl); in kvvfsWriteJrnl()
38474 pFile->nJrnl = iEnd; in kvvfsWriteJrnl()
38476 memcpy(pFile->aJrnl+iOfst, zBuf, iAmt); in kvvfsWriteJrnl()
38492 char *aData = pFile->aData; in kvvfsWriteDb()
38493 SQLITE_KV_LOG(("xWrite('%s-db',%d,%lld)\n", pFile->zClass, iAmt, iOfst)); in kvvfsWriteDb()
38495 assert( (iAmt & (iAmt-1))==0 ); in kvvfsWriteDb()
38496 assert( pFile->szPage<0 || pFile->szPage==iAmt ); in kvvfsWriteDb()
38497 pFile->szPage = iAmt; in kvvfsWriteDb()
38501 if( sqlite3KvvfsMethods.xWrite(pFile->zClass, zKey, aData) ){ in kvvfsWriteDb()
38504 if( iOfst+iAmt > pFile->szDb ){ in kvvfsWriteDb()
38505 pFile->szDb = iOfst + iAmt; in kvvfsWriteDb()
38511 ** Truncate an kvvfs-file.
38515 SQLITE_KV_LOG(("xTruncate('%s-journal',%lld)\n", pFile->zClass, size)); in kvvfsTruncateJrnl()
38517 sqlite3KvvfsMethods.xDelete(pFile->zClass, "jrnl"); in kvvfsTruncateJrnl()
38518 sqlite3_free(pFile->aJrnl); in kvvfsTruncateJrnl()
38519 pFile->aJrnl = 0; in kvvfsTruncateJrnl()
38520 pFile->nJrnl = 0; in kvvfsTruncateJrnl()
38525 if( pFile->szDb>size in kvvfsTruncateDb()
38526 && pFile->szPage>0 in kvvfsTruncateDb()
38527 && (size % pFile->szPage)==0 in kvvfsTruncateDb()
38531 SQLITE_KV_LOG(("xTruncate('%s-db',%lld)\n", pFile->zClass, size)); in kvvfsTruncateDb()
38532 pgno = 1 + size/pFile->szPage; in kvvfsTruncateDb()
38533 pgnoMax = 2 + pFile->szDb/pFile->szPage; in kvvfsTruncateDb()
38536 sqlite3KvvfsMethods.xDelete(pFile->zClass, zKey); in kvvfsTruncateDb()
38539 pFile->szDb = size; in kvvfsTruncateDb()
38546 ** Sync an kvvfs-file.
38552 SQLITE_KV_LOG(("xSync('%s-journal')\n", pFile->zClass)); in kvvfsSyncJrnl()
38553 if( pFile->nJrnl<=0 ){ in kvvfsSyncJrnl()
38556 zOut = sqlite3_malloc64( pFile->nJrnl*2 + 50 ); in kvvfsSyncJrnl()
38560 n = pFile->nJrnl; in kvvfsSyncJrnl()
38567 kvvfsEncode(pFile->aJrnl, pFile->nJrnl, &zOut[i]); in kvvfsSyncJrnl()
38568 i = sqlite3KvvfsMethods.xWrite(pFile->zClass, "jrnl", zOut); in kvvfsSyncJrnl()
38577 ** Return the current file-size of an kvvfs-file.
38581 SQLITE_KV_LOG(("xFileSize('%s-journal')\n", pFile->zClass)); in kvvfsFileSizeJrnl()
38582 *pSize = pFile->nJrnl; in kvvfsFileSizeJrnl()
38587 SQLITE_KV_LOG(("xFileSize('%s-db')\n", pFile->zClass)); in kvvfsFileSizeDb()
38588 if( pFile->szDb>=0 ){ in kvvfsFileSizeDb()
38589 *pSize = pFile->szDb; in kvvfsFileSizeDb()
38597 ** Lock an kvvfs-file.
38601 assert( !pFile->isJournal ); in kvvfsLock()
38602 SQLITE_KV_LOG(("xLock(%s,%d)\n", pFile->zClass, eLock)); in kvvfsLock()
38605 pFile->szDb = kvvfsReadFileSize(pFile); in kvvfsLock()
38611 ** Unlock an kvvfs-file.
38615 assert( !pFile->isJournal ); in kvvfsUnlock()
38616 SQLITE_KV_LOG(("xUnlock(%s,%d)\n", pFile->zClass, eLock)); in kvvfsUnlock()
38618 pFile->szDb = -1; in kvvfsUnlock()
38624 ** Check if another file-handle holds a RESERVED lock on an kvvfs-file.
38633 ** File control method. For custom operations on an kvvfs-file.
38644 SQLITE_KV_LOG(("xSync('%s-db')\n", pFile->zClass)); in kvvfsFileControlDb()
38645 if( pFile->szDb>0 && 0!=kvvfsWriteFileSize(pFile, pFile->szDb) ){ in kvvfsFileControlDb()
38654 ** Return the sector-size in bytes for an kvvfs-file.
38661 ** Return the device characteristic flags supported by an kvvfs-file.
38670 ** Open an kvvfs file handle.
38685 pFile->isJournal = 0; in kvvfsOpen()
38686 pFile->base.pMethods = &kvvfs_db_io_methods; in kvvfsOpen()
38688 if( strcmp(zName, "local-journal")==0 in kvvfsOpen()
38689 || strcmp(zName, "session-journal")==0 in kvvfsOpen()
38691 pFile->isJournal = 1; in kvvfsOpen()
38692 pFile->base.pMethods = &kvvfs_jrnl_io_methods; in kvvfsOpen()
38697 pFile->zClass = "session"; in kvvfsOpen()
38699 pFile->zClass = "local"; in kvvfsOpen()
38701 pFile->aData = sqlite3_malloc64(SQLITE_KVOS_SZ); in kvvfsOpen()
38702 if( pFile->aData==0 ){ in kvvfsOpen()
38705 pFile->aJrnl = 0; in kvvfsOpen()
38706 pFile->nJrnl = 0; in kvvfsOpen()
38707 pFile->szPage = -1; in kvvfsOpen()
38708 pFile->szDb = -1; in kvvfsOpen()
38714 ** ensure the file-system modifications are synced to disk before
38718 if( strcmp(zPath, "local-journal")==0 ){ in kvvfsDelete()
38721 if( strcmp(zPath, "session-journal")==0 ){ in kvvfsDelete()
38738 if( strcmp(zPath, "local-journal")==0 ){ in kvvfsAccess()
38741 if( strcmp(zPath, "session-journal")==0 ){ in kvvfsAccess()
38774 if( nOut<nPath+1 ) nPath = nOut - 1; in kvvfsFullPathname()
38826 ** This routine is called initialize the KV-vfs as the default VFS.
38856 ** This file contains the VFS implementation for unix-like operating systems
38862 ** use flock(), dot-files, various proprietary locking schemas, or simply
38872 ** * General-purpose declarations and utility functions.
38876 ** + for no-op locks
38877 ** + for dot-file locks
38885 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
38898 ** 3. Dot-file locking,
38958 ** -DHAVE_GETHOSTUUID=0
38959 ** -DHAVE_GETHOSTUUID=1
38962 ** -DSQLITE_ENABLE_LOCKING_STYLE.
39000 ** If we are to be thread-safe, include the pthreads header.
39021 ** Maximum supported path-length.
39040 # define SQLITE_DEFAULT_UNIX_VFS "unix-dotfile"
39041 /* ^^^ should SQLITE_DEFAULT_UNIX_VFS be "unix-none"? */
39080 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
39081 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
39086 ** structure are used to store the file descriptor while waiting for an
39109 UnixUnusedFd *pPreallocatedUnused; /* Pre-allocated UnixUnusedFd */
39137 ** transaction counter in bytes 24-27 of database files are updated
39138 ** whenever any part of the database changes. An assertion fault will
39202 ** The threadid macro resolves to the thread-id or to 0. Used for
39223 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
39224 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
39232 ** Linux-specific IOCTL magic numbers used for controlling F2FS
39250 ** which always has the same well-defined interface.
39261 ** Many system calls are accessed through pointer-to-functions so that
39290 ** DJGPP. But it is DOS - what did you expect?
39443 ** log if they come from non-root processes. So avoid calling fchown() if
39523 int i = -1; in unixNextSystemCall()
39527 for(i=0; i<ArraySize(aSyscall)-1; i++){ in unixNextSystemCall()
39555 ** The m parameter will be non-zero only when creating -wal, -journal,
39556 ** and -shm files. We want those files to have *exactly* the same
39558 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
39583 fd = -1; in robust_open()
39648 ** integer lock-type.
39667 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
39668 ** command-line option on the compiler. This code is normally
39684 if( p->l_type==F_RDLCK ){ in lockTrace()
39686 }else if( p->l_type==F_WRLCK ){ in lockTrace()
39688 }else if( p->l_type==F_UNLCK ){ in lockTrace()
39693 assert( p->l_whence==SEEK_SET ); in lockTrace()
39697 threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len, in lockTrace()
39698 (int)p->l_pid, s); in lockTrace()
39699 if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){ in lockTrace()
39712 sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n", in lockTrace()
39732 /* On Android, ftruncate() always uses 32-bit offsets, even if in robust_ftruncate()
39786 ** A pointer to an instance of the following structure can be used as a
39793 ** a performance-critical path, so it is sufficient to put these
39818 ** Changes are made in-place. Return the new name length.
39820 ** The original filename is in z[0..n-1]. Return the number of
39825 while( n>1 && z[n-1]=='/' ){ n--; } in vxworksSimplifyName()
39834 while( j>0 && z[j-1]!='/' ){ j--; } in vxworksSimplifyName()
39835 if( j>0 ){ j--; } in vxworksSimplifyName()
39866 pNew->zCanonicalName = (char*)&pNew[1]; in vxworksFindFileId()
39867 memcpy(pNew->zCanonicalName, zAbsoluteName, n+1); in vxworksFindFileId()
39868 n = vxworksSimplifyName(pNew->zCanonicalName, n); in vxworksFindFileId()
39870 /* Search for an existing entry that matching the canonical name. in vxworksFindFileId()
39875 for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){ in vxworksFindFileId()
39876 if( pCandidate->nName==n in vxworksFindFileId()
39877 && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0 in vxworksFindFileId()
39880 pCandidate->nRef++; in vxworksFindFileId()
39887 pNew->nRef = 1; in vxworksFindFileId()
39888 pNew->nName = n; in vxworksFindFileId()
39889 pNew->pNext = vxworksFileList; in vxworksFindFileId()
39901 assert( pId->nRef>0 ); in vxworksReleaseFileId()
39902 pId->nRef--; in vxworksReleaseFileId()
39903 if( pId->nRef==0 ){ in vxworksReleaseFileId()
39905 for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){} in vxworksReleaseFileId()
39907 *pp = pId->pNext; in vxworksReleaseFileId()
39932 ** an exclusive lock on fd1, then try to get an exclusive lock
39957 ** The sqlite3_file structure for POSIX is no longer just an integer file
39965 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
39971 ** a locked and an unlocked state.
39979 ** When an attempt is made to close an unixFile, if there are
39993 ** on linux - with NPTL a lock created by thread A can override locks
39994 ** in thread B. But there is no way to know at compile-time which
39996 ** compile-time whether or not thread A can override locks on thread B.
39997 ** One has to do a run-time check to discover the behavior of the
40008 ** An instance of the following structure serves as the key used
40017 ** sizes ino_t at only 32-bits instead of 64-bits. (See
40018 ** https://android-review.googlesource.com/#/c/115351/3/dist/sqlite3.c)
40019 ** To work around this, always allocate 64-bits for the inode number.
40020 ** On small machines that only have 32-bit inodes, this wastes 4 bytes,
40028 ** An instance of the following structure is allocated for each open
40032 ** structure contains a pointer to an instance of this object and this
40058 unsigned char bProcessLock; /* An exclusive process lock is held */
40087 assert( pFile->pInode ); in unixFileMutexHeld()
40088 return sqlite3_mutex_held(pFile->pInode->pLockMutex); in unixFileMutexHeld()
40091 assert( pFile->pInode ); in unixFileMutexNotheld()
40092 return sqlite3_mutex_notheld(pFile->pInode->pLockMutex); in unixFileMutexNotheld()
40098 ** This function - unixLogErrorAtLine(), is only ever called via the macro
40101 ** It is invoked after an error occurs in an OS function and errno has been
40103 ** errno and, if possible, the human-readable equivalent from strerror() or
40109 ** failed (e.g. "unlink", "open") and the associated file-system path,
40123 ** the strerror() function to obtain the human-readable error message in unixLogErrorAtLine()
40136 ** strerror_r(), which always writes an error message into aErr[]. in unixLogErrorAtLine()
40139 ** available, the error message will often be an empty string. Not a in unixLogErrorAtLine()
40144 ** int-type return, depending on its version. in unixLogErrorAtLine()
40150 strerror_r(iErrno, aErr, sizeof(aErr)-1); in unixLogErrorAtLine()
40156 /* Non-threadsafe build, use strerror(). */ in unixLogErrorAtLine()
40162 "os_unix.c:%d: (%d) %s(%s) - %s", in unixLogErrorAtLine()
40179 ** So we don't even try to recover from an EINTR. Just log the error
40185 pFile ? pFile->zPath : 0, lineno); in robust_close()
40190 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
40194 pFile->lastErrno = error; in storeLastErrno()
40198 ** Close all file descriptors accumulated in the unixInodeInfo->pUnused list.
40201 unixInodeInfo *pInode = pFile->pInode; in closePendingFds()
40205 for(p=pInode->pUnused; p; p=pNext){ in closePendingFds()
40206 pNext = p->pNext; in closePendingFds()
40207 robust_close(pFile, p->fd, __LINE__); in closePendingFds()
40210 pInode->pUnused = 0; in closePendingFds()
40220 unixInodeInfo *pInode = pFile->pInode; in releaseInodeInfo()
40224 pInode->nRef--; in releaseInodeInfo()
40225 if( pInode->nRef==0 ){ in releaseInodeInfo()
40226 assert( pInode->pShmNode==0 ); in releaseInodeInfo()
40227 sqlite3_mutex_enter(pInode->pLockMutex); in releaseInodeInfo()
40229 sqlite3_mutex_leave(pInode->pLockMutex); in releaseInodeInfo()
40230 if( pInode->pPrev ){ in releaseInodeInfo()
40231 assert( pInode->pPrev->pNext==pInode ); in releaseInodeInfo()
40232 pInode->pPrev->pNext = pInode->pNext; in releaseInodeInfo()
40235 inodeList = pInode->pNext; in releaseInodeInfo()
40237 if( pInode->pNext ){ in releaseInodeInfo()
40238 assert( pInode->pNext->pPrev==pInode ); in releaseInodeInfo()
40239 pInode->pNext->pPrev = pInode->pPrev; in releaseInodeInfo()
40241 sqlite3_mutex_free(pInode->pLockMutex); in releaseInodeInfo()
40250 ** return value might be uninitialized if an error occurs.
40254 ** Return an appropriate error code.
40263 struct stat statbuf; /* Low-level file information */ in findInodeInfo()
40268 /* Get low-level information about the file that we can used to in findInodeInfo()
40271 fd = pFile->h; in findInodeInfo()
40276 if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS; in findInodeInfo()
40282 /* On OS X on an msdos filesystem, the inode number is reported in findInodeInfo()
40283 ** incorrectly for zero-size files. See ticket #3260. To work in findInodeInfo()
40287 ** an ASCII 'S' character which also happens to be the first byte in findInodeInfo()
40292 if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){ in findInodeInfo()
40309 fileId.pId = pFile->pId; in findInodeInfo()
40315 while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){ in findInodeInfo()
40316 pInode = pInode->pNext; in findInodeInfo()
40324 memcpy(&pInode->fileId, &fileId, sizeof(fileId)); in findInodeInfo()
40326 pInode->pLockMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); in findInodeInfo()
40327 if( pInode->pLockMutex==0 ){ in findInodeInfo()
40332 pInode->nRef = 1; in findInodeInfo()
40334 pInode->pNext = inodeList; in findInodeInfo()
40335 pInode->pPrev = 0; in findInodeInfo()
40336 if( inodeList ) inodeList->pPrev = pInode; in findInodeInfo()
40339 pInode->nRef++; in findInodeInfo()
40350 return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId; in fileHasMoved()
40353 return pFile->pInode!=0 && in fileHasMoved()
40354 (osStat(pFile->zPath, &buf)!=0 in fileHasMoved()
40355 || (u64)buf.st_ino!=pFile->pInode->fileId.ino); in fileHasMoved()
40374 if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return; in verifyDbFile()
40376 rc = osFstat(pFile->h, &buf); in verifyDbFile()
40378 sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath); in verifyDbFile()
40382 sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath); in verifyDbFile()
40386 sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath); in verifyDbFile()
40390 sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath); in verifyDbFile()
40399 ** to a non-zero value otherwise *pResOut is set to zero. The return value
40400 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
40410 assert( pFile->eFileLock<=SHARED_LOCK ); in unixCheckReservedLock()
40411 sqlite3_mutex_enter(pFile->pInode->pLockMutex); in unixCheckReservedLock()
40414 if( pFile->pInode->eFileLock>SHARED_LOCK ){ in unixCheckReservedLock()
40421 if( !reserved && !pFile->pInode->bProcessLock ){ in unixCheckReservedLock()
40427 if( osFcntl(pFile->h, F_GETLK, &lock) ){ in unixCheckReservedLock()
40436 sqlite3_mutex_leave(pFile->pInode->pLockMutex); in unixCheckReservedLock()
40437 OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved)); in unixCheckReservedLock()
40447 ** Set a posix-advisory-lock.
40450 ** SQLITE_ENABLE_SETLK_TIMEOUT then the routine has an extra parameter
40451 ** which is a pointer to a unixFile. If the unixFile->iBusyTimeout
40456 ** If SQLITE_ENABLE_SETLK_TIMEOUT is not defined, then do a non-blocking
40467 int tm = pFile->iBusyTimeout; in osSetPosixAdvisoryLock()
40477 tm--; in osSetPosixAdvisoryLock()
40485 ** Attempt to set a system-lock on the file pFile. The lock is
40488 ** If the pFile was opened read/write from unix-excl, then the only lock
40489 ** ever obtained is an exclusive lock, and it is obtained exactly once
40491 ** operations become no-ops. Locking operations still happen internally,
40496 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
40497 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
40498 ** and is read-only.
40500 ** Zero is returned if the call completes successfully, or -1 if a call
40505 unixInodeInfo *pInode = pFile->pInode; in unixFileLock()
40507 assert( sqlite3_mutex_held(pInode->pLockMutex) ); in unixFileLock()
40508 if( (pFile->ctrlFlags & (UNIXFILE_EXCL|UNIXFILE_RDONLY))==UNIXFILE_EXCL ){ in unixFileLock()
40509 if( pInode->bProcessLock==0 ){ in unixFileLock()
40511 /* assert( pInode->nLock==0 ); <-- Not true if unix-excl READONLY used */ in unixFileLock()
40516 rc = osSetPosixAdvisoryLock(pFile->h, &lock, pFile); in unixFileLock()
40518 pInode->bProcessLock = 1; in unixFileLock()
40519 pInode->nLock++; in unixFileLock()
40525 if( pFile->bBlockOnConnect && pLock->l_type==F_RDLCK in unixFileLock()
40526 && pLock->l_start==SHARED_FIRST && pLock->l_len==SHARED_SIZE in unixFileLock()
40528 rc = osFcntl(pFile->h, F_SETLKW, pLock); in unixFileLock()
40531 rc = osSetPosixAdvisoryLock(pFile->h, pLock, pFile); in unixFileLock()
40537 ** Lock the file with the lock specified by parameter eFileLock - one
40551 ** UNLOCKED -> SHARED
40552 ** SHARED -> RESERVED
40553 ** SHARED -> EXCLUSIVE
40554 ** RESERVED -> (PENDING) -> EXCLUSIVE
40555 ** PENDING -> EXCLUSIVE
40563 ** lock primitives (called read-locks and write-locks below, to avoid in unixLock()
40572 ** To obtain a SHARED lock, a read-lock is obtained on the 'pending in unixLock()
40573 ** byte'. If this is successful, 'shared byte range' is read-locked in unixLock()
40576 ** and Windows95 lacks a shared-lock capability. So on Windows95, a in unixLock()
40578 ** Windows95 is now pretty much extinct, but this work-around for the in unixLock()
40579 ** lack of shared-locks on Windows95 lives on, for backwards in unixLock()
40583 ** A RESERVED lock is implemented by grabbing a write-lock on the in unixLock()
40586 ** An EXCLUSIVE lock may only be requested after either a SHARED or in unixLock()
40587 ** RESERVED lock is held. An EXCLUSIVE lock is implemented by obtaining in unixLock()
40588 ** a write-lock on the entire 'shared byte range'. Since all other locks in unixLock()
40589 ** require a read-lock on one of the bytes within this range, this ensures in unixLock()
40592 ** If a process that holds a RESERVED lock requests an EXCLUSIVE, then in unixLock()
40594 ** obtaining a write-lock on the 'pending byte'. This ensures that no new in unixLock()
40598 ** then re-attempt the EXCLUSIVE lock later on, after existing SHARED in unixLock()
40608 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h, in unixLock()
40609 azFileLock(eFileLock), azFileLock(pFile->eFileLock), in unixLock()
40610 azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared, in unixLock()
40617 if( pFile->eFileLock>=eFileLock ){ in unixLock()
40618 OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h, in unixLock()
40628 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK ); in unixLock()
40630 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK ); in unixLock()
40632 /* This mutex is needed because pFile->pInode is shared across threads in unixLock()
40634 pInode = pFile->pInode; in unixLock()
40635 sqlite3_mutex_enter(pInode->pLockMutex); in unixLock()
40640 if( (pFile->eFileLock!=pInode->eFileLock && in unixLock()
40641 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK)) in unixLock()
40652 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){ in unixLock()
40654 assert( pFile->eFileLock==0 ); in unixLock()
40655 assert( pInode->nShared>0 ); in unixLock()
40656 pFile->eFileLock = SHARED_LOCK; in unixLock()
40657 pInode->nShared++; in unixLock()
40658 pInode->nLock++; in unixLock()
40664 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will in unixLock()
40670 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock==RESERVED_LOCK) in unixLock()
40682 pFile->eFileLock = PENDING_LOCK; in unixLock()
40683 pInode->eFileLock = PENDING_LOCK; in unixLock()
40692 assert( pInode->nShared==0 ); in unixLock()
40693 assert( pInode->eFileLock==0 ); in unixLock()
40696 /* Now get the read-lock */ in unixLock()
40720 pFile->eFileLock = SHARED_LOCK; in unixLock()
40721 pInode->nLock++; in unixLock()
40722 pInode->nShared = 1; in unixLock()
40724 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){ in unixLock()
40725 /* We are trying for an exclusive lock but another thread in this in unixLock()
40733 assert( 0!=pFile->eFileLock ); in unixLock()
40756 /* Set up the transaction-counter change checking flags when in unixLock()
40762 && pFile->eFileLock<=SHARED_LOCK in unixLock()
40765 pFile->transCntrChng = 0; in unixLock()
40766 pFile->dbUpdate = 0; in unixLock()
40767 pFile->inNormalWrite = 1; in unixLock()
40772 pFile->eFileLock = eFileLock; in unixLock()
40773 pInode->eFileLock = eFileLock; in unixLock()
40777 sqlite3_mutex_leave(pInode->pLockMutex); in unixLock()
40778 OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), in unixLock()
40788 unixInodeInfo *pInode = pFile->pInode; in setPendingFd()
40789 UnixUnusedFd *p = pFile->pPreallocatedUnused; in setPendingFd()
40791 p->pNext = pInode->pUnused; in setPendingFd()
40792 pInode->pUnused = p; in setPendingFd()
40793 pFile->h = -1; in setPendingFd()
40794 pFile->pPreallocatedUnused = 0; in setPendingFd()
40802 ** the requested locking level, this routine is a no-op.
40804 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
40817 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock, in posixUnlock()
40818 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, in posixUnlock()
40822 if( pFile->eFileLock<=eFileLock ){ in posixUnlock()
40825 pInode = pFile->pInode; in posixUnlock()
40826 sqlite3_mutex_enter(pInode->pLockMutex); in posixUnlock()
40827 assert( pInode->nShared!=0 ); in posixUnlock()
40828 if( pFile->eFileLock>SHARED_LOCK ){ in posixUnlock()
40829 assert( pInode->eFileLock==pFile->eFileLock ); in posixUnlock()
40840 pFile->inNormalWrite = 0; in posixUnlock()
40844 ** before establishing the readlock - to avoid a race condition we downgrade in posixUnlock()
40860 off_t divSize = SHARED_SIZE - 1; in posixUnlock()
40866 if( unixFileLock(pFile, &lock)==(-1) ){ in posixUnlock()
40876 if( unixFileLock(pFile, &lock)==(-1) ){ in posixUnlock()
40887 lock.l_len = SHARED_SIZE-divSize; in posixUnlock()
40888 if( unixFileLock(pFile, &lock)==(-1) ){ in posixUnlock()
40903 ** process is holding an incompatible lock. If it does, this in posixUnlock()
40907 ** an assert to fail). */ in posixUnlock()
40919 pInode->eFileLock = SHARED_LOCK; in posixUnlock()
40927 /* Decrement the shared lock counter. Release the lock using an in posixUnlock()
40931 pInode->nShared--; in posixUnlock()
40932 if( pInode->nShared==0 ){ in posixUnlock()
40937 pInode->eFileLock = NO_LOCK; in posixUnlock()
40941 pInode->eFileLock = NO_LOCK; in posixUnlock()
40942 pFile->eFileLock = NO_LOCK; in posixUnlock()
40950 pInode->nLock--; in posixUnlock()
40951 assert( pInode->nLock>=0 ); in posixUnlock()
40952 if( pInode->nLock==0 ) closePendingFds(pFile); in posixUnlock()
40956 sqlite3_mutex_leave(pInode->pLockMutex); in posixUnlock()
40958 pFile->eFileLock = eFileLock; in posixUnlock()
40968 ** the requested locking level, this routine is a no-op.
40972 assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 ); in unixUnlock()
40997 if( pFile->h>=0 ){ in closeUnixFile()
40998 robust_close(pFile, pFile->h, __LINE__); in closeUnixFile()
40999 pFile->h = -1; in closeUnixFile()
41002 if( pFile->pId ){ in closeUnixFile()
41003 if( pFile->ctrlFlags & UNIXFILE_DELETE ){ in closeUnixFile()
41004 osUnlink(pFile->pId->zCanonicalName); in closeUnixFile()
41006 vxworksReleaseFileId(pFile->pId); in closeUnixFile()
41007 pFile->pId = 0; in closeUnixFile()
41011 if( pFile->ctrlFlags & UNIXFILE_DELETE ){ in closeUnixFile()
41012 osUnlink(pFile->zPath); in closeUnixFile()
41013 sqlite3_free(*(char**)&pFile->zPath); in closeUnixFile()
41014 pFile->zPath = 0; in closeUnixFile()
41017 OSTRACE(("CLOSE %-3d\n", pFile->h)); in closeUnixFile()
41018 OpenCounter(-1); in closeUnixFile()
41019 sqlite3_free(pFile->pPreallocatedUnused); in closeUnixFile()
41030 unixInodeInfo *pInode = pFile->pInode; in unixClose()
41041 assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 ); in unixClose()
41042 sqlite3_mutex_enter(pInode->pLockMutex); in unixClose()
41043 if( pInode->nLock ){ in unixClose()
41046 ** descriptor to pInode->pUnused list. It will be automatically closed in unixClose()
41051 sqlite3_mutex_leave(pInode->pLockMutex); in unixClose()
41053 assert( pFile->pShm==0 ); in unixClose()
41063 ****************************** No-op Locking **********************************
41069 ** This locking mode is appropriate for use on read-only databases
41070 ** (ex: databases that are burned into CD-ROM, for example.) It can
41100 /******************* End of the no-op lock implementation *********************
41104 ************************* Begin dot-file Locking ******************************
41113 ** (2) An application crash or power loss can leave stale lock files
41116 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
41121 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
41136 ** is assumed another client holds RESERVED if the lock-file exists.
41142 if( pFile->eFileLock>=SHARED_LOCK ){ in dotlockCheckReservedLock()
41145 *pResOut = osAccess((const char*)pFile->lockingContext, 0)==0; in dotlockCheckReservedLock()
41147 OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, 0, *pResOut)); in dotlockCheckReservedLock()
41152 ** Lock the file with the lock specified by parameter eFileLock - one
41166 ** UNLOCKED -> SHARED
41167 ** SHARED -> RESERVED
41168 ** SHARED -> (PENDING) -> EXCLUSIVE
41169 ** RESERVED -> (PENDING) -> EXCLUSIVE
41170 ** PENDING -> EXCLUSIVE
41180 char *zLockFile = (char *)pFile->lockingContext; in dotlockLock()
41187 if( pFile->eFileLock > NO_LOCK ){ in dotlockLock()
41188 pFile->eFileLock = eFileLock; in dotlockLock()
41198 /* grab an exclusive lock */ in dotlockLock()
41215 pFile->eFileLock = eFileLock; in dotlockLock()
41224 ** the requested locking level, this routine is a no-op.
41230 char *zLockFile = (char *)pFile->lockingContext; in dotlockUnlock()
41234 OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock, in dotlockUnlock()
41235 pFile->eFileLock, osGetpid(0))); in dotlockUnlock()
41238 /* no-op if possible */ in dotlockUnlock()
41239 if( pFile->eFileLock==eFileLock ){ in dotlockUnlock()
41247 pFile->eFileLock = SHARED_LOCK; in dotlockUnlock()
41264 pFile->eFileLock = NO_LOCK; in dotlockUnlock()
41275 sqlite3_free(pFile->lockingContext); in dotlockClose()
41278 /****************** End of the dot-file lock implementation *******************
41286 ** flock() locking is like dot-file locking in that the various
41287 ** fine-grain locking levels supported by SQLite are collapsed into
41289 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
41314 ** to a non-zero value otherwise *pResOut is set to zero. The return value
41315 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
41327 assert( pFile->eFileLock<=SHARED_LOCK ); in flockCheckReservedLock()
41335 ** 0 as well. The caller will then attempt to take an EXCLUSIVE lock on the in flockCheckReservedLock()
41337 ** holding a lock, that attempt will fail and an SQLITE_BUSY returned to in flockCheckReservedLock()
41340 ** work with the flock VFS - as it always takes EXCLUSIVE locks - so it is in flockCheckReservedLock()
41348 ** Lock the file with the lock specified by parameter eFileLock - one
41362 ** UNLOCKED -> SHARED
41363 ** SHARED -> RESERVED
41364 ** SHARED -> (PENDING) -> EXCLUSIVE
41365 ** RESERVED -> (PENDING) -> EXCLUSIVE
41366 ** PENDING -> EXCLUSIVE
41384 if (pFile->eFileLock > NO_LOCK) { in flockLock()
41385 pFile->eFileLock = eFileLock; in flockLock()
41389 /* grab an exclusive lock */ in flockLock()
41391 if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) { in flockLock()
41400 pFile->eFileLock = eFileLock; in flockLock()
41402 OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), in flockLock()
41418 ** the requested locking level, this routine is a no-op.
41424 OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock, in flockUnlock()
41425 pFile->eFileLock, osGetpid(0))); in flockUnlock()
41428 /* no-op if possible */ in flockUnlock()
41429 if( pFile->eFileLock==eFileLock ){ in flockUnlock()
41433 /* shared can just be set because we always have an exclusive */ in flockUnlock()
41435 pFile->eFileLock = eFileLock; in flockUnlock()
41440 if( robust_flock(pFile->h, LOCK_UN) ){ in flockUnlock()
41446 pFile->eFileLock = NO_LOCK; in flockUnlock()
41470 ** Semaphore locking is like dot-lock and flock in that it really only
41480 ** to a non-zero value otherwise *pResOut is set to zero. The return value
41481 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
41493 if( pFile->eFileLock>SHARED_LOCK ){ in semXCheckReservedLock()
41499 sem_t *pSem = pFile->pInode->pSem; in semXCheckReservedLock()
41501 if( sem_trywait(pSem)==-1 ){ in semXCheckReservedLock()
41508 reserved = (pFile->eFileLock < SHARED_LOCK); in semXCheckReservedLock()
41515 OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved)); in semXCheckReservedLock()
41522 ** Lock the file with the lock specified by parameter eFileLock - one
41536 ** UNLOCKED -> SHARED
41537 ** SHARED -> RESERVED
41538 ** SHARED -> (PENDING) -> EXCLUSIVE
41539 ** RESERVED -> (PENDING) -> EXCLUSIVE
41540 ** PENDING -> EXCLUSIVE
41552 sem_t *pSem = pFile->pInode->pSem; in semXLock()
41557 if (pFile->eFileLock > NO_LOCK) { in semXLock()
41558 pFile->eFileLock = eFileLock; in semXLock()
41564 if( sem_trywait(pSem)==-1 ){ in semXLock()
41570 pFile->eFileLock = eFileLock; in semXLock()
41581 ** the requested locking level, this routine is a no-op.
41585 sem_t *pSem = pFile->pInode->pSem; in semXUnlock()
41589 OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock, in semXUnlock()
41590 pFile->eFileLock, osGetpid(0))); in semXUnlock()
41593 /* no-op if possible */ in semXUnlock()
41594 if( pFile->eFileLock==eFileLock ){ in semXUnlock()
41598 /* shared can just be set because we always have an exclusive */ in semXUnlock()
41600 pFile->eFileLock = eFileLock; in semXUnlock()
41605 if ( sem_post(pSem)==-1 ) { in semXUnlock()
41613 pFile->eFileLock = NO_LOCK; in semXUnlock()
41646 ** on Apple Macintosh computers - both OS9 and OSX.
41648 ** Third-party implementations of AFP are available. But this code here
41675 ** This is a utility for setting or clearing a bit-range lock on an
41694 pb.fd = pFile->h; in afpSetLock()
41697 (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""), in afpSetLock()
41700 if ( err==-1 ) { in afpSetLock()
41723 ** to a non-zero value otherwise *pResOut is set to zero. The return value
41724 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
41735 context = (afpLockingContext *) pFile->lockingContext; in afpCheckReservedLock()
41736 if( context->reserved ){ in afpCheckReservedLock()
41740 sqlite3_mutex_enter(pFile->pInode->pLockMutex); in afpCheckReservedLock()
41742 if( pFile->pInode->eFileLock>SHARED_LOCK ){ in afpCheckReservedLock()
41750 int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); in afpCheckReservedLock()
41754 lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); in afpCheckReservedLock()
41764 sqlite3_mutex_leave(pFile->pInode->pLockMutex); in afpCheckReservedLock()
41765 OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved)); in afpCheckReservedLock()
41772 ** Lock the file with the lock specified by parameter eFileLock - one
41786 ** UNLOCKED -> SHARED
41787 ** SHARED -> RESERVED
41788 ** SHARED -> (PENDING) -> EXCLUSIVE
41789 ** RESERVED -> (PENDING) -> EXCLUSIVE
41790 ** PENDING -> EXCLUSIVE
41798 unixInodeInfo *pInode = pFile->pInode; in afpLock()
41799 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; in afpLock()
41802 OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h, in afpLock()
41803 azFileLock(eFileLock), azFileLock(pFile->eFileLock), in afpLock()
41804 azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0))); in afpLock()
41810 if( pFile->eFileLock>=eFileLock ){ in afpLock()
41811 OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h, in afpLock()
41821 assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK ); in afpLock()
41823 assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK ); in afpLock()
41825 /* This mutex is needed because pFile->pInode is shared across threads in afpLock()
41827 pInode = pFile->pInode; in afpLock()
41828 sqlite3_mutex_enter(pInode->pLockMutex); in afpLock()
41833 if( (pFile->eFileLock!=pInode->eFileLock && in afpLock()
41834 (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK)) in afpLock()
41845 (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){ in afpLock()
41847 assert( pFile->eFileLock==0 ); in afpLock()
41848 assert( pInode->nShared>0 ); in afpLock()
41849 pFile->eFileLock = SHARED_LOCK; in afpLock()
41850 pInode->nShared++; in afpLock()
41851 pInode->nLock++; in afpLock()
41856 ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will in afpLock()
41860 || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK) in afpLock()
41863 failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1); in afpLock()
41877 assert( pInode->nShared==0 ); in afpLock()
41878 assert( pInode->eFileLock==0 ); in afpLock()
41881 /* Now get the read-lock SHARED_LOCK */ in afpLock()
41884 pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1); in afpLock()
41885 lrc1 = afpSetLock(context->dbPath, pFile, in afpLock()
41886 SHARED_FIRST+pInode->sharedByte, 1, 1); in afpLock()
41888 lrc1Errno = pFile->lastErrno; in afpLock()
41891 lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); in afpLock()
41903 pFile->eFileLock = SHARED_LOCK; in afpLock()
41904 pInode->nLock++; in afpLock()
41905 pInode->nShared = 1; in afpLock()
41907 }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){ in afpLock()
41908 /* We are trying for an exclusive lock but another thread in this in afpLock()
41917 assert( 0!=pFile->eFileLock ); in afpLock()
41918 if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) { in afpLock()
41920 failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1); in afpLock()
41922 context->reserved = 1; in afpLock()
41926 /* Acquire an EXCLUSIVE lock */ in afpLock()
41931 if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST + in afpLock()
41932 pInode->sharedByte, 1, 0)) ){ in afpLock()
41935 failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, in afpLock()
41937 if( failed && (failed2 = afpSetLock(context->dbPath, pFile, in afpLock()
41938 SHARED_FIRST + pInode->sharedByte, 1, 1)) ){ in afpLock()
41956 pFile->eFileLock = eFileLock; in afpLock()
41957 pInode->eFileLock = eFileLock; in afpLock()
41959 pFile->eFileLock = PENDING_LOCK; in afpLock()
41960 pInode->eFileLock = PENDING_LOCK; in afpLock()
41964 sqlite3_mutex_leave(pInode->pLockMutex); in afpLock()
41965 OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), in afpLock()
41975 ** the requested locking level, this routine is a no-op.
41981 afpLockingContext *context = (afpLockingContext *) pFile->lockingContext; in afpUnlock()
41985 OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock, in afpUnlock()
41986 pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared, in afpUnlock()
41990 if( pFile->eFileLock<=eFileLock ){ in afpUnlock()
41993 pInode = pFile->pInode; in afpUnlock()
41994 sqlite3_mutex_enter(pInode->pLockMutex); in afpUnlock()
41995 assert( pInode->nShared!=0 ); in afpUnlock()
41996 if( pFile->eFileLock>SHARED_LOCK ){ in afpUnlock()
41997 assert( pInode->eFileLock==pFile->eFileLock ); in afpUnlock()
42008 assert( pFile->inNormalWrite==0 in afpUnlock()
42009 || pFile->dbUpdate==0 in afpUnlock()
42010 || pFile->transCntrChng==1 ); in afpUnlock()
42011 pFile->inNormalWrite = 0; in afpUnlock()
42014 if( pFile->eFileLock==EXCLUSIVE_LOCK ){ in afpUnlock()
42015 rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0); in afpUnlock()
42016 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){ in afpUnlock()
42017 /* only re-establish the shared lock if necessary */ in afpUnlock()
42018 int sharedLockByte = SHARED_FIRST+pInode->sharedByte; in afpUnlock()
42019 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1); in afpUnlock()
42024 if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){ in afpUnlock()
42025 rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0); in afpUnlock()
42027 if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){ in afpUnlock()
42028 rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0); in afpUnlock()
42030 context->reserved = 0; in afpUnlock()
42033 if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){ in afpUnlock()
42034 pInode->eFileLock = SHARED_LOCK; in afpUnlock()
42039 /* Decrement the shared lock counter. Release the lock using an in afpUnlock()
42043 unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte; in afpUnlock()
42044 pInode->nShared--; in afpUnlock()
42045 if( pInode->nShared==0 ){ in afpUnlock()
42047 rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0); in afpUnlock()
42050 pInode->eFileLock = NO_LOCK; in afpUnlock()
42051 pFile->eFileLock = NO_LOCK; in afpUnlock()
42055 pInode->nLock--; in afpUnlock()
42056 assert( pInode->nLock>=0 ); in afpUnlock()
42057 if( pInode->nLock==0 ) closePendingFds(pFile); in afpUnlock()
42061 sqlite3_mutex_leave(pInode->pLockMutex); in afpUnlock()
42063 pFile->eFileLock = eFileLock; in afpUnlock()
42078 if( pFile->pInode ){ in afpClose()
42079 unixInodeInfo *pInode = pFile->pInode; in afpClose()
42080 sqlite3_mutex_enter(pInode->pLockMutex); in afpClose()
42081 if( pInode->nLock ){ in afpClose()
42084 ** descriptor to pInode->aPending. It will be automatically closed when in afpClose()
42089 sqlite3_mutex_leave(pInode->pLockMutex); in afpClose()
42092 sqlite3_free(pFile->lockingContext); in afpClose()
42102 ** is available. If you don't compile for a mac, then the "unix-afp"
42117 ** the requested locking level, this routine is a no-op.
42133 **************** Non-locking sqlite3_file methods *****************************
42157 assert( id->h>2 ); in seekAndRead()
42160 got = osPread(id->h, pBuf, cnt, offset); in seekAndRead()
42161 SimulateIOError( got = -1 ); in seekAndRead()
42163 got = osPread64(id->h, pBuf, cnt, offset); in seekAndRead()
42164 SimulateIOError( got = -1 ); in seekAndRead()
42166 newOffset = lseek(id->h, offset, SEEK_SET); in seekAndRead()
42167 SimulateIOError( newOffset = -1 ); in seekAndRead()
42170 return -1; in seekAndRead()
42172 got = osRead(id->h, pBuf, cnt); in seekAndRead()
42181 cnt -= got; in seekAndRead()
42188 OSTRACE(("READ %-3d %5d %7lld %llu\n", in seekAndRead()
42189 id->h, got+prior, offset-prior, TIMER_ELAPSED)); in seekAndRead()
42210 /* If this is a database file (not a journal, super-journal or temp in unixRead()
42213 assert( pFile->pPreallocatedUnused==0 in unixRead()
42222 if( offset<pFile->mmapSize ){ in unixRead()
42223 if( offset+amt <= pFile->mmapSize ){ in unixRead()
42224 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt); in unixRead()
42227 int nCopy = pFile->mmapSize - offset; in unixRead()
42228 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy); in unixRead()
42230 amt -= nCopy; in unixRead()
42240 /* pFile->lastErrno has been set by seekAndRead(). in unixRead()
42247 switch( pFile->lastErrno ){ in unixRead()
42261 /* Unread parts of the buffer must be zero-filled */ in unixRead()
42262 memset(&((char*)pBuf)[got], 0, amt-got); in unixRead()
42268 ** Attempt to seek the file-descriptor passed as the first argument to
42270 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
42296 SimulateIOError( iSeek = -1 ); in seekAndWriteFd()
42298 rc = -1; in seekAndWriteFd()
42306 OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED)); in seekAndWriteFd()
42314 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
42321 return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno); in seekAndWrite()
42340 /* If this is a database file (not a journal, super-journal or temp in unixWrite()
42343 assert( pFile->pPreallocatedUnused==0 in unixWrite()
42351 ** doing a hot-journal rollback or a write to some file other than a in unixWrite()
42356 if( pFile->inNormalWrite ){ in unixWrite()
42357 pFile->dbUpdate = 1; /* The database has been modified */ in unixWrite()
42364 if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){ in unixWrite()
42365 pFile->transCntrChng = 1; /* The transaction counter has changed */ in unixWrite()
42374 if( offset<pFile->mmapSize ){ in unixWrite()
42375 if( offset+amt <= pFile->mmapSize ){ in unixWrite()
42376 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt); in unixWrite()
42379 int nCopy = pFile->mmapSize - offset; in unixWrite()
42380 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy); in unixWrite()
42382 amt -= nCopy; in unixWrite()
42389 amt -= wrote; in unixWrite()
42393 SimulateIOError(( wrote=(-1), amt=1 )); in unixWrite()
42397 if( wrote<0 && pFile->lastErrno!=ENOSPC ){ in unixWrite()
42422 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
42442 ** unix systems. The following procedure is an attempt to make
42448 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
42460 ** as far as SQLite is concerned, an fdatasync() is always adequate.
42492 ** no-op. But go ahead and call fstat() to validate the file in full_fsync()
42507 /* If the FULLFSYNC failed, fall back to attempting an fsync(). in full_fsync()
42510 ** isn't supported for this file system. So, attempt an fsync in full_fsync()
42525 if( rc==-1 && errno==ENOTSUP ){ in full_fsync()
42531 if( OS_VXWORKS && rc!= -1 ){ in full_fsync()
42540 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
42541 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
42544 ** The directory file descriptor is used for only one thing - to
42553 ** replace this routine with a harmless no-op. To make this routine
42554 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
42562 int fd = -1; in openDirectory()
42566 for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--); in openDirectory()
42575 OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname)); in openDirectory()
42590 ** has been created by fsync-ing the directory that contains the file.
42595 ** will not roll back - possibly leading to database corruption.
42615 OSTRACE(("SYNC %-3d\n", pFile->h)); in unixSync()
42616 rc = full_fsync(pFile->h, isFullsync, isDataOnly); in unixSync()
42620 return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath); in unixSync()
42624 ** is set. This is a one-time occurrence. Many systems (examples: AIX) in unixSync()
42627 if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){ in unixSync()
42629 OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath, in unixSync()
42631 rc = osOpenDirectory(pFile->zPath, &dirfd); in unixSync()
42639 pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC; in unixSync()
42645 ** Truncate an open file to a specified size
42653 /* If the user has configured a chunk-size for this file, truncate the in unixTruncate()
42654 ** file so that it consists of an integer number of chunks (i.e. the in unixTruncate()
42658 if( pFile->szChunk>0 ){ in unixTruncate()
42659 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk; in unixTruncate()
42662 rc = robust_ftruncate(pFile->h, nByte); in unixTruncate()
42665 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); in unixTruncate()
42669 ** doing a hot-journal rollback or a write to some file other than a in unixTruncate()
42672 ** when restoring a database using the backup API from a zero-length in unixTruncate()
42675 if( pFile->inNormalWrite && nByte==0 ){ in unixTruncate()
42676 pFile->transCntrChng = 1; in unixTruncate()
42685 if( nByte<pFile->mmapSize ){ in unixTruncate()
42686 pFile->mmapSize = nByte; in unixTruncate()
42701 rc = osFstat(((unixFile*)id)->h, &buf); in unixFileSize()
42709 /* When opening a zero-size database, the findInodeInfo() procedure in unixFileSize()
42711 ** in the OS-X msdos filesystem. In order to avoid problems with upper in unixFileSize()
42723 ** Handler for proxy-locking file-control verbs. Defined below in the
42731 ** file-control operation. Enlarge the database to nBytes in size
42732 ** (rounded up to the next chunk-size). If the database is already
42733 ** nBytes or larger, this routine is a no-op.
42736 if( pFile->szChunk>0 ){ in fcntlSizeHint()
42740 if( osFstat(pFile->h, &buf) ){ in fcntlSizeHint()
42744 nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk; in fcntlSizeHint()
42750 ** or an error number on failure". See the manpage for details. */ in fcntlSizeHint()
42753 err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size); in fcntlSizeHint()
42760 ** at offset (nSize-1), to set the size of the file correctly. in fcntlSizeHint()
42764 int nBlk = buf.st_blksize; /* File-system block size */ in fcntlSizeHint()
42768 iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1; in fcntlSizeHint()
42771 for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){ in fcntlSizeHint()
42772 if( iWrite>=nSize ) iWrite = nSize - 1; in fcntlSizeHint()
42781 if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){ in fcntlSizeHint()
42783 if( pFile->szChunk<=0 ){ in fcntlSizeHint()
42784 if( robust_ftruncate(pFile->h, nByte) ){ in fcntlSizeHint()
42786 return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath); in fcntlSizeHint()
42800 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
42802 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
42806 *pArg = (pFile->ctrlFlags & mask)!=0; in unixModeBit()
42808 pFile->ctrlFlags &= ~mask; in unixModeBit()
42810 pFile->ctrlFlags |= mask; in unixModeBit()
42821 ** Information and control of an open file handle.
42828 int rc = osIoctl(pFile->h, F2FS_IOC_START_ATOMIC_WRITE); in unixFileControl()
42832 int rc = osIoctl(pFile->h, F2FS_IOC_COMMIT_ATOMIC_WRITE); in unixFileControl()
42836 int rc = osIoctl(pFile->h, F2FS_IOC_ABORT_VOLATILE_WRITE); in unixFileControl()
42842 osClose(pFile->h); in unixFileControl()
42843 pFile->h = -1; in unixFileControl()
42847 *(int*)pArg = pFile->eFileLock; in unixFileControl()
42851 *(int*)pArg = pFile->lastErrno; in unixFileControl()
42855 pFile->szChunk = *(int *)pArg; in unixFileControl()
42874 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName); in unixFileControl()
42878 char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname ); in unixFileControl()
42880 unixGetTempname(pFile->pVfs->mxPathname, zTFile); in unixFileControl()
42891 int iOld = pFile->iBusyTimeout; in unixFileControl()
42894 pFile->iBusyTimeout = iNew<0 ? 0x7FFFFFFF : (unsigned)iNew; in unixFileControl()
42896 pFile->iBusyTimeout = !!(*(int*)pArg); in unixFileControl()
42905 pFile->bBlockOnConnect = iNew; in unixFileControl()
42919 ** 64-bit type. */ in unixFileControl()
42924 *(i64*)pArg = pFile->mmapSizeMax; in unixFileControl()
42925 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){ in unixFileControl()
42926 pFile->mmapSizeMax = newLimit; in unixFileControl()
42927 if( pFile->mmapSize>0 ){ in unixFileControl()
42929 rc = unixMapfile(pFile, -1); in unixFileControl()
42942 ((unixFile*)id)->dbUpdate = 0; in unixFileControl()
42966 ** If pFd->sectorSize is non-zero when this function is called, it is a
42967 ** no-op. Otherwise, the values of pFd->sectorSize and
42968 ** pFd->deviceCharacteristics are set according to the file-system
42976 assert( pFd->deviceCharacteristics==0 || pFd->sectorSize!=0 ); in setDeviceCharacteristics()
42977 if( pFd->sectorSize==0 ){ in setDeviceCharacteristics()
42983 res = osIoctl(pFd->h, F2FS_IOC_GET_FEATURES, &f); in setDeviceCharacteristics()
42985 pFd->deviceCharacteristics = SQLITE_IOCAP_BATCH_ATOMIC; in setDeviceCharacteristics()
42990 if( pFd->ctrlFlags & UNIXFILE_PSOW ){ in setDeviceCharacteristics()
42991 pFd->deviceCharacteristics |= SQLITE_IOCAP_POWERSAFE_OVERWRITE; in setDeviceCharacteristics()
42993 pFd->deviceCharacteristics |= SQLITE_IOCAP_SUBPAGE_READ; in setDeviceCharacteristics()
42995 pFd->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; in setDeviceCharacteristics()
43002 if( pFile->sectorSize == 0 ){ in setDeviceCharacteristics()
43005 /* Set defaults for non-supported filesystems */ in setDeviceCharacteristics()
43006 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; in setDeviceCharacteristics()
43007 pFile->deviceCharacteristics = 0; in setDeviceCharacteristics()
43008 if( fstatvfs(pFile->h, &fsInfo) == -1 ) { in setDeviceCharacteristics()
43013 pFile->sectorSize = fsInfo.f_bsize; in setDeviceCharacteristics()
43014 pFile->deviceCharacteristics = in setDeviceCharacteristics()
43022 pFile->sectorSize = fsInfo.f_bsize; in setDeviceCharacteristics()
43023 pFile->deviceCharacteristics = in setDeviceCharacteristics()
43025 (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) | in setDeviceCharacteristics()
43032 pFile->sectorSize = fsInfo.f_bsize; in setDeviceCharacteristics()
43033 pFile->deviceCharacteristics = in setDeviceCharacteristics()
43041 pFile->sectorSize = fsInfo.f_bsize; in setDeviceCharacteristics()
43042 pFile->deviceCharacteristics = in setDeviceCharacteristics()
43044 (((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2) | in setDeviceCharacteristics()
43049 pFile->sectorSize = fsInfo.f_bsize; in setDeviceCharacteristics()
43050 pFile->deviceCharacteristics = in setDeviceCharacteristics()
43052 (((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2) | in setDeviceCharacteristics()
43057 pFile->deviceCharacteristics = in setDeviceCharacteristics()
43066 if( pFile->sectorSize % 512 != 0 ){ in setDeviceCharacteristics()
43067 pFile->deviceCharacteristics = 0; in setDeviceCharacteristics()
43068 pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE; in setDeviceCharacteristics()
43079 ** if two files are created in the same file-system directory (i.e.
43086 return pFd->sectorSize; in unixSectorSize()
43095 ** words, after a power-loss event, parts of the file that were never
43096 ** written might end up being altered.) However, non-PSOW behavior is very,
43099 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
43105 return pFd->deviceCharacteristics; in unixDeviceCharacteristics()
43131 ** Object used to represent an shared memory buffer.
43133 ** When multiple threads all reference the same wal-index, each thread
43135 ** of this unixShmNode object. In other words, each wal-index is opened
43150 ** The following fields are read-only after the object is created:
43162 ** locks are held by the process on this slot. If it is set to -1, then
43163 ** some client holds an EXCLUSIVE lock on the locking slot. If the aLock[]
43172 ** If SQLITE_ENABLE_SETLK_TIMEOUT is defined though, we use an array
43173 ** of mutexes - one for each locking slot. To read or write locking
43183 int szRegion; /* Size of shared-memory regions */
43185 u8 isReadonly; /* True if read-only */
43187 char **apRegion; /* Array of mapped shared-memory regions */
43193 int aLock[SQLITE_SHM_NLOCK]; /* # shared locks on slot, -1==excl lock */
43200 ** Structure used internally by this VFS to record the state of an
43204 ** are read-only thereafter:
43209 ** All other fields are read/write. The unixShm.pShmNode->pShmMutex must
43215 u8 hasMutex; /* True if holding the unixShmNode->pShmMutex */
43229 ** wal-mode transactions in other processes on database file pFile. If
43231 ** such transactions, or 0 otherwise. If an error occurs, return an
43238 if( pFile->pShm){ in unixFcntlExternalReader()
43239 unixShmNode *pShmNode = pFile->pShm->pShmNode; in unixFcntlExternalReader()
43246 f.l_len = SQLITE_SHM_NLOCK - 3; in unixFcntlExternalReader()
43248 sqlite3_mutex_enter(pShmNode->pShmMutex); in unixFcntlExternalReader()
43249 if( osFcntl(pShmNode->hShm, F_GETLK, &f)<0 ){ in unixFcntlExternalReader()
43254 sqlite3_mutex_leave(pShmNode->pShmMutex); in unixFcntlExternalReader()
43262 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
43264 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
43273 unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */ in unixShmSystemLock()
43277 pShmNode = pFile->pInode->pShmNode; in unixShmSystemLock()
43281 assert( pShmNode->nRef>=0 ); in unixShmSystemLock()
43286 assert( pShmNode->nRef>0 || unixMutexHeld() ); in unixShmSystemLock()
43287 assert( pShmNode->nRef==0 || sqlite3_mutex_held(pShmNode->pShmMutex) ); in unixShmSystemLock()
43291 for(ii=ofst-UNIX_SHM_BASE; ii<ofst-UNIX_SHM_BASE+n; ii++){ in unixShmSystemLock()
43292 assert( sqlite3_mutex_held(pShmNode->aMutex[ii]) ); in unixShmSystemLock()
43295 assert( sqlite3_mutex_held(pShmNode->pShmMutex) ); in unixShmSystemLock()
43296 assert( pShmNode->nRef>0 ); in unixShmSystemLock()
43307 if( pShmNode->hShm>=0 ){ in unixShmSystemLock()
43314 res = osSetPosixAdvisoryLock(pShmNode->hShm, &f, pFile); in unixShmSystemLock()
43315 if( res==-1 ){ in unixShmSystemLock()
43317 rc = (pFile->iBusyTimeout ? SQLITE_BUSY_TIMEOUT : SQLITE_BUSY); in unixShmSystemLock()
43326 OSTRACE(("SHM-LOCK ")); in unixShmSystemLock()
43329 OSTRACE(("unlock %d..%d ok\n", ofst, ofst+n-1)); in unixShmSystemLock()
43331 OSTRACE(("read-lock %d..%d ok\n", ofst, ofst+n-1)); in unixShmSystemLock()
43334 OSTRACE(("write-lock %d..%d ok\n", ofst, ofst+n-1)); in unixShmSystemLock()
43338 OSTRACE(("unlock %d..%d failed\n", ofst, ofst+n-1)); in unixShmSystemLock()
43340 OSTRACE(("read-lock %d..%d failed\n", ofst, ofst+n-1)); in unixShmSystemLock()
43343 OSTRACE(("write-lock %d..%d failed\n", ofst, ofst+n-1)); in unixShmSystemLock()
43353 ** a time, assuming that each mapping must be an integer multiple of the
43354 ** current system page-size.
43357 ** to use 64KB pages - in this case each mapping must cover at least two
43363 assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */ in unixShmRegionPerMap()
43371 ** This is not a VFS shared-memory method; it is a utility function called
43372 ** by VFS shared-memory methods.
43375 unixShmNode *p = pFd->pInode->pShmNode; in unixShmPurge()
43377 if( p && ALWAYS(p->nRef==0) ){ in unixShmPurge()
43380 assert( p->pInode==pFd->pInode ); in unixShmPurge()
43381 sqlite3_mutex_free(p->pShmMutex); in unixShmPurge()
43384 sqlite3_mutex_free(p->aMutex[i]); in unixShmPurge()
43387 for(i=0; i<p->nRegion; i+=nShmPerMap){ in unixShmPurge()
43388 if( p->hShm>=0 ){ in unixShmPurge()
43389 osMunmap(p->apRegion[i], p->szRegion); in unixShmPurge()
43391 sqlite3_free(p->apRegion[i]); in unixShmPurge()
43394 sqlite3_free(p->apRegion); in unixShmPurge()
43395 if( p->hShm>=0 ){ in unixShmPurge()
43396 robust_close(pFd, p->hShm, __LINE__); in unixShmPurge()
43397 p->hShm = -1; in unixShmPurge()
43399 p->pInode->pShmNode = 0; in unixShmPurge()
43406 ** take it now. Return SQLITE_OK if successful, or an SQLite error
43411 ** SQLITE_READONLY_CANTINIT and set pShmNode->isUnlocked=1.
43420 ** and proceed with opening the *-shm file. in unixLockSharedMemory()
43423 ** is the first to open it. In this case take an EXCLUSIVE lock on the in unixLockSharedMemory()
43424 ** DMS byte and truncate the *-shm file to zero bytes in size. Then in unixLockSharedMemory()
43427 ** If another process is holding an EXCLUSIVE lock on the DMS byte, in unixLockSharedMemory()
43428 ** return SQLITE_BUSY to the caller (it will try again). An earlier in unixLockSharedMemory()
43431 ** EXCLUSIVE failed just before truncating the *-shm file, then this in unixLockSharedMemory()
43432 ** process might open and use the *-shm file without truncating it. in unixLockSharedMemory()
43433 ** And if the *-shm file has been corrupted by a power failure or in unixLockSharedMemory()
43439 if( osFcntl(pShmNode->hShm, F_GETLK, &lock)!=0 ) { in unixLockSharedMemory()
43442 if( pShmNode->isReadonly ){ in unixLockSharedMemory()
43443 pShmNode->isUnlocked = 1; in unixLockSharedMemory()
43449 ** *-shm file. And after it has done so, it will not release its in unixLockSharedMemory()
43453 int iSaveTimeout = pDbFd->iBusyTimeout; in unixLockSharedMemory()
43454 pDbFd->iBusyTimeout = 0; in unixLockSharedMemory()
43458 pDbFd->iBusyTimeout = iSaveTimeout; in unixLockSharedMemory()
43460 /* The first connection to attach must truncate the -shm file. We in unixLockSharedMemory()
43461 ** truncate to 3 bytes (an arbitrary small number, less than the in unixLockSharedMemory()
43462 ** -shm header size) rather than 0 as a system debugging aid, to in unixLockSharedMemory()
43463 ** help detect if a -shm file truncation is legitimate or is the work in unixLockSharedMemory()
43465 if( rc==SQLITE_OK && robust_ftruncate(pShmNode->hShm, 3) ){ in unixLockSharedMemory()
43466 rc = unixLogError(SQLITE_IOERR_SHMOPEN,"ftruncate",pShmNode->zFilename); in unixLockSharedMemory()
43481 ** Open a shared-memory area associated with open database file pDbFd.
43484 ** The file used to implement shared-memory is in the same directory
43486 ** file with the "-shm" suffix added. For example, if the database file
43488 ** for shared memory will be called "/home/user1/config.db-shm".
43490 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
43494 ** database to end up using different files for shared memory -
43495 ** meaning that their memory would not really be shared - resulting
43497 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
43498 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
43499 ** option results in an incompatible build of SQLite; builds of SQLite
43502 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
43505 ** When opening a new shared-memory file, if no other instances of that
43509 ** If the original database file (pDbFd) is using the "unix-excl" VFS
43510 ** that means that an exclusive lock is held on the database file and
43527 assert( pDbFd->pShm==0 ); in unixOpenSharedMemory()
43529 /* Check to see if a unixShmNode object already exists. Reuse an existing in unixOpenSharedMemory()
43534 pInode = pDbFd->pInode; in unixOpenSharedMemory()
43535 pShmNode = pInode->pShmNode; in unixOpenSharedMemory()
43539 const char *zBasePath = pDbFd->zPath; in unixOpenSharedMemory()
43543 ** a new *-shm file is created, an attempt will be made to create it in unixOpenSharedMemory()
43546 if( osFstat(pDbFd->h, &sStat) ){ in unixOpenSharedMemory()
43562 zShm = pShmNode->zFilename = (char*)&pShmNode[1]; in unixOpenSharedMemory()
43565 SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x", in unixOpenSharedMemory()
43568 sqlite3_snprintf(nShmFilename, zShm, "%s-shm", zBasePath); in unixOpenSharedMemory()
43569 sqlite3FileSuffix3(pDbFd->zPath, zShm); in unixOpenSharedMemory()
43571 pShmNode->hShm = -1; in unixOpenSharedMemory()
43572 pDbFd->pInode->pShmNode = pShmNode; in unixOpenSharedMemory()
43573 pShmNode->pInode = pDbFd->pInode; in unixOpenSharedMemory()
43575 pShmNode->pShmMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); in unixOpenSharedMemory()
43576 if( pShmNode->pShmMutex==0 ){ in unixOpenSharedMemory()
43584 pShmNode->aMutex[ii] = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST); in unixOpenSharedMemory()
43585 if( pShmNode->aMutex[ii]==0 ){ in unixOpenSharedMemory()
43594 if( pInode->bProcessLock==0 ){ in unixOpenSharedMemory()
43595 if( 0==sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){ in unixOpenSharedMemory()
43596 pShmNode->hShm = robust_open(zShm, O_RDWR|O_CREAT|O_NOFOLLOW, in unixOpenSharedMemory()
43599 if( pShmNode->hShm<0 ){ in unixOpenSharedMemory()
43600 pShmNode->hShm = robust_open(zShm, O_RDONLY|O_NOFOLLOW, in unixOpenSharedMemory()
43602 if( pShmNode->hShm<0 ){ in unixOpenSharedMemory()
43606 pShmNode->isReadonly = 1; in unixOpenSharedMemory()
43613 robustFchown(pShmNode->hShm, sStat.st_uid, sStat.st_gid); in unixOpenSharedMemory()
43621 p->pShmNode = pShmNode; in unixOpenSharedMemory()
43623 p->id = pShmNode->nextShmId++; in unixOpenSharedMemory()
43625 pShmNode->nRef++; in unixOpenSharedMemory()
43626 pDbFd->pShm = p; in unixOpenSharedMemory()
43633 ** at pShmNode->pFirst. This must be done while holding the in unixOpenSharedMemory()
43634 ** pShmNode->pShmMutex. in unixOpenSharedMemory()
43636 sqlite3_mutex_enter(pShmNode->pShmMutex); in unixOpenSharedMemory()
43637 p->pNext = pShmNode->pFirst; in unixOpenSharedMemory()
43638 pShmNode->pFirst = p; in unixOpenSharedMemory()
43639 sqlite3_mutex_leave(pShmNode->pShmMutex); in unixOpenSharedMemory()
43652 ** shared-memory associated with the database file fd. Shared-memory regions
43653 ** are numbered starting from zero. Each shared-memory region is szRegion
43656 ** If an error occurs, an error code is returned and *pp is set to NULL.
43658 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
43661 ** bExtend is non-zero and the requested shared-memory region has not yet
43664 ** If the shared-memory region has already been allocated or is allocated by
43683 /* If the shared-memory file has not yet been opened, open it now. */ in unixShmMap()
43684 if( pDbFd->pShm==0 ){ in unixShmMap()
43689 p = pDbFd->pShm; in unixShmMap()
43690 pShmNode = p->pShmNode; in unixShmMap()
43691 sqlite3_mutex_enter(pShmNode->pShmMutex); in unixShmMap()
43692 if( pShmNode->isUnlocked ){ in unixShmMap()
43695 pShmNode->isUnlocked = 0; in unixShmMap()
43697 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 ); in unixShmMap()
43698 assert( pShmNode->pInode==pDbFd->pInode ); in unixShmMap()
43699 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 ); in unixShmMap()
43700 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 ); in unixShmMap()
43705 if( pShmNode->nRegion<nReqRegion ){ in unixShmMap()
43710 pShmNode->szRegion = szRegion; in unixShmMap()
43712 if( pShmNode->hShm>=0 ){ in unixShmMap()
43714 ** Check to see if it has been allocated (i.e. if the wal-index file is in unixShmMap()
43717 if( osFstat(pShmNode->hShm, &sStat) ){ in unixShmMap()
43745 if( seekAndWriteFd(pShmNode->hShm, iPg*pgsz + pgsz-1,"",1,&x)!=1 ){ in unixShmMap()
43746 const char *zFile = pShmNode->zFilename; in unixShmMap()
43757 pShmNode->apRegion, nReqRegion*sizeof(char *) in unixShmMap()
43763 pShmNode->apRegion = apNew; in unixShmMap()
43764 while( pShmNode->nRegion<nReqRegion ){ in unixShmMap()
43768 if( pShmNode->hShm>=0 ){ in unixShmMap()
43770 pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, in unixShmMap()
43771 MAP_SHARED, pShmNode->hShm, szRegion*(i64)pShmNode->nRegion in unixShmMap()
43774 rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename); in unixShmMap()
43787 pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i]; in unixShmMap()
43789 pShmNode->nRegion += nShmPerMap; in unixShmMap()
43794 if( pShmNode->nRegion>iRegion ){ in unixShmMap()
43795 *pp = pShmNode->apRegion[iRegion]; in unixShmMap()
43799 if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY; in unixShmMap()
43800 sqlite3_mutex_leave(pShmNode->pShmMutex); in unixShmMap()
43805 ** Check that the pShmNode->aLock[] array comports with the locking bitmasks
43807 ** is to be used in an assert(). e.g.
43820 for(pX=pShmNode->pFirst; pX; pX=pX->pNext){ in assertLockingArrayOk()
43823 if( pX->exclMask & (1<<i) ){ in assertLockingArrayOk()
43825 aLock[i] = -1; in assertLockingArrayOk()
43826 }else if( pX->sharedMask & (1<<i) ){ in assertLockingArrayOk()
43833 assert( 0==memcmp(pShmNode->aLock, aLock, sizeof(aLock)) ); in assertLockingArrayOk()
43834 return (memcmp(pShmNode->aLock, aLock, sizeof(aLock))==0); in assertLockingArrayOk()
43840 ** Change the lock state for a shared-memory segment.
43857 u16 mask = (1<<(ofst+n)) - (1<<ofst); /* Mask of locks to take or release */ in unixShmLock()
43860 p = pDbFd->pShm; in unixShmLock()
43862 pShmNode = p->pShmNode; in unixShmLock()
43864 aLock = pShmNode->aLock; in unixShmLock()
43866 assert( pShmNode==pDbFd->pInode->pShmNode ); in unixShmLock()
43867 assert( pShmNode->pInode==pDbFd->pInode ); in unixShmLock()
43875 assert( pShmNode->hShm>=0 || pDbFd->pInode->bProcessLock==1 ); in unixShmLock()
43876 assert( pShmNode->hShm<0 || pDbFd->pInode->bProcessLock==0 ); in unixShmLock()
43892 u16 lockMask = (p->exclMask|p->sharedMask); in unixShmLock()
43893 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || ( in unixShmLock()
43904 ** a) An unlock operation where there are locks to unlock, in unixShmLock()
43905 ** b) An shared lock where the requested lock is not already held in unixShmLock()
43906 ** c) An exclusive lock where the requested lock is not already held in unixShmLock()
43908 ** The SQLite core never requests an exclusive lock that it already holds. in unixShmLock()
43912 || 0==(p->exclMask & mask) in unixShmLock()
43914 if( ((flags & SQLITE_SHM_UNLOCK) && ((p->exclMask|p->sharedMask) & mask)) in unixShmLock()
43915 || (flags==(SQLITE_SHM_SHARED|SQLITE_SHM_LOCK) && 0==(p->sharedMask & mask)) in unixShmLock()
43920 ** this is an attempt on an exclusive lock use sqlite3_mutex_try(). If any in unixShmLock()
43928 ** case thread 2 does a non-blocking request for the WRITER lock. But - in unixShmLock()
43932 ** a lock on a read-locking slot at this point, this breaks the in unixShmLock()
43933 ** anti-deadlock rules (see above). */ in unixShmLock()
43938 rc = sqlite3_mutex_try(pShmNode->aMutex[iMutex]); in unixShmLock()
43941 sqlite3_mutex_enter(pShmNode->aMutex[iMutex]); in unixShmLock()
43945 sqlite3_mutex_enter(pShmNode->pShmMutex); in unixShmLock()
43950 /* Case (a) - unlock. */ in unixShmLock()
43952 assert( (p->exclMask & p->sharedMask)==0 ); in unixShmLock()
43953 assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask ); in unixShmLock()
43954 assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask ); in unixShmLock()
43959 ** from the file-descriptor below. */ in unixShmLock()
43965 aLock[ofst]--; in unixShmLock()
43966 p->sharedMask &= ~mask; in unixShmLock()
43974 p->sharedMask &= ~mask; in unixShmLock()
43975 p->exclMask &= ~mask; in unixShmLock()
43979 /* Case (b) - a shared lock. */ in unixShmLock()
43982 /* An exclusive lock is held by some other connection. BUSY. */ in unixShmLock()
43990 p->sharedMask |= mask; in unixShmLock()
43994 /* Case (c) - an exclusive lock. */ in unixShmLock()
43998 assert( (p->sharedMask & mask)==0 ); in unixShmLock()
43999 assert( (p->exclMask & mask)==0 ); in unixShmLock()
44011 ** also update the in-memory values. */ in unixShmLock()
44015 p->exclMask |= mask; in unixShmLock()
44017 aLock[ii] = -1; in unixShmLock()
44028 for(iMutex--; iMutex>=ofst; iMutex--){ in unixShmLock()
44029 sqlite3_mutex_leave(pShmNode->aMutex[iMutex]); in unixShmLock()
44032 sqlite3_mutex_leave(pShmNode->pShmMutex); in unixShmLock()
44036 OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n", in unixShmLock()
44037 p->id, osGetpid(0), p->sharedMask, p->exclMask)); in unixShmLock()
44051 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */ in unixShmBarrier()
44052 assert( fd->pMethods->xLock==nolockLock in unixShmBarrier()
44060 ** Close a connection to shared-memory. Delete the underlying
44064 ** routine is a harmless no-op.
44068 int deleteFlag /* Delete shared-memory if true */ in unixShmUnmap()
44071 unixShmNode *pShmNode; /* The underlying shared-memory file */ in unixShmUnmap()
44076 p = pDbFd->pShm; in unixShmUnmap()
44078 pShmNode = p->pShmNode; in unixShmUnmap()
44080 assert( pShmNode==pDbFd->pInode->pShmNode ); in unixShmUnmap()
44081 assert( pShmNode->pInode==pDbFd->pInode ); in unixShmUnmap()
44085 sqlite3_mutex_enter(pShmNode->pShmMutex); in unixShmUnmap()
44086 for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){} in unixShmUnmap()
44087 *pp = p->pNext; in unixShmUnmap()
44091 pDbFd->pShm = 0; in unixShmUnmap()
44092 sqlite3_mutex_leave(pShmNode->pShmMutex); in unixShmUnmap()
44094 /* If pShmNode->nRef has reached 0, then close the underlying in unixShmUnmap()
44095 ** shared-memory file, too */ in unixShmUnmap()
44098 assert( pShmNode->nRef>0 ); in unixShmUnmap()
44099 pShmNode->nRef--; in unixShmUnmap()
44100 if( pShmNode->nRef==0 ){ in unixShmUnmap()
44101 if( deleteFlag && pShmNode->hShm>=0 ){ in unixShmUnmap()
44102 osUnlink(pShmNode->zFilename); in unixShmUnmap()
44124 assert( pFd->nFetchOut==0 ); in unixUnmapfile()
44125 if( pFd->pMapRegion ){ in unixUnmapfile()
44126 osMunmap(pFd->pMapRegion, pFd->mmapSizeActual); in unixUnmapfile()
44127 pFd->pMapRegion = 0; in unixUnmapfile()
44128 pFd->mmapSize = 0; in unixUnmapfile()
44129 pFd->mmapSizeActual = 0; in unixUnmapfile()
44143 ** If unsuccessful, an error message is logged via sqlite3_log() and
44153 int h = pFd->h; /* File descriptor open on db file */ in unixRemapfile()
44154 u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */ in unixRemapfile()
44155 i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */ in unixRemapfile()
44159 assert( pFd->nFetchOut==0 ); in unixRemapfile()
44160 assert( nNew>pFd->mmapSize ); in unixRemapfile()
44161 assert( nNew<=pFd->mmapSizeMax ); in unixRemapfile()
44163 assert( pFd->mmapSizeActual>=pFd->mmapSize ); in unixRemapfile()
44167 if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE; in unixRemapfile()
44172 i64 nReuse = pFd->mmapSize; in unixRemapfile()
44175 i64 nReuse = (pFd->mmapSize & ~(szSyspage-1)); in unixRemapfile()
44181 osMunmap(pReq, nOrig-nReuse); in unixRemapfile()
44188 pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse); in unixRemapfile()
44191 osMunmap(pNew, nNew - nReuse); in unixRemapfile()
44205 /* If pNew is still NULL, try to create an entirely new mapping. */ in unixRemapfile()
44213 unixLogError(SQLITE_OK, zErr, pFd->zPath); in unixRemapfile()
44218 pFd->mmapSizeMax = 0; in unixRemapfile()
44220 pFd->pMapRegion = (void *)pNew; in unixRemapfile()
44221 pFd->mmapSize = pFd->mmapSizeActual = nNew; in unixRemapfile()
44225 ** Memory map or remap the file opened by file-descriptor pFd (if the file
44228 ** outstanding xFetch() references to it, this function is a no-op.
44230 ** If parameter nByte is non-negative, then it is the requested size of
44237 ** recreated as a result of outstanding references) or an SQLite error
44241 assert( nMap>=0 || pFd->nFetchOut==0 ); in unixMapfile()
44242 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) ); in unixMapfile()
44243 if( pFd->nFetchOut>0 ) return SQLITE_OK; in unixMapfile()
44246 struct stat statbuf; /* Low-level file information */ in unixMapfile()
44247 if( osFstat(pFd->h, &statbuf) ){ in unixMapfile()
44252 if( nMap>pFd->mmapSizeMax ){ in unixMapfile()
44253 nMap = pFd->mmapSizeMax; in unixMapfile()
44256 assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) ); in unixMapfile()
44257 if( nMap!=pFd->mmapSize ){ in unixMapfile()
44271 ** Finally, if an error does occur, return an SQLite error code. The final
44284 if( pFd->mmapSizeMax>0 ){ in unixFetch()
44290 if( pFd->pMapRegion==0 ){ in unixFetch()
44291 int rc = unixMapfile(pFd, -1); in unixFetch()
44294 if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){ in unixFetch()
44295 *pp = &((u8 *)pFd->pMapRegion)[iOff]; in unixFetch()
44296 pFd->nFetchOut++; in unixFetch()
44304 ** If the third argument is non-NULL, then this function releases a
44305 ** reference obtained by an earlier call to unixFetch(). The second
44319 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference), in unixUnfetch()
44321 assert( (p==0)==(pFd->nFetchOut==0) ); in unixUnfetch()
44324 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] ); in unixUnfetch()
44327 pFd->nFetchOut--; in unixUnfetch()
44332 assert( pFd->nFetchOut>=0 ); in unixUnfetch()
44350 ** of "finder" functions. A finder-function is used to locate the appropriate
44353 ** the correct finder-function for that VFS.
44356 ** object. The only interesting finder-function is autolockIoFinder, which
44360 ** For finder-function F, two objects are created:
44362 ** (1) The real finder-function named "FImpt()".
44369 ** directly at the finder-function since C90 rules prevent a void*
44378 ** * An I/O method finder function called FINDER that returns a pointer
44486 ** The proxy locking method is a "super-method" in the sense that it
44488 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
44557 if( statfs(filePath, &fsInfo) != -1 ){ in autolockIoFinderImpl()
44569 ** Test byte-range lock using fcntl(). If the call succeeds, in autolockIoFinderImpl()
44570 ** assume that the file-system supports POSIX style locks. in autolockIoFinderImpl()
44576 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { in autolockIoFinderImpl()
44616 if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) { in vxworksIoFinderImpl()
44628 ** An abstract type for a pointer to an IO method finder function:
44654 assert( pNew->pInode==NULL ); in fillInUnixFile()
44659 OSTRACE(("OPEN %-3d %s\n", h, zFilename)); in fillInUnixFile()
44660 pNew->h = h; in fillInUnixFile()
44661 pNew->pVfs = pVfs; in fillInUnixFile()
44662 pNew->zPath = zFilename; in fillInUnixFile()
44663 pNew->ctrlFlags = (u8)ctrlFlags; in fillInUnixFile()
44665 pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap; in fillInUnixFile()
44669 pNew->ctrlFlags |= UNIXFILE_PSOW; in fillInUnixFile()
44671 if( strcmp(pVfs->zName,"unix-excl")==0 ){ in fillInUnixFile()
44672 pNew->ctrlFlags |= UNIXFILE_EXCL; in fillInUnixFile()
44676 pNew->pId = vxworksFindFileId(zFilename); in fillInUnixFile()
44677 if( pNew->pId==0 ){ in fillInUnixFile()
44686 pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew); in fillInUnixFile()
44691 pNew->lockingContext = (void*)zFilename; in fillInUnixFile()
44701 rc = findInodeInfo(pNew, &pNew->pInode); in fillInUnixFile()
44703 /* If an error occurred in findInodeInfo(), close the file descriptor in fillInUnixFile()
44714 ** handle h - as it is guaranteed that no posix locks will be released in fillInUnixFile()
44722 h = -1; in fillInUnixFile()
44733 pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) ); in fillInUnixFile()
44740 pCtx->dbPath = zFilename; in fillInUnixFile()
44741 pCtx->reserved = 0; in fillInUnixFile()
44744 rc = findInodeInfo(pNew, &pNew->pInode); in fillInUnixFile()
44746 sqlite3_free(pNew->lockingContext); in fillInUnixFile()
44748 h = -1; in fillInUnixFile()
44769 pNew->lockingContext = zLockFile; in fillInUnixFile()
44778 rc = findInodeInfo(pNew, &pNew->pInode); in fillInUnixFile()
44779 if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){ in fillInUnixFile()
44780 char *zSemName = pNew->pInode->aSemName; in fillInUnixFile()
44783 pNew->pId->zCanonicalName); in fillInUnixFile()
44786 pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1); in fillInUnixFile()
44787 if( pNew->pInode->pSem == SEM_FAILED ){ in fillInUnixFile()
44789 pNew->pInode->aSemName[0] = '\0'; in fillInUnixFile()
44800 h = -1; in fillInUnixFile()
44802 pNew->ctrlFlags |= UNIXFILE_DELETE; in fillInUnixFile()
44808 pId->pMethods = pLockingStyle; in fillInUnixFile()
44861 ** pVfs->mxPathname bytes.
44868 /* It's odd to simulate an io-error here, but really this is just in unixGetTempname()
44869 ** using the io-error infrastructure to test that SQLite handles this in unixGetTempname()
44884 zBuf[nBuf-2] = 0; in unixGetTempname()
44887 if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ){ in unixGetTempname()
44899 ** Routine to transform a unixFile into a proxy-locking unixFile.
44900 ** Implementation in the proxy-lock division, but used by unixOpen()
44907 ** Search for an unused file descriptor that was opened on the database
44908 ** file (not a journal or super-journal file) identified by pathname
44914 ** other file descriptor open on the same file is holding a file-lock.
44920 ** such file descriptor is located, -1 is returned.
44925 /* Do not search for an unused file descriptor on vxworks. Not because in findReusableFd()
44928 ** not to risk breaking vxworks support for the sake of such an obscure in findReusableFd()
44936 ** almost certain that an open() call on the same path will also fail. in findReusableFd()
44937 ** For this reason, if an error occurs in the stat() call here, it is in findReusableFd()
44938 ** ignored and -1 is returned. The caller will try to open a new file in findReusableFd()
44939 ** descriptor on the same path, fail, and return an error to SQLite. in findReusableFd()
44947 while( pInode && (pInode->fileId.dev!=sStat.st_dev in findReusableFd()
44948 || pInode->fileId.ino!=(u64)sStat.st_ino) ){ in findReusableFd()
44949 pInode = pInode->pNext; in findReusableFd()
44953 assert( sqlite3_mutex_notheld(pInode->pLockMutex) ); in findReusableFd()
44954 sqlite3_mutex_enter(pInode->pLockMutex); in findReusableFd()
44956 for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext)); in findReusableFd()
44959 *pp = pUnused->pNext; in findReusableFd()
44961 sqlite3_mutex_leave(pInode->pLockMutex); in findReusableFd()
44994 ** written to *pMode. If an IO error occurs, an SQLite error code is
44998 ** an indication to robust_open() to create the file using
45001 ** this function queries the file-system for the permissions on the
45030 ** "<path to db>-journal" in findCreateFileMode()
45031 ** "<path to db>-wal" in findCreateFileMode()
45032 ** "<path to db>-journalNN" in findCreateFileMode()
45033 ** "<path to db>-walNN" in findCreateFileMode()
45039 ** a '-' character. However in 8+3 filename mode, or if a corrupt in findCreateFileMode()
45040 ** rollback journal specifies a super-journal with a goofy name, then in findCreateFileMode()
45041 ** the '-' might be missing or the '-' might be the first character in in findCreateFileMode()
45044 nDb = sqlite3Strlen30(zPath) - 1; in findCreateFileMode()
45046 if( zPath[nDb]=='-' ){ in findCreateFileMode()
45052 nDb--; in findCreateFileMode()
45081 ** ReadWrite() -> (READWRITE | CREATE)
45082 ** ReadOnly() -> (READONLY)
45083 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
45085 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
45099 int fd = -1; /* File descriptor returned by open() */ in unixOpen()
45118 /* If creating a super- or main-file journal, this function will open in unixOpen()
45119 ** a file-descriptor on the directory too. The first time unixSync() in unixOpen()
45146 /* The main DB, main journal, WAL file and super-journal are never in unixOpen()
45153 /* Assert that the upper layer has set one of the "file-type" flags. */ in unixOpen()
45180 fd = pUnused->fd; in unixOpen()
45187 p->pPreallocatedUnused = pUnused; in unixOpen()
45189 /* Database filenames are double-zero terminated if they are not in unixOpen()
45197 rc = unixGetTempname(pVfs->mxPathname, zTmpname); in unixOpen()
45203 /* Generated temporary filenames are always double-zero terminated in unixOpen()
45224 assert( !p->pPreallocatedUnused ); in unixOpen()
45229 OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags)); in unixOpen()
45237 /* Failed to open the file for read/write access. Try read-only. */ in unixOpen()
45246 fd = pReadonly->fd; in unixOpen()
45261 ** the case. The chown() system call will be a no-op if the current in unixOpen()
45280 if( p->pPreallocatedUnused ){ in unixOpen()
45281 p->pPreallocatedUnused->fd = fd; in unixOpen()
45282 p->pPreallocatedUnused->flags = in unixOpen()
45301 p->openFlags = openFlags; in unixOpen()
45306 if( fstatfs(fd, &fsInfo) == -1 ){ in unixOpen()
45312 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; in unixOpen()
45315 ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS; in unixOpen()
45331 if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){ in unixOpen()
45336 ** never use proxy, NULL means use proxy for non-local files only. */ in unixOpen()
45349 ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op in unixOpen()
45367 sqlite3_free(p->pPreallocatedUnused); in unixOpen()
45385 if( osUnlink(zPath)==(-1) ){ in unixDelete()
45454 int rc; /* Non-zero following any error */
45469 const char *zName, /* Name to append to pPath. Not zero-terminated */ in appendOnePathElement()
45477 if( pPath->nUsed>1 ){ in appendOnePathElement()
45478 assert( pPath->zOut[0]=='/' ); in appendOnePathElement()
45479 while( pPath->zOut[--pPath->nUsed]!='/' ){} in appendOnePathElement()
45484 if( pPath->nUsed + nName + 2 >= pPath->nOut ){ in appendOnePathElement()
45485 pPath->rc = SQLITE_ERROR; in appendOnePathElement()
45488 pPath->zOut[pPath->nUsed++] = '/'; in appendOnePathElement()
45489 memcpy(&pPath->zOut[pPath->nUsed], zName, nName); in appendOnePathElement()
45490 pPath->nUsed += nName; in appendOnePathElement()
45492 if( pPath->rc==SQLITE_OK ){ in appendOnePathElement()
45495 pPath->zOut[pPath->nUsed] = 0; in appendOnePathElement()
45496 zIn = pPath->zOut; in appendOnePathElement()
45499 pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn); in appendOnePathElement()
45504 if( pPath->nSymlink++ > SQLITE_MAX_SYMLINK ){ in appendOnePathElement()
45505 pPath->rc = SQLITE_CANTOPEN_BKPT; in appendOnePathElement()
45508 got = osReadlink(zIn, zLnk, sizeof(zLnk)-2); in appendOnePathElement()
45509 if( got<=0 || got>=(ssize_t)sizeof(zLnk)-2 ){ in appendOnePathElement()
45510 pPath->rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn); in appendOnePathElement()
45515 pPath->nUsed = 0; in appendOnePathElement()
45517 pPath->nUsed -= nName + 1; in appendOnePathElement()
45530 const char *zPath /* Path to append to pPath. Is zero-terminated */ in appendAllPathElements()
45537 appendOnePathElement(pPath, &zPath[j], i-j); in appendAllPathElements()
45545 ** is stored as a nul-terminated string in the buffer pointed to by
45549 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
45567 if( osGetcwd(zPwd, sizeof(zPwd)-2)==0 ){ in unixFullPathname()
45609 ** GCC with -pedantic-errors says that C90 does not allow a void* to be in unixDlSym()
45612 ** use dlsym() with -pedantic-errors? in unixDlSym()
45620 ** This work-around is unlikely to work correctly on any system where in unixDlSym()
45649 ** errors. The reports issued by valgrind are incorrect - we would in unixRandomness()
45651 ** uninitialized space in zBuf - but valgrind errors tend to worry in unixRandomness()
45699 ** -DHAVE_NANOSLEEP=0 (perhaps in conjunction with -DHAVE_USLEEP if in unixSleep()
45719 ** The following variable, if set to a non-zero value, is interpreted as
45783 ** low-level error message when operating-system problems come up
45802 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
45804 ** meta-layer over top of the primitive locking implemented above. For
45807 ** been defined - so that the primitive locking methods are available
45812 ** The default locking schemes in SQLite use byte-range locks on the
45817 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
45821 ** shared range is taken for an EXCLUSIVE lock):
45825 ** SHARED_RANGE 0x40000002 -> 0x40000200
45829 ** the read cache when byte-range locks are present. Enabling the read
45832 ** close-to-open semantics for ensuring cache coherency
45836 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
45845 ** -----------------
45877 ** -----------------------
45887 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
45888 ** by taking an sqlite-style shared lock on the conch file, reading the
45892 ** is patterned after the database file name as ".<databasename>-conch".
45894 ** host ID and/or proxy path, then the lock is escalated to an exclusive
45900 ** The proxy file - a single-byte file used for all advisory file locks
45909 ** The shared lock and an open file descriptor are maintained until
45916 ** ---------------------
45920 ** Database files accessed on non-local file systems are
45965 int conchHeld; /* 1 if the conch is held, -1 if lockless */
45998 if( lPath[len-1]!='/' ){ in proxyGetLockPath()
46027 if( lockPath[i] == '/' && (i - start > 0) ){ in proxyCreateLockPath()
46029 if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') in proxyCreateLockPath()
46030 || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){ in proxyCreateLockPath()
46062 int fd = -1; in proxyCreateUnixFile()
46071 ** 2. if that fails, and this is a lock file (not-conch), try creating in proxyCreateUnixFile()
46073 ** 3. if that fails, try to open the file read-only in proxyCreateUnixFile()
46078 fd = pUnused->fd; in proxyCreateUnixFile()
46119 pNew->openFlags = openFlags; in proxyCreateUnixFile()
46123 pUnused->fd = fd; in proxyCreateUnixFile()
46124 pUnused->flags = openFlags; in proxyCreateUnixFile()
46125 pNew->pPreallocatedUnused = pUnused; in proxyCreateUnixFile()
46183 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
46189 ** Takes an open conch file, copies the contents to a new path and then moves
46195 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; in proxyBreakConchLock()
46196 unixFile *conchFile = pCtx->conchFile; in proxyBreakConchLock()
46199 char *cPath = pCtx->conchFilePath; in proxyBreakConchLock()
46203 int fd = -1; in proxyBreakConchLock()
46204 int rc = -1; in proxyBreakConchLock()
46207 /* create a new path by replace the trailing '-conch' with '-break' */ in proxyBreakConchLock()
46210 (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){ in proxyBreakConchLock()
46215 readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0); in proxyBreakConchLock()
46236 robust_close(pFile, conchFile->h, __LINE__); in proxyBreakConchLock()
46237 conchFile->h = fd; in proxyBreakConchLock()
46238 conchFile->openFlags = O_RDWR | O_CREAT; in proxyBreakConchLock()
46255 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; in proxyConchLock()
46256 unixFile *conchFile = pCtx->conchFile; in proxyConchLock()
46263 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); in proxyConchLock()
46273 if( osFstat(conchFile->h, &buf) ){ in proxyConchLock()
46292 int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0); in proxyConchLock()
46314 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK); in proxyConchLock()
46317 rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType); in proxyConchLock()
46327 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
46333 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; in proxyTakeConch()
46335 if( pCtx->conchHeld!=0 ){ in proxyTakeConch()
46338 unixFile *conchFile = pCtx->conchFile; in proxyTakeConch()
46351 OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h, in proxyTakeConch()
46352 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), in proxyTakeConch()
46368 storeLastErrno(pFile, conchFile->lastErrno); in proxyTakeConch()
46380 ** retry with a new auto-generated path in proxyTakeConch()
46382 do { /* in case we need to try again for an :auto: named lock file */ in proxyTakeConch()
46388 if( !pCtx->lockProxyPath ){ in proxyTakeConch()
46389 /* for auto-named local lock file, just check the host ID and we'll in proxyTakeConch()
46393 size_t pathLen = (readLen - PROXY_PATHINDEX); in proxyTakeConch()
46396 pathLen=MAXPATHLEN-1; in proxyTakeConch()
46406 && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX], in proxyTakeConch()
46407 readLen-PROXY_PATHINDEX) in proxyTakeConch()
46415 if( (conchFile->openFlags&O_RDWR) == 0 ){ in proxyTakeConch()
46421 if( !pCtx->lockProxyPath ){ in proxyTakeConch()
46422 proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN); in proxyTakeConch()
46431 futimes(conchFile->h, NULL); in proxyTakeConch()
46433 if( conchFile->pInode && conchFile->pInode->nShared>1 ){ in proxyTakeConch()
46434 /* We are trying for an exclusive lock but another thread in this in proxyTakeConch()
46449 if( pCtx->lockProxyPath!=NULL ){ in proxyTakeConch()
46450 strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, in proxyTakeConch()
46456 robust_ftruncate(conchFile->h, writeSize); in proxyTakeConch()
46458 full_fsync(conchFile->h,0,0); in proxyTakeConch()
46464 int err = osFstat(pFile->h, &buf); in proxyTakeConch()
46470 osFchmod(conchFile->h, cmode); in proxyTakeConch()
46473 rc = osFchmod(conchFile->h, cmode); in proxyTakeConch()
46474 }while( rc==(-1) && errno==EINTR ); in proxyTakeConch()
46490 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK); in proxyTakeConch()
46493 OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h)); in proxyTakeConch()
46494 if( rc==SQLITE_OK && pFile->openFlags ){ in proxyTakeConch()
46496 if( pFile->h>=0 ){ in proxyTakeConch()
46497 robust_close(pFile, pFile->h, __LINE__); in proxyTakeConch()
46499 pFile->h = -1; in proxyTakeConch()
46500 fd = robust_open(pCtx->dbPath, pFile->openFlags, 0); in proxyTakeConch()
46503 pFile->h = fd; in proxyTakeConch()
46509 if( rc==SQLITE_OK && !pCtx->lockProxy ){ in proxyTakeConch()
46510 char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath; in proxyTakeConch()
46511 rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1); in proxyTakeConch()
46514 ** so try again via auto-naming in proxyTakeConch()
46526 pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath); in proxyTakeConch()
46527 if( !pCtx->lockProxyPath ){ in proxyTakeConch()
46533 pCtx->conchHeld = 1; in proxyTakeConch()
46535 if( pCtx->lockProxy->pMethod == &afpIoMethods ){ in proxyTakeConch()
46537 afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext; in proxyTakeConch()
46538 afpCtx->dbPath = pCtx->lockProxyPath; in proxyTakeConch()
46541 conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); in proxyTakeConch()
46543 OSTRACE(("TAKECONCH %d %s\n", conchFile->h, in proxyTakeConch()
46546 } while (1); /* in case we need to retry the :auto: lock file - in proxyTakeConch()
46559 pCtx = (proxyLockingContext *)pFile->lockingContext; in proxyReleaseConch()
46560 conchFile = pCtx->conchFile; in proxyReleaseConch()
46561 OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h, in proxyReleaseConch()
46562 (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), in proxyReleaseConch()
46564 if( pCtx->conchHeld>0 ){ in proxyReleaseConch()
46565 rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK); in proxyReleaseConch()
46567 pCtx->conchHeld = 0; in proxyReleaseConch()
46568 OSTRACE(("RELEASECONCH %d %s\n", conchFile->h, in proxyReleaseConch()
46586 int len = (int)strlen(dbPath); /* Length of database filename - dbPath */ in proxyCreateConchPathname()
46598 for( i=(len-1); i>=0; i-- ){ in proxyCreateConchPathname()
46610 /* append the "-conch" suffix to the file */ in proxyCreateConchPathname()
46611 memcpy(&conchPath[i+1], "-conch", 7); in proxyCreateConchPathname()
46618 /* Takes a fully configured proxy locking-style unix file and switches
46622 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; in switchLockProxyPath()
46623 char *oldPath = pCtx->lockProxyPath; in switchLockProxyPath()
46626 if( pFile->eFileLock!=NO_LOCK ){ in switchLockProxyPath()
46635 unixFile *lockProxy = pCtx->lockProxy; in switchLockProxyPath()
46636 pCtx->lockProxy=NULL; in switchLockProxyPath()
46637 pCtx->conchHeld = 0; in switchLockProxyPath()
46639 rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy); in switchLockProxyPath()
46644 pCtx->lockProxyPath = sqlite3DbStrDup(0, path); in switchLockProxyPath()
46659 if( pFile->pMethod == &afpIoMethods ){ in proxyGetDbPathForUnixFile()
46662 assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); in proxyGetDbPathForUnixFile()
46663 strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, in proxyGetDbPathForUnixFile()
46667 if( pFile->pMethod == &dotlockIoMethods ){ in proxyGetDbPathForUnixFile()
46670 int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX); in proxyGetDbPathForUnixFile()
46671 memcpy(dbPath, (char *)pFile->lockingContext, len + 1); in proxyGetDbPathForUnixFile()
46674 assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN ); in proxyGetDbPathForUnixFile()
46675 strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN); in proxyGetDbPathForUnixFile()
46681 ** Takes an already filled in unix file and alters it so all file locking
46685 ** ->lockingContext
46686 ** ->pMethod
46694 if( pFile->eFileLock!=NO_LOCK ){ in proxyTransformUnixFile()
46704 OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h, in proxyTransformUnixFile()
46713 rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath); in proxyTransformUnixFile()
46715 rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0); in proxyTransformUnixFile()
46716 if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){ in proxyTransformUnixFile()
46718 ** (c) the file system is read-only, then enable no-locking access. in proxyTransformUnixFile()
46726 if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) { in proxyTransformUnixFile()
46728 if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){ in proxyTransformUnixFile()
46733 pCtx->conchHeld = -1; /* read only FS/ lockless */ in proxyTransformUnixFile()
46739 pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath); in proxyTransformUnixFile()
46743 pCtx->dbPath = sqlite3DbStrDup(0, dbPath); in proxyTransformUnixFile()
46744 if( pCtx->dbPath==NULL ){ in proxyTransformUnixFile()
46752 pCtx->oldLockingContext = pFile->lockingContext; in proxyTransformUnixFile()
46753 pFile->lockingContext = pCtx; in proxyTransformUnixFile()
46754 pCtx->pOldMethod = pFile->pMethod; in proxyTransformUnixFile()
46755 pFile->pMethod = &proxyIoMethods; in proxyTransformUnixFile()
46757 if( pCtx->conchFile ){ in proxyTransformUnixFile()
46758 pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile); in proxyTransformUnixFile()
46759 sqlite3_free(pCtx->conchFile); in proxyTransformUnixFile()
46761 sqlite3DbFree(0, pCtx->lockProxyPath); in proxyTransformUnixFile()
46762 sqlite3_free(pCtx->conchFilePath); in proxyTransformUnixFile()
46765 OSTRACE(("TRANSPROXY %d %s\n", pFile->h, in proxyTransformUnixFile()
46779 if( pFile->pMethod == &proxyIoMethods ){ in proxyFileControl()
46780 proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext; in proxyFileControl()
46782 if( pCtx->lockProxyPath ){ in proxyFileControl()
46783 *(const char **)pArg = pCtx->lockProxyPath; in proxyFileControl()
46795 int isProxyStyle = (pFile->pMethod == &proxyIoMethods); in proxyFileControl()
46798 /* turn off proxy locking - not supported. If support is added for in proxyFileControl()
46804 /* turn off proxy locking - already off - NOOP */ in proxyFileControl()
46811 (proxyLockingContext*)pFile->lockingContext; in proxyFileControl()
46813 || (pCtx->lockProxyPath && in proxyFileControl()
46814 !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN)) in proxyFileControl()
46837 ** above this point are all utilities. The lock-related methods of the
46838 ** proxy-locking sqlite3_io_method object follow.
46845 ** to a non-zero value otherwise *pResOut is set to zero. The return value
46846 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
46852 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; in proxyCheckReservedLock()
46853 if( pCtx->conchHeld>0 ){ in proxyCheckReservedLock()
46854 unixFile *proxy = pCtx->lockProxy; in proxyCheckReservedLock()
46855 return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut); in proxyCheckReservedLock()
46864 ** Lock the file with the lock specified by parameter eFileLock - one
46878 ** UNLOCKED -> SHARED
46879 ** SHARED -> RESERVED
46880 ** SHARED -> (PENDING) -> EXCLUSIVE
46881 ** RESERVED -> (PENDING) -> EXCLUSIVE
46882 ** PENDING -> EXCLUSIVE
46891 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; in proxyLock()
46892 if( pCtx->conchHeld>0 ){ in proxyLock()
46893 unixFile *proxy = pCtx->lockProxy; in proxyLock()
46894 rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock); in proxyLock()
46895 pFile->eFileLock = proxy->eFileLock; in proxyLock()
46909 ** the requested locking level, this routine is a no-op.
46915 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; in proxyUnlock()
46916 if( pCtx->conchHeld>0 ){ in proxyUnlock()
46917 unixFile *proxy = pCtx->lockProxy; in proxyUnlock()
46918 rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock); in proxyUnlock()
46919 pFile->eFileLock = proxy->eFileLock; in proxyUnlock()
46933 proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; in proxyClose()
46934 unixFile *lockProxy = pCtx->lockProxy; in proxyClose()
46935 unixFile *conchFile = pCtx->conchFile; in proxyClose()
46939 rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK); in proxyClose()
46941 rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy); in proxyClose()
46944 pCtx->lockProxy = 0; in proxyClose()
46947 if( pCtx->conchHeld ){ in proxyClose()
46951 rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile); in proxyClose()
46955 sqlite3DbFree(0, pCtx->lockProxyPath); in proxyClose()
46956 sqlite3_free(pCtx->conchFilePath); in proxyClose()
46957 sqlite3DbFree(0, pCtx->dbPath); in proxyClose()
46959 pFile->lockingContext = pCtx->oldLockingContext; in proxyClose()
46960 pFile->pMethod = pCtx->pOldMethod; in proxyClose()
46962 return pFile->pMethod->xClose(id); in proxyClose()
46982 ** This routine registers all VFS implementations for unix-like operating
46994 ** The following macro defines an initializer for an sqlite3_vfs object. in sqlite3_os_init()
46999 ** when compiling with -pedantic-errors on GCC.) in sqlite3_os_init()
47002 ** finder-function. The finder-function returns a pointer to the in sqlite3_os_init()
47005 ** macro for addition information on finder-functions. in sqlite3_os_init()
47010 ** database file and tries to choose an locking method appropriate for in sqlite3_os_init()
47053 UNIXVFS("unix-none", nolockIoFinder ), in sqlite3_os_init()
47054 UNIXVFS("unix-dotfile", dotlockIoFinder ), in sqlite3_os_init()
47055 UNIXVFS("unix-excl", posixIoFinder ), in sqlite3_os_init()
47057 UNIXVFS("unix-namedsem", semIoFinder ), in sqlite3_os_init()
47060 UNIXVFS("unix-posix", posixIoFinder ), in sqlite3_os_init()
47063 UNIXVFS("unix-flock", flockIoFinder ), in sqlite3_os_init()
47066 UNIXVFS("unix-afp", afpIoFinder ), in sqlite3_os_init()
47067 UNIXVFS("unix-nfs", nfsIoFinder ), in sqlite3_os_init()
47068 UNIXVFS("unix-proxy", proxyIoFinder ), in sqlite3_os_init()
47073 /* Double-check that the aSyscall[] array has been constructed in sqlite3_os_init()
47099 ** READ-0 UNIX_SHM_BASE+3 123 in sqlite3_os_init()
47100 ** READ-1 UNIX_SHM_BASE+4 124 in sqlite3_os_init()
47101 ** READ-2 UNIX_SHM_BASE+5 125 in sqlite3_os_init()
47102 ** READ-3 UNIX_SHM_BASE+6 126 in sqlite3_os_init()
47103 ** READ-4 UNIX_SHM_BASE+7 127 in sqlite3_os_init()
47106 assert( UNIX_SHM_DMS==128 ); /* Byte offset of the deadman-switch */ in sqlite3_os_init()
47120 ** This routine is a no-op for unix.
47174 ** based on the sub-platform)?
47182 ** based on the sub-platform)?
47270 ** characters, so we allocate 4 bytes per character assuming worst-case of
47271 ** 4-bytes-per-character for UTF8.
47294 ** Returns non-zero if the character should be treated as a directory
47358 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
47371 typedef struct winShm winShm; /* A connection to shared-memory */
47372 typedef struct winShmNode winShmNode; /* A region of shared-memory */
47384 BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
47427 # define winFileBusyTimeout(pDbFd) pDbFd->iBusyTimeout
47440 BOOL bNoLock; /* Non-zero if locking is disabled. */
47454 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
47464 * If this is non-zero, an isolated heap will be created by the native Win32
47467 * and an isolated heap will be created to store all allocated data.
47470 * WARNING: It is important to note that when this setting is non-zero and the
47474 * data will almost certainly result in an immediate access violation.
47482 * This is the maximum possible initial size of the Win32-specific heap, in
47490 * This is the extra space for the initial size of the Win32-specific heap,
47503 # define SQLITE_WIN32_MAX_CACHE_SIZE (((SQLITE_WIN32_HEAP_MAX_INIT_SIZE) - \
47510 * Win32-specific heap. It cannot be negative.
47516 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
47522 * initial size of the Win32-specific heap to exceed the maximum amount
47531 * The initial size of the Win32-specific heap. This value may be zero.
47540 * The maximum size of the Win32-specific heap. This value may be zero.
47556 ** The winMemData structure stores information required by the Win32-specific
47640 ** Many system calls are accessed through pointer-to-functions so that
47881 ** an ANSI string regardless of the _UNICODE setting */
48265 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
48468 int i = -1; in winNextSystemCall()
48472 for(i=0; i<ArraySize(aSyscall)-1; i++){ in winNextSystemCall()
48487 ** "pnLargest" argument, if non-zero, will be used to return the size of the
48578 int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */ in sqlite3_win32_write_debug()
48579 if( nMin<-1 ) nMin = -1; /* all negative values become -1. */ in sqlite3_win32_write_debug()
48580 assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE ); in sqlite3_win32_write_debug()
48647 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
48650 ** Here is an interesting observation: Win95, Win98, and WinME lack
48675 ** NOTE: The WinRT sub-platform is always assumed to be based on the NT in sqlite3_win32_is_nt()
48702 ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are in sqlite3_win32_is_nt()
48754 ** Change the size of an existing memory allocation
48782 ** Return the size of an outstanding allocation, in bytes.
48797 if( n==(SIZE_T)-1 ){ in winMemSize()
48819 assert( pWinMemData->magic1==WINMEM_MAGIC1 ); in winMemInit()
48820 assert( pWinMemData->magic2==WINMEM_MAGIC2 ); in winMemInit()
48823 if( !pWinMemData->hHeap ){ in winMemInit()
48831 pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS, in winMemInit()
48833 if( !pWinMemData->hHeap ){ in winMemInit()
48840 pWinMemData->bOwned = TRUE; in winMemInit()
48841 assert( pWinMemData->bOwned ); in winMemInit()
48844 pWinMemData->hHeap = osGetProcessHeap(); in winMemInit()
48845 if( !pWinMemData->hHeap ){ in winMemInit()
48850 pWinMemData->bOwned = FALSE; in winMemInit()
48851 assert( !pWinMemData->bOwned ); in winMemInit()
48853 assert( pWinMemData->hHeap!=0 ); in winMemInit()
48854 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); in winMemInit()
48856 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); in winMemInit()
48868 assert( pWinMemData->magic1==WINMEM_MAGIC1 ); in winMemShutdown()
48869 assert( pWinMemData->magic2==WINMEM_MAGIC2 ); in winMemShutdown()
48871 if( pWinMemData->hHeap ){ in winMemShutdown()
48872 assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE ); in winMemShutdown()
48874 assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) ); in winMemShutdown()
48876 if( pWinMemData->bOwned ){ in winMemShutdown()
48877 if( !osHeapDestroy(pWinMemData->hHeap) ){ in winMemShutdown()
48879 osGetLastError(), (void*)pWinMemData->hHeap); in winMemShutdown()
48881 pWinMemData->bOwned = FALSE; in winMemShutdown()
48883 pWinMemData->hHeap = NULL; in winMemShutdown()
48888 ** Populate the low-level memory allocation function pointers in
48916 ** Convert a UTF-8 string to Microsoft Unicode.
48924 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0); in winUtf8ToUnicode()
48932 nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText, in winUtf8ToUnicode()
48943 ** Convert a Microsoft Unicode string to UTF-8.
48951 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0); in winUnicodeToUtf8()
48959 nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte, in winUnicodeToUtf8()
48969 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
48979 nWideChar = osMultiByteToWideChar(codepage, 0, zText, -1, NULL, in winMbcsToUnicode()
48988 nWideChar = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText, in winMbcsToUnicode()
48999 ** Convert a Microsoft Unicode string to a multi-byte character string,
49009 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0); in winUnicodeToMbcs()
49017 nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText, in winUnicodeToMbcs()
49028 ** Convert a multi-byte character string to UTF-8.
49047 ** Convert a UTF-8 string to a multi-byte character string.
49164 ** it accepts a UTF-8 string.
49208 ** it accepts a UTF-16 string.
49242 ** is zero if the error message fits in the buffer, or non-zero
49322 ** This function - winLogErrorAtLine() - is only ever called via the macro
49325 ** This routine is invoked after an error occurs in an OS function.
49327 ** error code and, if possible, the human-readable equivalent from
49333 ** failed and the associated file-system path, if any.
49353 "os_win.c:%d: (%lu) %s(%s) - %s", in winLogErrorAtLine()
49362 ** will be retried following a locking error - probably caused by
49379 ** non-zero if the error code is transient in nature and the operation
49404 ** to give up with an error.
49467 y.tm_year = pTm.wYear - 1900; in localtime()
49468 y.tm_mon = pTm.wMonth - 1; in localtime()
49482 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
49516 memset(&pFile->local, 0, sizeof(pFile->local)); in winceCreateLock()
49526 pFile->hMutex = osCreateMutexW(NULL, FALSE, zName); in winceCreateLock()
49527 if (!pFile->hMutex){ in winceCreateLock()
49528 pFile->lastErrno = osGetLastError(); in winceCreateLock()
49530 return winLogError(SQLITE_IOERR, pFile->lastErrno, in winceCreateLock()
49535 winceMutexAcquire(pFile->hMutex); in winceCreateLock()
49538 ** case-sensitive, take advantage of that by uppercasing the mutex name in winceCreateLock()
49542 pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL, in winceCreateLock()
49547 ** must be zero-initialized */ in winceCreateLock()
49556 if( pFile->hShared ){ in winceCreateLock()
49557 pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared, in winceCreateLock()
49560 if( !pFile->shared ){ in winceCreateLock()
49561 pFile->lastErrno = osGetLastError(); in winceCreateLock()
49562 winLogError(SQLITE_IOERR, pFile->lastErrno, in winceCreateLock()
49565 osCloseHandle(pFile->hShared); in winceCreateLock()
49566 pFile->hShared = NULL; in winceCreateLock()
49571 if( pFile->hShared==NULL ){ in winceCreateLock()
49573 pFile->lastErrno = lastErrno; in winceCreateLock()
49574 winLogError(SQLITE_IOERR, pFile->lastErrno, in winceCreateLock()
49578 winceMutexRelease(pFile->hMutex); in winceCreateLock()
49579 osCloseHandle(pFile->hMutex); in winceCreateLock()
49580 pFile->hMutex = NULL; in winceCreateLock()
49586 memset(pFile->shared, 0, sizeof(winceLock)); in winceCreateLock()
49589 winceMutexRelease(pFile->hMutex); in winceCreateLock()
49597 if (pFile->hMutex){ in winceDestroyLock()
49599 winceMutexAcquire(pFile->hMutex); in winceDestroyLock()
49603 if (pFile->local.nReaders){ in winceDestroyLock()
49604 pFile->shared->nReaders --; in winceDestroyLock()
49606 if (pFile->local.bReserved){ in winceDestroyLock()
49607 pFile->shared->bReserved = FALSE; in winceDestroyLock()
49609 if (pFile->local.bPending){ in winceDestroyLock()
49610 pFile->shared->bPending = FALSE; in winceDestroyLock()
49612 if (pFile->local.bExclusive){ in winceDestroyLock()
49613 pFile->shared->bExclusive = FALSE; in winceDestroyLock()
49616 /* De-reference and close our copy of the shared memory handle */ in winceDestroyLock()
49617 osUnmapViewOfFile(pFile->shared); in winceDestroyLock()
49618 osCloseHandle(pFile->hShared); in winceDestroyLock()
49621 winceMutexRelease(pFile->hMutex); in winceDestroyLock()
49622 osCloseHandle(pFile->hMutex); in winceDestroyLock()
49623 pFile->hMutex = NULL; in winceDestroyLock()
49628 ** An implementation of the LockFile() API of Windows for CE
49643 if (!pFile->hMutex) return TRUE; in winceLockFile()
49644 winceMutexAcquire(pFile->hMutex); in winceLockFile()
49646 /* Wanting an exclusive lock? */ in winceLockFile()
49649 if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){ in winceLockFile()
49650 pFile->shared->bExclusive = TRUE; in winceLockFile()
49651 pFile->local.bExclusive = TRUE; in winceLockFile()
49656 /* Want a read-only lock? */ in winceLockFile()
49659 if (pFile->shared->bExclusive == 0){ in winceLockFile()
49660 pFile->local.nReaders ++; in winceLockFile()
49661 if (pFile->local.nReaders == 1){ in winceLockFile()
49662 pFile->shared->nReaders ++; in winceLockFile()
49672 if (pFile->shared->bPending == 0) { in winceLockFile()
49673 pFile->shared->bPending = TRUE; in winceLockFile()
49674 pFile->local.bPending = TRUE; in winceLockFile()
49682 if (pFile->shared->bReserved == 0) { in winceLockFile()
49683 pFile->shared->bReserved = TRUE; in winceLockFile()
49684 pFile->local.bReserved = TRUE; in winceLockFile()
49689 winceMutexRelease(pFile->hMutex); in winceLockFile()
49694 ** An implementation of the UnlockFile API of Windows for CE
49709 if (!pFile->hMutex) return TRUE; in winceUnlockFile()
49710 winceMutexAcquire(pFile->hMutex); in winceUnlockFile()
49712 /* Releasing a reader lock or an exclusive lock */ in winceUnlockFile()
49714 /* Did we have an exclusive lock? */ in winceUnlockFile()
49715 if (pFile->local.bExclusive){ in winceUnlockFile()
49717 pFile->local.bExclusive = FALSE; in winceUnlockFile()
49718 pFile->shared->bExclusive = FALSE; in winceUnlockFile()
49723 else if (pFile->local.nReaders){ in winceUnlockFile()
49726 pFile->local.nReaders --; in winceUnlockFile()
49727 if (pFile->local.nReaders == 0) in winceUnlockFile()
49729 pFile->shared->nReaders --; in winceUnlockFile()
49738 if (pFile->local.bPending){ in winceUnlockFile()
49739 pFile->local.bPending = FALSE; in winceUnlockFile()
49740 pFile->shared->bPending = FALSE; in winceUnlockFile()
49747 if (pFile->local.bReserved) { in winceUnlockFile()
49748 pFile->local.bReserved = FALSE; in winceUnlockFile()
49749 pFile->shared->bReserved = FALSE; in winceUnlockFile()
49754 winceMutexRelease(pFile->hMutex); in winceUnlockFile()
49798 ** Take an EXCLUSIVE lock if parameter bExclusive is true, or a SHARED lock
49804 ** SQLITE_BUSY_TIMEOUT otherwise. Or, if an error occurs, SQLITE_IOERR.
49837 /* If SQLITE_ENABLE_SETLK_TIMEOUT is defined, then the file-handle was in winHandleLockTimeout()
49913 ** Remove an nByte lock starting at offset iOff from HANDLE h.
49929 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
49935 ** If successful, return SQLITE_OK. Or, if an error occurs, return an SQLite
49952 ** containing the lower 32-bits of the new file-offset. Or, if it fails, in winHandleSeek()
49955 ** whether an error has actually occurred, it is also necessary to call in winHandleSeek()
49983 ** Otherwise, set pFile->lastErrno and return non-zero.
49988 rc = winHandleSeek(pFile->h, iOffset); in winSeekFile()
49990 pFile->lastErrno = osGetLastError(); in winSeekFile()
49991 winLogError(rc, pFile->lastErrno, "winSeekFile", pFile->zPath); in winSeekFile()
50006 ** It is reported that an attempt to close a handle might sometimes
50011 ** giving up and returning an error.
50020 assert( pFile->pShm==0 ); in winClose()
50022 assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE ); in winClose()
50024 osGetCurrentProcessId(), pFile, pFile->h)); in winClose()
50031 rc = osCloseHandle(pFile->h); in winClose()
50037 winVfsAppData *pAppData = (winVfsAppData*)pFile->pVfs->pAppData; in winClose()
50038 if( pAppData==NULL || !pAppData->bNoLock ){ in winClose()
50042 if( pFile->zDeleteOnClose ){ in winClose()
50045 osDeleteFileW(pFile->zDeleteOnClose)==0 in winClose()
50046 && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff in winClose()
50051 sqlite3_free(pFile->zDeleteOnClose); in winClose()
50055 pFile->h = NULL; in winClose()
50057 OpenCounter(-1); in winClose()
50059 osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed")); in winClose()
50062 "winClose", pFile->zPath); in winClose()
50089 pFile->h, pBuf, amt, offset, pFile->locktype));
50094 if( offset<pFile->mmapSize ){
50095 if( offset+amt <= pFile->mmapSize ){
50096 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
50097 OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
50098 osGetCurrentProcessId(), pFile, pFile->h));
50101 int nCopy = (int)(pFile->mmapSize - offset);
50102 memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
50104 amt -= nCopy;
50113 osGetCurrentProcessId(), pFile, pFile->h));
50116 while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
50121 while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
50126 pFile->lastErrno = lastErrno;
50128 osGetCurrentProcessId(), pFile, pFile->h));
50129 return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
50130 "winRead", pFile->zPath);
50134 /* Unread parts of the buffer must be zero-filled */
50135 memset(&((char*)pBuf)[nRead], 0, amt-nRead);
50137 osGetCurrentProcessId(), pFile, pFile->h));
50142 osGetCurrentProcessId(), pFile, pFile->h));
50167 pFile->h, pBuf, amt, offset, pFile->locktype));
50172 if( offset<pFile->mmapSize ){
50173 if( offset+amt <= pFile->mmapSize ){
50174 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
50175 OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
50176 osGetCurrentProcessId(), pFile, pFile->h));
50179 int nCopy = (int)(pFile->mmapSize - offset);
50180 memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
50182 amt -= nCopy;
50210 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
50212 if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
50228 nRem -= nWrite;
50231 pFile->lastErrno = lastErrno;
50237 if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
50238 || ( pFile->lastErrno==ERROR_DISK_FULL )){
50240 osGetCurrentProcessId(), pFile, pFile->h));
50241 return winLogError(SQLITE_FULL, pFile->lastErrno,
50242 "winWrite1", pFile->zPath);
50245 osGetCurrentProcessId(), pFile, pFile->h));
50246 return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
50247 "winWrite2", pFile->zPath);
50252 osGetCurrentProcessId(), pFile, pFile->h));
50311 ** Truncate an open file to a specified size
50319 if( pFile->nFetchOut>0 ){
50320 /* File truncation is a no-op if there are outstanding memory mapped
50325 ** if there is an active read cursor when the incremental vacuum occurs.
50326 ** No real harm comes of this - the database file is not corrupted,
50330 ** The only feasible work-around is to defer the truncation until after
50331 ** all references to memory-mapped content are closed. That is doable,
50334 ** now to simply make transactions a no-op if there are pending reads. We
50344 osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
50346 /* If the user has configured a chunk-size for this file, truncate the
50347 ** file so that it consists of an integer number of chunks (i.e. the
50351 if( pFile->szChunk>0 ){
50352 nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
50356 if( pFile->pMapRegion ){
50357 oldMmapSize = pFile->mmapSize;
50364 /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
50366 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
50367 "winTruncate1", pFile->zPath);
50368 }else if( 0==osSetEndOfFile(pFile->h) &&
50370 pFile->lastErrno = lastErrno;
50371 rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
50372 "winTruncate2", pFile->zPath);
50378 winMapfile(pFile, -1);
50386 osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
50432 osGetCurrentProcessId(), pFile, pFile->h, flags,
50433 pFile->locktype));
50445 ** no-op
50448 OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
50449 osGetCurrentProcessId(), pFile, pFile->h));
50453 if( pFile->pMapRegion ){
50454 if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
50455 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
50457 pFile, pFile->pMapRegion));
50459 pFile->lastErrno = osGetLastError();
50460 OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
50462 pFile, pFile->pMapRegion));
50463 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
50464 "winSync1", pFile->zPath);
50468 rc = osFlushFileBuffers(pFile->h);
50472 osGetCurrentProcessId(), pFile, pFile->h));
50475 pFile->lastErrno = osGetLastError();
50477 osGetCurrentProcessId(), pFile, pFile->h));
50478 return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
50479 "winSync2", pFile->zPath);
50494 OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
50499 if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
50503 pFile->lastErrno = osGetLastError();
50504 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
50505 "winFileSize", pFile->zPath);
50514 lowerBits = osGetFileSize(pFile->h, &upperBits);
50518 pFile->lastErrno = lastErrno;
50519 rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
50520 "winFileSize", pFile->zPath);
50525 pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
50544 ** obtain an exclusive lock. These flags are used with the LockFileEx function
50568 OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
50575 res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
50577 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS&mask, SHARED_FIRST, 0,
50585 pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
50586 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS&mask,
50587 SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
50591 pFile->lastErrno = osGetLastError();
50594 OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
50604 OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
50606 res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
50610 res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
50614 pFile->lastErrno = lastErrno;
50615 winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
50616 "winUnlockReadLock", pFile->zPath);
50618 OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
50623 ** Lock the file with the lock specified by parameter locktype - one
50637 ** UNLOCKED -> SHARED
50638 ** SHARED -> RESERVED
50639 ** SHARED -> (PENDING) -> EXCLUSIVE
50640 ** RESERVED -> (PENDING) -> EXCLUSIVE
50641 ** PENDING -> EXCLUSIVE
50651 int newLocktype; /* Set pFile->locktype to this value before exiting */
50658 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
50664 if( pFile->locktype>=locktype ){
50665 OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
50669 /* Do not allow any kind of write-lock on a read-only database
50671 if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
50677 assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
50679 assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
50681 /* Lock the PENDING_LOCK byte if we need to acquire an EXCLUSIVE lock or
50685 newLocktype = pFile->locktype;
50687 || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
50691 /* Flags for the LockFileEx() call. This should be an exclusive lock if
50700 ** around problems caused by indexing and/or anti-virus software on
50705 res = winLockFile(&pFile->h, flags, PENDING_BYTE, 0, 1, 0);
50709 OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
50710 pFile->h, cnt, res
50714 pFile->lastErrno = lastErrno;
50716 OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
50717 pFile->h, cnt, sqlite3ErrName(rc)
50722 cnt--;
50731 assert( pFile->locktype==NO_LOCK );
50733 res = winGetReadLock(pFile, pFile->bBlockOnConnect);
50747 assert( pFile->locktype==SHARED_LOCK );
50748 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
50763 /* Acquire an EXCLUSIVE lock
50766 assert( pFile->locktype>=SHARED_LOCK );
50768 res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
50782 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
50791 pFile->lastErrno = lastErrno;
50793 OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
50794 pFile->h, locktype, newLocktype));
50796 pFile->locktype = (u8)newLocktype;
50798 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
50805 ** non-zero, otherwise zero.
50812 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
50815 if( pFile->locktype>=RESERVED_LOCK ){
50817 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
50819 res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
50821 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
50824 OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
50827 OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
50828 pFile->h, pResOut, *pResOut));
50837 ** the requested locking level, this routine is a no-op.
50850 pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
50851 type = pFile->locktype;
50853 winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
50858 "winUnlock", pFile->zPath);
50862 winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
50868 winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
50870 pFile->locktype = (u8)locktype;
50872 pFile->h, pFile->locktype, sqlite3ErrName(rc)));
50877 ****************************** No-op Locking **********************************
50883 ** This locking mode is appropriate for use on read-only databases
50884 ** (ex: databases that are burned into CD-ROM, for example.) It can
50911 /******************* End of the no-op lock implementation *********************
50916 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
50918 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
50922 *pArg = (pFile->ctrlFlags & mask)!=0;
50924 pFile->ctrlFlags &= ~mask;
50926 pFile->ctrlFlags |= mask;
50941 OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
50944 *(int*)pArg = pFile->locktype;
50945 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50949 *(int*)pArg = (int)pFile->lastErrno;
50950 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50954 pFile->szChunk = *(int *)pArg;
50955 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50959 if( pFile->szChunk>0 ){
50970 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
50973 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50978 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50983 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
50987 *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
50988 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
51003 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
51008 *phFile = pFile->h;
51009 OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
51015 HANDLE hOldFile = pFile->h;
51016 pFile->h = *phFile;
51019 hOldFile, pFile->h));
51024 (void)osCloseHandle(pFile->h);
51025 pFile->h = NULL;
51030 int rc = winGetTempname(pFile->pVfs, &zTFile);
51034 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
51047 ** least a 64-bit type. */
51052 *(i64*)pArg = pFile->mmapSizeMax;
51053 if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
51054 pFile->mmapSizeMax = newLimit;
51055 if( pFile->mmapSize>0 ){
51057 rc = winMapfile(pFile, -1);
51060 OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
51067 int iOld = pFile->iBusyTimeout;
51070 pFile->iBusyTimeout = (iNew < 0) ? INFINITE : (DWORD)iNew;
51072 pFile->iBusyTimeout = (DWORD)(!!iNew);
51081 pFile->bBlockOnConnect = iNew;
51087 OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
51097 ** if two files are created in the same file-system directory (i.e.
51112 ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
51154 ** log-summary, each thread has its own winFile object, but they all
51156 ** log-summary is opened only once per process.
51164 ** The following fields are read-only after the object is created:
51172 ** File-handle hSharedShm is used to (a) take the DMS lock, (b) truncate
51173 ** the *-shm file if the DMS-locking protocol demands it, and (c) map
51174 ** regions of the *-shm file into memory using MapViewOfFile() or
51184 int isReadonly; /* True if read-only */
51185 int szRegion; /* Size of shared-memory regions */
51209 ** Structure used internally by this VFS to record the state of an
51217 HANDLE hShm; /* File-handle on *-shm file. For locking. */
51218 int bReadonly; /* True if hShm is opened read-only */
51237 ** This is not a VFS shared-memory method; it is a utility function called
51238 ** by VFS shared-memory methods.
51244 OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
51248 if( p->nRef==0 ){
51250 if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
51251 for(i=0; i<p->nRegion; i++){
51252 BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
51253 OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
51256 bRc = osCloseHandle(p->aRegion[i].hMap);
51257 OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
51261 winHandleClose(p->hSharedShm);
51265 winDelete(pVfs, p->zFilename, 0);
51269 *pp = p->pNext;
51270 sqlite3_free(p->aRegion);
51273 pp = &p->pNext;
51280 ** pShmNode. Take the lock. Truncate the *-shm file if required.
51281 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
51284 HANDLE h = pShmNode->hSharedShm;
51287 assert( sqlite3_mutex_held(pShmNode->mutex) );
51290 /* We have an EXCLUSIVE lock on the DMS byte. This means that this
51293 if( pShmNode->isReadonly ){
51309 pShmNode->isUnlocked = 0;
51318 ** Convert a UTF-8 filename into whatever form the underlying
51324 ** - If the filename starts with "<drive>:/" or "<drive>:\",
51325 ** it is converted to UTF-16 as-is.
51326 ** - If the filename contains '/', it is assumed to be a
51328 ** absolute path in UTF-16.
51329 ** - Otherwise it must be a filename only, the win32 filename
51330 ** is returned in UTF-16.
51332 ** UTF-8 -> UTF-16 conversion will be done. This can only
51375 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
51383 nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1,
51415 ** This function is used to open a handle on a *-shm file.
51452 ** TODO: retry-on-ioerr.
51479 /* Due to pre-processor directives earlier in this file,
51511 ** Open the shared-memory area associated with database file pDbFd.
51520 assert( pDbFd->pShm==0 ); /* Not previously opened */
51526 nName = sqlite3Strlen30(pDbFd->zPath);
51532 pNew->zFilename = (char*)&pNew[1];
51533 pNew->hSharedShm = INVALID_HANDLE_VALUE;
51534 pNew->isUnlocked = 1;
51535 sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
51536 sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
51538 /* Open a file-handle on the *-shm file for this connection. This file-handle
51539 ** is only used for locking. The mapping of the *-shm file is created using
51541 p->bReadonly = sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0);
51542 rc = winHandleOpen(pNew->zFilename, &p->bReadonly, &p->hShm);
51544 /* Look to see if there is an existing winShmNode that can be used.
51547 for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
51550 if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
51557 pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
51558 if( pShmNode->mutex==0 ) rc = SQLITE_IOERR_NOMEM_BKPT;
51561 /* Open a file-handle to use for mappings, and for the DMS lock. */
51564 pShmNode->isReadonly = p->bReadonly;
51565 rc = winHandleOpen(pNew->zFilename, &pShmNode->isReadonly, &h);
51566 pShmNode->hSharedShm = h;
51569 /* If successful, link the new winShmNode into the global list. If an
51572 pShmNode->pNext = winShmNodeList;
51576 sqlite3_mutex_free(pShmNode->mutex);
51577 if( pShmNode->hSharedShm!=INVALID_HANDLE_VALUE ){
51578 osCloseHandle(pShmNode->hSharedShm);
51586 p->pShmNode = pShmNode;
51587 pShmNode->nRef++;
51589 p->id = pShmNode->nextShmId++;
51591 pDbFd->pShm = p;
51593 winHandleClose(p->hShm);
51597 assert( rc!=SQLITE_OK || pShmNode->isUnlocked==0 || pShmNode->nRegion==0 );
51604 ** Close a connection to shared-memory. Delete the underlying
51611 winFile *pDbFd; /* Database holding shared-memory */
51613 winShmNode *pShmNode; /* The underlying shared-memory file */
51616 p = pDbFd->pShm;
51618 if( p->hShm!=INVALID_HANDLE_VALUE ){
51619 osCloseHandle(p->hShm);
51622 pShmNode = p->pShmNode;
51625 /* If pShmNode->nRef has reached 0, then close the underlying
51626 ** shared-memory file, too. */
51627 assert( pShmNode->nRef>0 );
51628 pShmNode->nRef--;
51629 if( pShmNode->nRef==0 ){
51630 winShmPurge(pDbFd->pVfs, deleteFlag);
51636 pDbFd->pShm = 0;
51641 ** Change the lock state for a shared-memory segment.
51650 winShm *p = pDbFd->pShm; /* The shared memory being locked */
51653 u16 mask = (u16)((1U<<(ofst+n)) - (1U<<ofst)); /* Mask of locks to [un]take */
51656 pShmNode = p->pShmNode;
51681 u16 lockMask = (p->exclMask|p->sharedMask);
51682 assert( (flags & SQLITE_SHM_UNLOCK) || pDbFd->iBusyTimeout==0 || (
51693 ** a) An unlock operation where there are locks to unlock,
51694 ** b) An shared lock where the requested lock is not already held
51695 ** c) An exclusive lock where the requested lock is not already held
51697 ** The SQLite core never requests an exclusive lock that it already holds.
51700 || 0==(p->exclMask & mask)
51702 if( ((flags & SQLITE_SHM_UNLOCK) && ((p->exclMask|p->sharedMask) & mask))
51703 || (flags==(SQLITE_SHM_SHARED|SQLITE_SHM_LOCK) && 0==(p->sharedMask & mask))
51708 /* Case (a) - unlock. */
51710 assert( (p->exclMask & p->sharedMask)==0 );
51711 assert( !(flags & SQLITE_SHM_EXCLUSIVE) || (p->exclMask & mask)==mask );
51712 assert( !(flags & SQLITE_SHM_SHARED) || (p->sharedMask & mask)==mask );
51714 rc = winHandleUnlock(p->hShm, ofst+WIN_SHM_BASE, n);
51718 p->exclMask = (p->exclMask & ~mask);
51719 p->sharedMask = (p->sharedMask & ~mask);
51724 rc = winHandleLockTimeout(p->hShm, ofst+WIN_SHM_BASE, n, bExcl, nMs);
51727 p->exclMask = (p->exclMask | mask);
51729 p->sharedMask = (p->sharedMask | mask);
51736 "SHM-LOCK(%d,%d,%d) pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x,"
51739 osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
51755 sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
51762 ** shared-memory associated with the database file fd. Shared-memory regions
51763 ** are numbered starting from zero. Each shared-memory region is szRegion
51766 ** If an error occurs, an error code is returned and *pp is set to NULL.
51768 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
51771 ** isWrite is non-zero and the requested shared-memory region has not yet
51774 ** If the shared-memory region has already been allocated or is allocated by
51787 winShm *pShm = pDbFd->pShm;
51796 pShm = pDbFd->pShm;
51799 pShmNode = pShm->pShmNode;
51801 sqlite3_mutex_enter(pShmNode->mutex);
51802 if( pShmNode->isUnlocked ){
51804 assert( pShmNode->nRegion==0 );
51809 assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
51810 if( pShmNode->nRegion<=iRegion ){
51811 HANDLE hShared = pShmNode->hSharedShm;
51814 sqlite3_int64 sz; /* Current size of wal-index file */
51816 pShmNode->szRegion = szRegion;
51819 ** Check to see if it has been allocated (i.e. if the wal-index file is
51824 rc = winLogError(rc, osGetLastError(), "winShmMap1", pDbFd->zPath);
51832 ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
51837 rc = winLogError(rc, osGetLastError(), "winShmMap2", pDbFd->zPath);
51844 pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
51850 pShmNode->aRegion = apNew;
51852 if( pShmNode->isReadonly ){
51857 while( pShmNode->nRegion<=iRegion ){
51858 HANDLE hMap = NULL; /* file-mapping handle */
51869 OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
51870 osGetCurrentProcessId(), pShmNode->nRegion, nByte,
51873 int iOffset = pShmNode->nRegion*szRegion;
51877 iOffset - iOffsetShift, szRegion + iOffsetShift
51881 0, iOffset - iOffsetShift, szRegion + iOffsetShift
51884 OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
51885 osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
51889 pShmNode->lastErrno = osGetLastError();
51890 rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
51891 "winShmMap3", pDbFd->zPath);
51896 pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
51897 pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
51898 pShmNode->nRegion++;
51903 if( pShmNode->nRegion>iRegion ){
51906 char *p = (char *)pShmNode->aRegion[iRegion].pMap;
51911 if( pShmNode->isReadonly && rc==SQLITE_OK ){
51914 sqlite3_mutex_leave(pShmNode->mutex);
51931 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
51933 osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
51934 pFile->mmapSize, pFile->mmapSizeMax));
51935 if( pFile->pMapRegion ){
51936 if( !osUnmapViewOfFile(pFile->pMapRegion) ){
51937 pFile->lastErrno = osGetLastError();
51938 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
51940 pFile->pMapRegion));
51941 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
51942 "winUnmapfile1", pFile->zPath);
51944 pFile->pMapRegion = 0;
51945 pFile->mmapSize = 0;
51947 if( pFile->hMap!=NULL ){
51948 if( !osCloseHandle(pFile->hMap) ){
51949 pFile->lastErrno = osGetLastError();
51950 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
51951 osGetCurrentProcessId(), pFile, pFile->hMap));
51952 return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
51953 "winUnmapfile2", pFile->zPath);
51955 pFile->hMap = NULL;
51957 OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
51963 ** Memory map or remap the file opened by file-descriptor pFd (if the file
51966 ** outstanding xFetch() references to it, this function is a no-op.
51968 ** If parameter nByte is non-negative, then it is the requested size of
51975 ** recreated as a result of outstanding references) or an SQLite error
51982 assert( nMap>=0 || pFd->nFetchOut==0 );
51983 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
51986 if( pFd->nFetchOut>0 ) return SQLITE_OK;
51991 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
51996 if( nMap>pFd->mmapSizeMax ){
51997 nMap = pFd->mmapSizeMax;
51999 nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
52001 if( nMap==0 && pFd->mmapSize>0 ){
52004 if( nMap!=pFd->mmapSize ){
52011 if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
52017 pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
52019 pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
52023 pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
52027 if( pFd->hMap==NULL ){
52028 pFd->lastErrno = osGetLastError();
52029 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
52030 "winMapfile1", pFd->zPath);
52032 OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
52039 pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
52041 pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
52044 osCloseHandle(pFd->hMap);
52045 pFd->hMap = NULL;
52046 pFd->lastErrno = osGetLastError();
52047 rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
52048 "winMapfile2", pFd->zPath);
52050 OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
52054 pFd->pMapRegion = pNew;
52055 pFd->mmapSize = nMap;
52058 OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
52070 ** Finally, if an error does occur, return an SQLite error code. The final
52086 if( pFd->mmapSizeMax>0 ){
52092 if( pFd->pMapRegion==0 ){
52093 int rc = winMapfile(pFd, -1);
52100 if( pFd->mmapSize >= (iOff+nAmt+nEofBuffer) ){
52101 assert( pFd->pMapRegion!=0 );
52102 *pp = &((u8 *)pFd->pMapRegion)[iOff];
52103 pFd->nFetchOut++;
52114 ** If the third argument is non-NULL, then this function releases a
52115 ** reference obtained by an earlier call to winFetch(). The second
52128 ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
52130 assert( (p==0)==(pFd->nFetchOut==0) );
52133 assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
52139 pFd->nFetchOut--;
52143 ** is unnecessary can be omitted - potentially improving
52148 assert( pFd->nFetchOut>=0 );
52163 ** This vector defines all the methods that can operate on an
52189 ** This vector defines all the methods that can operate on an
52234 ** This function returns non-zero if the specified UTF-8 string buffer
52242 if( winIsDirSep(zBuf[nLen-1]) ){
52289 /* It's odd to simulate an io-error here, but really this is just
52290 ** using the io-error infrastructure to test that SQLite handles this
52298 nMax = pVfs->mxPathname;
52302 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
52310 nDir = nMax - (nPre + 15);
52315 if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
52321 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
52363 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
52383 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
52389 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
52401 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
52411 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
52416 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
52426 OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
52434 ** Check to make sure the temporary directory ends with an appropriate
52440 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
52458 OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
52462 sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
52470 zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
52476 OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
52518 ** The Windows version of xAccess() accepts an extra bit in the flags
52519 ** parameter that prevents an anti-virus retry loop.
52528 const char *zName, /* Name of the file (UTF-8) */
52545 const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
52588 /* The main DB, main journal, WAL file and super-journal are never
52595 /* Assert that the upper layer has set one of the "file-type" flags. */
52604 pFile->h = INVALID_HANDLE_VALUE;
52626 /* Database filenames are double-zero terminated if they are not
52772 pFile->lastErrno = lastErrno;
52773 winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
52790 pAppData = (winVfsAppData*)pVfs->pAppData;
52795 && ((pAppData==NULL) || !pAppData->bNoLock)
52801 OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
52806 pFile->zDeleteOnClose = zConverted;
52814 id->pMethods = pAppData ? pAppData->pMethod : &winIoMethod;
52815 pFile->pVfs = pVfs;
52816 pFile->h = h;
52818 pFile->ctrlFlags |= WINFILE_RDONLY;
52823 pFile->ctrlFlags |= WINFILE_PSOW;
52825 pFile->lastErrno = NO_ERROR;
52826 pFile->zPath = zName;
52828 pFile->hMap = NULL;
52829 pFile->pMapRegion = 0;
52830 pFile->mmapSize = 0;
52831 pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
52848 ** up and returning an error.
53003 /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
53049 ** Returns non-zero if the specified path name starts with the "long path"
53060 ** Returns non-zero if the specified path name starts with a drive letter
53071 ** Returns non-zero if the specified path name should be used verbatim. If
53072 ** non-zero is returned from this function, the calling function must simply
53073 ** use the provided path name verbatim -OR- resolve it into a full path name
53081 ** a legal UNC name, a volume relative path, or an absolute path name in the
53092 ** relative path or an absolute path. Callers of this function must not
53117 ** Changes are made in-place. Return the new name length.
53120 ** no-longer used bytes will be written by '\0'.
53127 /* Some test-cases assume that "./foo" and "foo" are different */
53154 if( osGetcwd(zOut, nOut-2)==0 ){
53161 /* SQLite assumes that xFullPathname() nul-terminates the output buffer
53162 ** even if it returns an error. */
53166 sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
53173 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
53200 zFull[nFull-1] = '\0';
53233 nByte = osReadlink(zIn, zDel, nFull-1);
53234 if( nByte ==(DWORD)-1 ){
53239 for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
53274 /* WinRT has no way to convert a relative path to an absolute one. */
53279 ** for converting the relative path name to an absolute
53282 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
53285 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
53292 /* It's odd to simulate an io-error here, but really this is just
53293 ** using the io-error infrastructure to test that SQLite handles this
53302 ** for converting the relative path name to an absolute
53305 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
53368 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
53370 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut+4);
53381 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut+6);
53384 sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
53474 for(j=0, k=p->i; j<sz; j++){
53475 p->a[k++] ^= x[j];
53476 if( k>=p->na ) k = 0;
53478 p->i = k;
53479 p->nXor += sz;
53550 ** The following variable, if set to a non-zero value, is interpreted as
53569 /* FILETIME structure is a 64-bit value representing the number of
53570 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
53577 /* 2^32 - to avoid use of LL and warnings in gcc */
53624 ** strerror_r() on Unix). After an error is returned by an OS
53627 ** buffer with a nul-terminated UTF-8 encoded error message
53633 ** is zero if the error message fits in the buffer, or non-zero
53634 ** otherwise (if the message was truncated). If non-zero is returned,
53635 ** then it is not necessary to include the nul-terminator character
53638 ** Not supplying an error message will have no adverse effect
53639 ** on SQLite. It is fine to have an implementation that never
53640 ** returns an error message:
53647 ** However if an error message is supplied, it will be incorporated
53692 "win32-longpath", /* zName */
53717 "win32-none", /* zName */
53742 "win32-longpath-none", /* zName */
53763 /* Double-check that the aSyscall[] array has been constructed
53816 ** 2016-09-07
53827 ** This file implements an in-memory VFS. A database is held as a contiguous
53843 /* Access to a lower-level VFS that (might) implement dynamic loading,
53846 #define ORIGVFS(p) ((sqlite3_vfs*)((p)->pAppData))
53850 ** An memdb object can be shared or separate. Shared memdb objects can be
53859 ** memdb objects are stored in memdb_g.apMemStore[] in an arbitrary order.
53898 /* An open file */
53906 ** File-scope variables for holding the memdb files that are accessible
54010 sqlite3_mutex_enter(p->pMutex);
54013 sqlite3_mutex_leave(p->pMutex);
54020 ** Close an memdb-file.
54025 MemStore *p = ((MemFile*)pFile)->pStore;
54026 if( p->zFName ){
54035 if( p->nRef==1 ){
54036 memdb_g.apMemStore[i] = memdb_g.apMemStore[--memdb_g.nMemStore];
54049 p->nRef--;
54050 if( p->nRef<=0 ){
54051 if( p->mFlags & SQLITE_DESERIALIZE_FREEONCLOSE ){
54052 sqlite3_free(p->aData);
54055 sqlite3_mutex_free(p->pMutex);
54064 ** Read data from an memdb-file.
54072 MemStore *p = ((MemFile*)pFile)->pStore;
54074 if( iOfst+iAmt>p->sz ){
54076 if( iOfst<p->sz ) memcpy(zBuf, p->aData+iOfst, p->sz - iOfst);
54080 memcpy(zBuf, p->aData+iOfst, iAmt);
54090 if( (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)==0 || NEVER(p->nMmap>0) ){
54093 if( newSz>p->szMax ){
54097 if( newSz>p->szMax ) newSz = p->szMax;
54098 pNew = sqlite3Realloc(p->aData, newSz);
54100 p->aData = pNew;
54101 p->szAlloc = newSz;
54106 ** Write data to an memdb-file.
54114 MemStore *p = ((MemFile*)pFile)->pStore;
54116 if( NEVER(p->mFlags & SQLITE_DESERIALIZE_READONLY) ){
54122 if( iOfst+iAmt>p->sz ){
54124 if( iOfst+iAmt>p->szAlloc
54130 if( iOfst>p->sz ) memset(p->aData+p->sz, 0, iOfst-p->sz);
54131 p->sz = iOfst+iAmt;
54133 memcpy(p->aData+iOfst, z, iAmt);
54139 ** Truncate an memdb-file.
54146 MemStore *p = ((MemFile*)pFile)->pStore;
54149 if( size>p->sz ){
54153 p->sz = size;
54160 ** Sync an memdb-file.
54169 ** Return the current file-size of an memdb-file.
54172 MemStore *p = ((MemFile*)pFile)->pStore;
54174 *pSize = p->sz;
54180 ** Lock an memdb-file.
54184 MemStore *p = pThis->pStore;
54186 if( eLock<=pThis->eLock ) return SQLITE_OK;
54189 assert( p->nWrLock==0 || p->nWrLock==1 );
54190 assert( pThis->eLock<=SQLITE_LOCK_SHARED || p->nWrLock==1 );
54191 assert( pThis->eLock==SQLITE_LOCK_NONE || p->nRdLock>=1 );
54193 if( eLock>SQLITE_LOCK_SHARED && (p->mFlags & SQLITE_DESERIALIZE_READONLY) ){
54198 assert( pThis->eLock==SQLITE_LOCK_NONE );
54199 if( p->nWrLock>0 ){
54202 p->nRdLock++;
54209 assert( pThis->eLock>=SQLITE_LOCK_SHARED );
54210 if( ALWAYS(pThis->eLock==SQLITE_LOCK_SHARED) ){
54211 if( p->nWrLock>0 ){
54214 p->nWrLock = 1;
54222 assert( pThis->eLock>=SQLITE_LOCK_SHARED );
54223 if( p->nRdLock>1 ){
54225 }else if( pThis->eLock==SQLITE_LOCK_SHARED ){
54226 p->nWrLock = 1;
54232 if( rc==SQLITE_OK ) pThis->eLock = eLock;
54238 ** Unlock an memdb-file.
54242 MemStore *p = pThis->pStore;
54243 if( eLock>=pThis->eLock ) return SQLITE_OK;
54248 if( ALWAYS(pThis->eLock>SQLITE_LOCK_SHARED) ){
54249 p->nWrLock--;
54252 if( pThis->eLock>SQLITE_LOCK_SHARED ){
54253 p->nWrLock--;
54255 p->nRdLock--;
54258 pThis->eLock = eLock;
54266 ** occur on an in-memory database.
54276 ** File control method. For custom operations on an memdb-file.
54279 MemStore *p = ((MemFile*)pFile)->pStore;
54283 *(char**)pArg = sqlite3_mprintf("memdb(%p,%lld)", p->aData, p->sz);
54288 if( iLimit<p->sz ){
54290 iLimit = p->szMax;
54292 iLimit = p->sz;
54295 p->szMax = iLimit;
54305 ** Return the sector-size in bytes for an memdb-file.
54313 ** Return the device characteristic flags supported by an memdb-file.
54323 /* Fetch a page of a memory-mapped file */
54330 MemStore *p = ((MemFile*)pFile)->pStore;
54332 if( iOfst+iAmt>p->sz || (p->mFlags & SQLITE_DESERIALIZE_RESIZEABLE)!=0 ){
54335 p->nMmap++;
54336 *pp = (void*)(p->aData + iOfst);
54342 /* Release a memory-mapped page */
54344 MemStore *p = ((MemFile*)pFile)->pStore;
54348 p->nMmap--;
54354 ** Open an mem file handle.
54377 if( strcmp(memdb_g.apMemStore[i]->zFName,zName)==0 ){
54399 p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE|SQLITE_DESERIALIZE_FREEONCLOSE;
54400 p->szMax = sqlite3GlobalConfig.mxMemdbSize;
54401 p->zFName = (char*)&p[1];
54402 memcpy(p->zFName, zName, szName+1);
54403 p->pMutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
54404 if( p->pMutex==0 ){
54405 memdb_g.nMemStore--;
54410 p->nRef = 1;
54414 p->nRef++;
54423 p->mFlags = SQLITE_DESERIALIZE_RESIZEABLE | SQLITE_DESERIALIZE_FREEONCLOSE;
54424 p->szMax = sqlite3GlobalConfig.mxMemdbSize;
54426 pFile->pStore = p;
54430 pFd->pMethods = &memdb_io_methods;
54435 #if 0 /* Only used to delete rollback journals, super-journals, and WAL
54439 ** ensure the file-system modifications are synced to disk before
54486 return ORIGVFS(pVfs)->xDlOpen(ORIGVFS(pVfs), zPath);
54491 ** utf-8 string describing the most recent error encountered associated
54495 ORIGVFS(pVfs)->xDlError(ORIGVFS(pVfs), nByte, zErrMsg);
54502 return ORIGVFS(pVfs)->xDlSym(ORIGVFS(pVfs), p, zSym);
54509 ORIGVFS(pVfs)->xDlClose(ORIGVFS(pVfs), pHandle);
54517 return ORIGVFS(pVfs)->xRandomness(ORIGVFS(pVfs), nByte, zBufOut);
54525 return ORIGVFS(pVfs)->xSleep(ORIGVFS(pVfs), nMicro);
54533 return ORIGVFS(pVfs)->xCurrentTime(ORIGVFS(pVfs), pTimeOut);
54538 return ORIGVFS(pVfs)->xGetLastError(ORIGVFS(pVfs), a, b);
54541 return ORIGVFS(pVfs)->xCurrentTimeInt64(ORIGVFS(pVfs), p);
54553 if( p->base.pMethods!=&memdb_io_methods ) return 0;
54554 pStore = p->pStore;
54556 if( pStore->zFName!=0 ) p = 0;
54587 if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
54590 if( piSize ) *piSize = -1;
54593 MemStore *pStore = p->pStore;
54594 assert( pStore->pMutex==0 );
54595 if( piSize ) *piSize = pStore->sz;
54597 pOut = pStore->aData;
54599 pOut = sqlite3_malloc64( pStore->sz );
54600 if( pOut ) memcpy(pOut, pStore->aData, pStore->sz);
54604 pBt = db->aDb[iDb].pBt;
54608 rc = zSql ? sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0) : SQLITE_NOMEM;
54635 unsigned char *pTo = pOut + szPage*(sqlite3_int64)(pgno-1);
54675 sqlite3_mutex_enter(db->mutex);
54676 if( zSchema==0 ) zSchema = db->aDb[0].zDbSName;
54687 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
54691 db->init.iDb = (u8)iDb;
54692 db->init.reopenMemdb = 1;
54694 db->init.reopenMemdb = 0;
54703 MemStore *pStore = p->pStore;
54704 pStore->aData = pData;
54706 pStore->sz = szDb;
54707 pStore->szAlloc = szBuf;
54708 pStore->szMax = szBuf;
54709 if( pStore->szMax<sqlite3GlobalConfig.mxMemdbSize ){
54710 pStore->szMax = sqlite3GlobalConfig.mxMemdbSize;
54712 pStore->mFlags = mFlags;
54721 sqlite3_mutex_leave(db->mutex);
54740 sz = pLower->szOsFile;
54765 ** This file implements an object that represents a fixed-length
54769 ** journalled during a transaction, or which pages have the "dont-write"
54798 (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
54815 ** sub-dividing and re-hashing. */
54819 ** (an arbitrary prime)in the hash function provided
54820 ** no fewer collisions than the no-op *1. */
54827 ** A bitmap is an instance of the following structure.
54840 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
54849 u32 nSet; /* Number of bits that are set - only valid for aHash
54873 p->iSize = iSize;
54879 ** Check to see if the i-th bit is set. Return true or false.
54885 i--;
54886 if( i>=p->iSize ) return 0;
54887 while( p->iDivisor ){
54888 u32 bin = i/p->iDivisor;
54889 i = i%p->iDivisor;
54890 p = p->u.apSub[bin];
54895 if( p->iSize<=BITVEC_NBIT ){
54896 return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
54899 while( p->u.aHash[h] ){
54900 if( p->u.aHash[h]==i ) return 1;
54911 ** Set the i-th bit. Return 0 on success and an error code if
54914 ** This routine might cause sub-bitmaps to be allocated. Failing
54915 ** to get the memory needed to hold the sub-bitmap is the only
54916 ** that can go wrong with an insert, assuming p and i are valid.
54926 assert( i<=p->iSize );
54927 i--;
54928 while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
54929 u32 bin = i/p->iDivisor;
54930 i = i%p->iDivisor;
54931 if( p->u.apSub[bin]==0 ){
54932 p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
54933 if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
54935 p = p->u.apSub[bin];
54937 if( p->iSize<=BITVEC_NBIT ){
54938 p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
54944 /* worrying about sub-dividing and re-hashing. */
54945 if( !p->u.aHash[h] ){
54946 if (p->nSet<(BITVEC_NINT-1)) {
54955 if( p->u.aHash[h]==i ) return SQLITE_OK;
54958 } while( p->u.aHash[h] );
54963 if( p->nSet>=BITVEC_MXHASH ){
54966 u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
54970 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
54971 memset(p->u.apSub, 0, sizeof(p->u.apSub));
54972 p->iDivisor = p->iSize/BITVEC_NPTR;
54973 if( (p->iSize%BITVEC_NPTR)!=0 ) p->iDivisor++;
54974 if( p->iDivisor<BITVEC_NBIT ) p->iDivisor = BITVEC_NBIT;
54984 p->nSet++;
54985 p->u.aHash[h] = i;
54990 ** Clear the i-th bit.
54998 i--;
54999 while( p->iDivisor ){
55000 u32 bin = i/p->iDivisor;
55001 i = i%p->iDivisor;
55002 p = p->u.apSub[bin];
55007 if( p->iSize<=BITVEC_NBIT ){
55008 p->u.aBitmap[i/BITVEC_SZELEM] &= ~(BITVEC_TELEM)(1<<(i&(BITVEC_SZELEM-1)));
55012 memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
55013 memset(p->u.aHash, 0, sizeof(p->u.aHash));
55014 p->nSet = 0;
55017 u32 h = BITVEC_HASH(aiValues[j]-1);
55018 p->nSet++;
55019 while( p->u.aHash[h] ){
55023 p->u.aHash[h] = aiValues[j];
55034 if( p->iDivisor ){
55037 sqlite3BitvecDestroy(p->u.apSub[i]);
55048 return p->iSize;
55053 ** Let V[] be an array of unsigned characters sufficient to hold
55054 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
55063 ** This routine runs an extensive test of the Bitvec code.
55065 ** The input is an array of integers that acts as a program
55088 ** an error is returned. If they are the same, zero is returned.
55090 ** If a memory allocation error occurs, return -1.
55095 int rc = -1;
55118 i = aOp[pc+2] - 1;
55130 if( (--aOp[pc+1]) > 0 ) nx = 0;
55146 ** match (rc==0). Change rc to non-zero if a discrepancy
55151 + (sqlite3BitvecSize(pBitvec) - sz);
55186 ** A complete page cache is an instance of this structure. Every
55197 ** such that p was added to the list more recently than p->pDirtyNext.
55202 ** page to eject from the cache mid-transaction. It is better to eject
55245 pPg = (PgHdr*)pLower->pExtra;
55246 printf("%3d: nRef %2lld flgs %02x data ", i, pPg->nRef, pPg->flags);
55247 a = (unsigned char *)pLower->pBuf;
55258 if( pCache->pCache==0 ) return;
55262 pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
55264 if( pLower && ((PgHdr*)pLower)->pPage==0 ){
55265 sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
55282 for(p=pCache->pDirty; p; p=p->pDirtyNext){
55289 for(p=pCache->pDirty; p; p=p->pDirtyNext){
55312 assert( pPg->pgno>0 || pPg->pPager==0 ); /* Page number is 1 or more */
55313 pCache = pPg->pCache;
55314 assert( pCache!=0 ); /* Every page has an associated PCache */
55315 if( pPg->flags & PGHDR_CLEAN ){
55316 assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
55319 assert( (pPg->flags & PGHDR_DIRTY)!=0 );/* If not CLEAN must be DIRTY */
55320 assert( pPg->pDirtyNext==0 || pPg->pDirtyNext->pDirtyPrev==pPg );
55321 assert( pPg->pDirtyPrev==0 || pPg->pDirtyPrev->pDirtyNext==pPg );
55322 assert( pPg->pDirtyPrev!=0 || pCache->pDirty==pPg );
55326 if( pPg->flags & PGHDR_WRITEABLE ){
55327 assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
55365 PCache *p = pPage->pCache;
55369 pPage->pgno));
55371 assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
55372 assert( pPage->pDirtyPrev || pPage==p->pDirty );
55375 if( p->pSynced==pPage ){
55376 p->pSynced = pPage->pDirtyPrev;
55379 if( pPage->pDirtyNext ){
55380 pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
55382 assert( pPage==p->pDirtyTail );
55383 p->pDirtyTail = pPage->pDirtyPrev;
55385 if( pPage->pDirtyPrev ){
55386 pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
55389 ** This is an optimization that allows sqlite3PcacheFetch() to skip
55392 assert( pPage==p->pDirty );
55393 p->pDirty = pPage->pDirtyNext;
55394 assert( p->bPurgeable || p->eCreate==2 );
55395 if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
55396 assert( p->bPurgeable==0 || p->eCreate==1 );
55397 p->eCreate = 2;
55402 pPage->pDirtyPrev = 0;
55403 pPage->pDirtyNext = p->pDirty;
55404 if( pPage->pDirtyNext ){
55405 assert( pPage->pDirtyNext->pDirtyPrev==0 );
55406 pPage->pDirtyNext->pDirtyPrev = pPage;
55408 p->pDirtyTail = pPage;
55409 if( p->bPurgeable ){
55410 assert( p->eCreate==2 );
55411 p->eCreate = 1;
55414 p->pDirty = pPage;
55417 ** pSynced to point to it. Checking the NEED_SYNC flag is an
55420 ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
55421 if( !p->pSynced
55422 && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
55424 p->pSynced = pPage;
55432 ** being used for an in-memory database, this function is a no-op.
55435 if( p->pCache->bPurgeable ){
55436 pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
55437 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
55438 pcacheDump(p->pCache);
55443 ** Compute the number of pages of cache requested. p->szCache is the
55447 if( p->szCache>=0 ){
55448 /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
55450 return p->szCache;
55453 /* IMPLEMENTATION-OF: R-59858-46238 If the argument N is negative, then the
55457 n = ((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
55470 /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
55471 ** built-in default page cache is used instead of the application defined
55480 /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
55511 p->szPage = 1;
55512 p->szExtra = szExtra;
55514 p->bPurgeable = bPurgeable;
55515 p->eCreate = 2;
55516 p->xStress = xStress;
55517 p->pStress = pStress;
55518 p->szCache = 100;
55519 p->szSpill = 1;
55529 assert( pCache->nRefSum==0 && pCache->pDirty==0 );
55530 if( pCache->szPage ){
55533 szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
55534 pCache->bPurgeable
55538 if( pCache->pCache ){
55539 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
55541 pCache->pCache = pNew;
55542 pCache->szPage = szPage;
55551 ** This routine returns a pointer to an sqlite3_pcache_page object if
55552 ** such an object is already in cache, or if a new one is created.
55581 assert( pCache->pCache!=0 );
55583 assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
55592 eCreate = createFlag & pCache->eCreate;
55594 assert( createFlag==0 || pCache->eCreate==eCreate );
55595 assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
55596 pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
55610 ** an OOM error.
55620 if( pCache->eCreate==2 ) return 0;
55622 if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
55623 /* Find a dirty page to write-out and recycle. First try to find a
55624 ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
55631 ** cleared). This is Ok, as pSynced is just an optimization. */
55632 for(pPg=pCache->pSynced;
55633 pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
55634 pPg=pPg->pDirtyPrev
55636 pCache->pSynced = pPg;
55638 for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
55644 "spill page %d making room for %d - cache used: %d/%d",
55645 pPg->pgno, pgno,
55646 sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache),
55649 pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
55650 rc = pCache->xStress(pCache->pStress, pPg);
55657 *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
55677 pPgHdr = (PgHdr*)pPage->pExtra;
55678 assert( pPgHdr->pPage==0 );
55679 memset(&pPgHdr->pDirty, 0, sizeof(PgHdr) - offsetof(PgHdr,pDirty));
55680 pPgHdr->pPage = pPage;
55681 pPgHdr->pData = pPage->pBuf;
55682 pPgHdr->pExtra = (void *)&pPgHdr[1];
55683 memset(pPgHdr->pExtra, 0, 8);
55684 assert( EIGHT_BYTE_ALIGNMENT( pPgHdr->pExtra ) );
55685 pPgHdr->pCache = pCache;
55686 pPgHdr->pgno = pgno;
55687 pPgHdr->flags = PGHDR_CLEAN;
55693 ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
55705 pPgHdr = (PgHdr *)pPage->pExtra;
55707 if( !pPgHdr->pPage ){
55710 pCache->nRefSum++;
55711 pPgHdr->nRef++;
55721 assert( p->nRef>0 );
55722 p->pCache->nRefSum--;
55723 if( (--p->nRef)==0 ){
55724 if( p->flags&PGHDR_CLEAN ){
55737 assert(p->nRef>0);
55739 p->nRef++;
55740 p->pCache->nRefSum++;
55749 assert( p->nRef==1 );
55751 if( p->flags&PGHDR_DIRTY ){
55754 p->pCache->nRefSum--;
55755 sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
55763 assert( p->nRef>0 );
55765 if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
55766 p->flags &= ~PGHDR_DONT_WRITE;
55767 if( p->flags & PGHDR_CLEAN ){
55768 p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
55769 pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
55770 assert( (p->flags & (PGHDR_DIRTY|PGHDR_CLEAN))==PGHDR_DIRTY );
55784 assert( (p->flags & PGHDR_DIRTY)!=0 );
55785 assert( (p->flags & PGHDR_CLEAN)==0 );
55787 p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
55788 p->flags |= PGHDR_CLEAN;
55789 pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
55791 if( p->nRef==0 ){
55801 pcacheTrace(("%p.CLEAN-ALL\n",pCache));
55802 while( (p = pCache->pDirty)!=0 ){
55812 pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
55813 for(p=pCache->pDirty; p; p=p->pDirtyNext){
55814 p->flags &= ~(PGHDR_NEED_SYNC|PGHDR_WRITEABLE);
55816 pCache->pSynced = pCache->pDirtyTail;
55824 for(p=pCache->pDirty; p; p=p->pDirtyNext){
55825 p->flags &= ~PGHDR_NEED_SYNC;
55827 pCache->pSynced = pCache->pDirtyTail;
55834 PCache *pCache = p->pCache;
55836 assert( p->nRef>0 );
55839 pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
55840 pOther = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, newPgno, 0);
55842 PgHdr *pXPage = (PgHdr*)pOther->pExtra;
55843 assert( pXPage->nRef==0 );
55844 pXPage->nRef++;
55845 pCache->nRefSum++;
55848 sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
55849 p->pgno = newPgno;
55850 if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
55866 if( pCache->pCache ){
55870 for(p=pCache->pDirty; p; p=pNext){
55871 pNext = p->pDirtyNext;
55876 assert( p->pgno>0 );
55877 if( p->pgno>pgno ){
55878 assert( p->flags&PGHDR_DIRTY );
55882 if( pgno==0 && pCache->nRefSum ){
55884 pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
55886 ** pCache->nRefSum>0 */
55887 memset(pPage1->pBuf, 0, pCache->szPage);
55891 sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
55899 assert( pCache->pCache!=0 );
55901 sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
55920 if( pA->pgno<pB->pgno ){
55921 pTail->pDirty = pA;
55923 pA = pA->pDirty;
55925 pTail->pDirty = pB;
55929 pTail->pDirty = pB;
55931 pB = pB->pDirty;
55933 pTail->pDirty = pA;
55958 pIn = p->pDirty;
55959 p->pDirty = 0;
55960 for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
55969 if( NEVER(i==N_SORT_BUCKET-1) ){
55989 for(p=pCache->pDirty; p; p=p->pDirtyNext){
55990 p->pDirty = p->pDirtyNext;
55992 return pcacheSortDirtyList(pCache->pDirty);
56002 return pCache->nRefSum;
56006 ** Return the number of references to the page supplied as an argument.
56009 return p->nRef;
56016 assert( pCache->pCache!=0 );
56017 return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
56022 ** Get the suggested cache-size value.
56030 ** Set the suggested cache-size value.
56033 assert( pCache->pCache!=0 );
56034 pCache->szCache = mxPage;
56035 sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
56040 ** Set the suggested cache-spill value. Make no changes if if the
56041 ** argument is zero. Return the effective cache-spill size, which will
56046 assert( p->pCache!=0 );
56049 mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
56051 p->szSpill = mxPage;
56054 if( res<p->szSpill ) res = p->szSpill;
56062 assert( pCache->pCache!=0 );
56063 sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
56068 ** in the page-cache hierarchy.
56080 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
56089 return (pCache->pDirty!=0);
56101 for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
56129 ** -------------------------------------------------------------
56131 ** -------------------------------------------------------------
56138 ** of which pages are "dirty". PgHdr1 is an extension added by this
56147 ** size can vary according to architecture, compile-time options, and
56153 ** allocations. However, the btree layer needs a small (16-byte) overrun
56168 ** (1) The general-purpose memory allocator - sqlite3Malloc()
56169 ** (2) Global page-cache memory provided using sqlite3_config() with
56171 ** (3) PCache-local bulk allocation.
56181 ** Or if N is negative, then -1024*N bytes of memory are allocated and used
56185 ** (3) is exhausted, subsequent allocations fail over to the general-purpose
56200 ** Each cache entry is represented by an instance of the following
56201 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated
56207 ** object is positioned immediately after the page buffer to serve as an
56211 ** but causes a 2-byte gap in the structure for most architectures (since
56212 ** pointers must be either 4 or 8-byte aligned). As this structure is located
56214 ** corrupt, code at the b-tree layer may overread the page buffer and
56220 ** The pLruNext and pLruPrev pointers form a double-linked circular list
56241 #define PAGE_IS_PINNED(p) ((p)->pLruNext==0)
56242 #define PAGE_IS_UNPINNED(p) ((p)->pLruNext!=0)
56246 ** pages when they are under memory pressure. A PGroup is an instance of
56270 unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
56275 /* Each page cache is an instance of the following object. Every
56276 ** open database file (including each in-memory database and each
56278 ** is an instance of this object.
56291 unsigned int *pnPurgeable; /* Pointer to pGroup->nPurgeable */
56309 PgHdr1 *pFree; /* List of unused pcache-local pages */
56310 void *pBulk; /* Bulk memory used by pcache-local */
56357 # define pcache1EnterMutex(X) assert((X)->mutex==0)
56358 # define pcache1LeaveMutex(X) assert((X)->mutex==0)
56361 # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
56362 # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
56372 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
56373 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
56391 while( n-- ){
56393 p->pNext = pcache1.pFree;
56402 ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
56403 ** true if pCache->pFree ends up containing one or more free pages.
56410 if( pCache->nMax<3 ) return 0;
56413 szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
56415 szBulk = -1024 * (i64)pcache1.nInitPage;
56417 if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
56418 szBulk = pCache->szAlloc*(i64)pCache->nMax;
56420 zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
56423 int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
56425 PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
56426 pX->page.pBuf = zBulk;
56427 pX->page.pExtra = (u8*)pX + ROUND8(sizeof(*pX));
56428 assert( EIGHT_BYTE_ALIGNMENT( pX->page.pExtra ) );
56429 pX->isBulkLocal = 1;
56430 pX->isAnchor = 0;
56431 pX->pNext = pCache->pFree;
56432 pX->pLruPrev = 0; /* Initializing this saves a valgrind error */
56433 pCache->pFree = pX;
56434 zBulk += pCache->szAlloc;
56435 }while( --nBulk );
56437 return pCache->pFree!=0;
56456 pcache1.pFree = pcache1.pFree->pNext;
56457 pcache1.nFreeSlot--;
56485 ** Free an allocated buffer obtained from pcache1Alloc().
56494 pSlot->pNext = pcache1.pFree;
56541 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
56542 if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
56543 assert( pCache->pFree!=0 );
56544 p = pCache->pFree;
56545 pCache->pFree = p->pNext;
56546 p->pNext = 0;
56553 assert( pCache->pGroup==&pcache1.grp );
56554 pcache1LeaveMutex(pCache->pGroup);
56557 pPg = pcache1Alloc(pCache->szAlloc);
56560 pcache1EnterMutex(pCache->pGroup);
56563 p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
56564 p->page.pBuf = pPg;
56565 p->page.pExtra = (u8*)p + ROUND8(sizeof(*p));
56566 assert( EIGHT_BYTE_ALIGNMENT( p->page.pExtra ) );
56567 p->isBulkLocal = 0;
56568 p->isAnchor = 0;
56569 p->pLruPrev = 0; /* Initializing this saves a valgrind error */
56571 (*pCache->pnPurgeable)++;
56581 pCache = p->pCache;
56582 assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
56583 if( p->isBulkLocal ){
56584 p->pNext = pCache->pFree;
56585 pCache->pFree = p;
56587 pcache1Free(p->page.pBuf);
56589 (*pCache->pnPurgeable)--;
56603 ** Free an allocated buffer obtained from sqlite3PageMalloc().
56627 if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
56648 assert( sqlite3_mutex_held(p->pGroup->mutex) );
56650 nNew = 2*(u64)p->nHash;
56655 pcache1LeaveMutex(p->pGroup);
56656 if( p->nHash ){ sqlite3BeginBenignMalloc(); }
56658 if( p->nHash ){ sqlite3EndBenignMalloc(); }
56659 pcache1EnterMutex(p->pGroup);
56661 for(i=0; i<p->nHash; i++){
56663 PgHdr1 *pNext = p->apHash[i];
56665 unsigned int h = pPage->iKey % nNew;
56666 pNext = pPage->pNext;
56667 pPage->pNext = apNew[h];
56671 sqlite3_free(p->apHash);
56672 p->apHash = apNew;
56673 p->nHash = nNew;
56680 ** LRU list, then this function is a no-op.
56687 assert( pPage->pLruNext );
56688 assert( pPage->pLruPrev );
56689 assert( sqlite3_mutex_held(pPage->pCache->pGroup->mutex) );
56690 pPage->pLruPrev->pLruNext = pPage->pLruNext;
56691 pPage->pLruNext->pLruPrev = pPage->pLruPrev;
56692 pPage->pLruNext = 0;
56693 /* pPage->pLruPrev = 0;
56695 assert( pPage->isAnchor==0 );
56696 assert( pPage->pCache->pGroup->lru.isAnchor==1 );
56697 pPage->pCache->nRecyclable--;
56703 ** Remove the page supplied as an argument from the hash table
56711 PCache1 *pCache = pPage->pCache;
56714 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
56715 h = pPage->iKey % pCache->nHash;
56716 for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
56717 *pp = (*pp)->pNext;
56719 pCache->nPage--;
56728 PGroup *pGroup = pCache->pGroup;
56730 assert( sqlite3_mutex_held(pGroup->mutex) );
56731 while( pGroup->nPurgeable>pGroup->nMaxPage
56732 && (p=pGroup->lru.pLruPrev)->isAnchor==0
56734 assert( p->pCache->pGroup==pGroup );
56739 if( pCache->nPage==0 && pCache->pBulk ){
56740 sqlite3_free(pCache->pBulk);
56741 pCache->pBulk = pCache->pFree = 0;
56756 TESTONLY( int nPage = 0; ) /* To assert pCache->nPage is correct */
56758 assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
56759 assert( pCache->iMaxKey >= iLimit );
56760 assert( pCache->nHash > 0 );
56761 if( pCache->iMaxKey - iLimit < pCache->nHash ){
56766 h = iLimit % pCache->nHash;
56767 iStop = pCache->iMaxKey % pCache->nHash;
56768 TESTONLY( nPage = -10; ) /* Disable the pCache->nPage validity check */
56772 h = pCache->nHash/2;
56773 iStop = h - 1;
56778 assert( h<pCache->nHash );
56779 pp = &pCache->apHash[h];
56781 if( pPage->iKey>=iLimit ){
56782 pCache->nPage--;
56783 *pp = pPage->pNext;
56787 pp = &pPage->pNext;
56792 h = (h+1) % pCache->nHash;
56794 assert( nPage<0 || pCache->nPage==(unsigned)nPage );
56811 ** private PGroup (mode-1). pcache1.separateCache is false if the single
56812 ** PGroup in pcache1.grp is used for all page caches (mode-2).
56814 ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
56816 ** * Use a unified cache in single-threaded applications that have
56817 ** configured a start-time buffer for use as page-cache memory using
56818 ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
56821 ** * Otherwise use separate caches (mode-1)
56875 assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
56883 pGroup->mxPinned = 10;
56888 if( pGroup->lru.isAnchor==0 ){
56889 pGroup->lru.isAnchor = 1;
56890 pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
56892 pCache->pGroup = pGroup;
56893 pCache->szPage = szPage;
56894 pCache->szExtra = szExtra;
56895 pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
56896 pCache->bPurgeable = (bPurgeable ? 1 : 0);
56899 pCache->nMin = 10;
56900 pGroup->nMinPage += pCache->nMin;
56901 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
56902 pCache->pnPurgeable = &pGroup->nPurgeable;
56904 pCache->pnPurgeable = &pCache->nPurgeableDummy;
56907 if( pCache->nHash==0 ){
56924 if( pCache->bPurgeable ){
56925 PGroup *pGroup = pCache->pGroup;
56928 if( n > 0x7fff0000 - pGroup->nMaxPage + pCache->nMax ){
56929 n = 0x7fff0000 - pGroup->nMaxPage + pCache->nMax;
56931 pGroup->nMaxPage += (n - pCache->nMax);
56932 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
56933 pCache->nMax = n;
56934 pCache->n90pct = pCache->nMax*9/10;
56947 if( pCache->bPurgeable ){
56948 PGroup *pGroup = pCache->pGroup;
56951 savedMaxPage = pGroup->nMaxPage;
56952 pGroup->nMaxPage = 0;
56954 pGroup->nMaxPage = savedMaxPage;
56965 pcache1EnterMutex(pCache->pGroup);
56966 n = pCache->nPage;
56967 pcache1LeaveMutex(pCache->pGroup);
56986 PGroup *pGroup = pCache->pGroup;
56990 assert( pCache->nPage >= pCache->nRecyclable );
56991 nPinned = pCache->nPage - pCache->nRecyclable;
56992 assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
56993 assert( pCache->n90pct == pCache->nMax*9/10 );
56995 nPinned>=pGroup->mxPinned
56996 || nPinned>=pCache->n90pct
56997 || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
57002 if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
57003 assert( pCache->nHash>0 && pCache->apHash );
57006 if( pCache->bPurgeable
57007 && !pGroup->lru.pLruPrev->isAnchor
57008 && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
57011 pPage = pGroup->lru.pLruPrev;
57015 pOther = pPage->pCache;
57016 if( pOther->szAlloc != pCache->szAlloc ){
57020 pGroup->nPurgeable -= (pOther->bPurgeable - pCache->bPurgeable);
57032 unsigned int h = iKey % pCache->nHash;
57033 pCache->nPage++;
57034 pPage->iKey = iKey;
57035 pPage->pNext = pCache->apHash[h];
57036 pPage->pCache = pCache;
57037 pPage->pLruNext = 0;
57038 /* pPage->pLruPrev = 0;
57040 *(void **)pPage->page.pExtra = 0;
57041 pCache->apHash[h] = pPage;
57042 if( iKey>pCache->iMaxKey ){
57043 pCache->iMaxKey = iKey;
57059 ** For a non-purgeable cache (a cache used as the storage for an in-memory
57062 ** a non-purgeable cache.
57105 ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
57116 /* Step 1: Search the hash table for an existing entry. */
57117 pPage = pCache->apHash[iKey % pCache->nHash];
57118 while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
57146 pcache1EnterMutex(pCache->pGroup);
57148 assert( pPage==0 || pCache->iMaxKey>=iKey );
57149 pcache1LeaveMutex(pCache->pGroup);
57163 assert( pCache->bPurgeable || createFlag!=1 );
57164 assert( pCache->bPurgeable || pCache->nMin==0 );
57165 assert( pCache->bPurgeable==0 || pCache->nMin==10 );
57166 assert( pCache->nMin==0 || pCache->bPurgeable );
57167 assert( pCache->nHash>0 );
57169 if( pCache->pGroup->mutex ){
57191 PGroup *pGroup = pCache->pGroup;
57193 assert( pPage->pCache==pCache );
57196 /* It is an error to call this function if the page is already
57199 assert( pPage->pLruNext==0 );
57202 if( reuseUnlikely || pGroup->nPurgeable>pGroup->nMaxPage ){
57206 PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
57207 pPage->pLruPrev = &pGroup->lru;
57208 (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
57210 pCache->nRecyclable++;
57213 pcache1LeaveMutex(pCache->pGroup);
57229 assert( pPage->iKey==iOld );
57230 assert( pPage->pCache==pCache );
57233 pcache1EnterMutex(pCache->pGroup);
57236 hOld = iOld%pCache->nHash;
57237 pp = &pCache->apHash[hOld];
57239 pp = &(*pp)->pNext;
57241 *pp = pPage->pNext;
57244 hNew = iNew%pCache->nHash;
57245 pPage->iKey = iNew;
57246 pPage->pNext = pCache->apHash[hNew];
57247 pCache->apHash[hNew] = pPage;
57248 if( iNew>pCache->iMaxKey ){
57249 pCache->iMaxKey = iNew;
57252 pcache1LeaveMutex(pCache->pGroup);
57264 pcache1EnterMutex(pCache->pGroup);
57265 if( iLimit<=pCache->iMaxKey ){
57267 pCache->iMaxKey = iLimit-1;
57269 pcache1LeaveMutex(pCache->pGroup);
57279 PGroup *pGroup = pCache->pGroup;
57280 assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
57282 if( pCache->nPage ) pcache1TruncateUnsafe(pCache, 0);
57283 assert( pGroup->nMaxPage >= pCache->nMax );
57284 pGroup->nMaxPage -= pCache->nMax;
57285 assert( pGroup->nMinPage >= pCache->nMin );
57286 pGroup->nMinPage -= pCache->nMin;
57287 pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
57290 sqlite3_free(pCache->pBulk);
57291 sqlite3_free(pCache->apHash);
57298 ** already provided an alternative.
57351 && p->isAnchor==0
57353 nFree += pcache1MemSize(p->page.pBuf);
57377 for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
57402 ** This module implements an object we call a "RowSet".
57405 ** are inserted into the RowSet in an arbitrary order. Inserts
57423 ** TEST checks to see if an element is already in the RowSet. SMALLEST
57427 ** allocated in chunks so most INSERTs do no allocation. There is an
57433 ** in the batch number. In other words, if an INSERT occurs between
57437 ** a non-zero batch number, it will see all prior INSERTs.
57439 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
57442 ** The cost of an INSERT is roughly constant. (Sometimes new memory
57443 ** has to be allocated on an INSERT.) The cost of a TEST with a new
57465 ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
57468 ** Each entry in a RowSet is an instance of the following object.
57493 ** A RowSet in an instance of the following structure.
57523 p->pChunk = 0;
57524 p->db = db;
57525 p->pEntry = 0;
57526 p->pLast = 0;
57527 p->pForest = 0;
57528 p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
57529 p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
57530 p->rsFlags = ROWSET_SORTED;
57531 p->iBatch = 0;
57544 for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
57545 pNextChunk = pChunk->pNextChunk;
57546 sqlite3DbFree(p->db, pChunk);
57548 p->pChunk = 0;
57549 p->nFresh = 0;
57550 p->pEntry = 0;
57551 p->pLast = 0;
57552 p->pForest = 0;
57553 p->rsFlags = ROWSET_SORTED;
57563 sqlite3DbFree(((RowSet*)pArg)->db, pArg);
57571 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
57576 if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
57580 pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
57584 pNew->pNextChunk = p->pChunk;
57585 p->pChunk = pNew;
57586 p->pFresh = pNew->aEntry;
57587 p->nFresh = ROWSET_ENTRY_PER_CHUNK;
57589 p->nFresh--;
57590 return p->pFresh++;
57604 assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
57608 pEntry->v = rowid;
57609 pEntry->pRight = 0;
57610 pLast = p->pLast;
57612 if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
57615 p->rsFlags &= ~ROWSET_SORTED;
57617 pLast->pRight = pEntry;
57619 p->pEntry = pEntry;
57621 p->pLast = pEntry;
57640 assert( pA->pRight==0 || pA->v<=pA->pRight->v );
57641 assert( pB->pRight==0 || pB->v<=pB->pRight->v );
57642 if( pA->v<=pB->v ){
57643 if( pA->v<pB->v ) pTail = pTail->pRight = pA;
57644 pA = pA->pRight;
57646 pTail->pRight = pB;
57650 pTail = pTail->pRight = pB;
57651 pB = pB->pRight;
57653 pTail->pRight = pA;
57671 pNext = pIn->pRight;
57672 pIn->pRight = 0;
57700 if( pIn->pLeft ){
57702 rowSetTreeToList(pIn->pLeft, ppFirst, &p);
57703 p->pRight = pIn;
57707 if( pIn->pRight ){
57708 rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
57712 assert( (*ppLast)->pRight==0 );
57724 ** list contains too few elements, then construct an incomplete tree
57735 if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
57739 if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
57743 pLeft = rowSetNDeepTree(ppList, iDepth-1);
57745 if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
57750 p->pLeft = pLeft;
57751 *ppList = p->pRight;
57752 p->pRight = rowSetNDeepTree(ppList, iDepth-1);
57755 *ppList = p->pRight;
57756 p->pLeft = p->pRight = 0;
57772 pList = p->pRight;
57773 p->pLeft = p->pRight = 0;
57777 pList = p->pRight;
57778 p->pLeft = pLeft;
57779 p->pRight = rowSetNDeepTree(&pList, iDepth);
57799 assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
57802 if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
57803 if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
57804 p->pEntry = rowSetEntrySort(p->pEntry);
57806 p->rsFlags |= ROWSET_SORTED|ROWSET_NEXT;
57810 if( p->pEntry ){
57811 *pRowid = p->pEntry->v;
57812 p->pEntry = p->pEntry->pRight;
57813 if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
57828 ** on pRowSet->pEntry, then sort those entries into the forest at
57829 ** pRowSet->pForest so that they can be tested.
57835 assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
57840 if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
57841 p = pRowSet->pEntry;
57843 struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
57844 if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
57848 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
57849 ppPrevTree = &pTree->pRight;
57850 if( pTree->pLeft==0 ){
57851 pTree->pLeft = rowSetListToTree(p);
57855 rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
57856 pTree->pLeft = 0;
57863 pTree->v = 0;
57864 pTree->pRight = 0;
57865 pTree->pLeft = rowSetListToTree(p);
57868 pRowSet->pEntry = 0;
57869 pRowSet->pLast = 0;
57870 pRowSet->rsFlags |= ROWSET_SORTED;
57872 pRowSet->iBatch = iBatch;
57878 for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
57879 p = pTree->pLeft;
57881 if( p->v<iRowid ){
57882 p = p->pRight;
57883 }else if( p->v>iRowid ){
57884 p = p->pLeft;
57930 ** This header file defines the interface to the write-ahead logging
57971 /* Connection to a write-ahead log (WAL) file.
57976 /* Open and close a connection to a write-ahead log. */
57984 ** snapshot is like a read-transaction. It is the state of the database
57985 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
57993 /* Read a page from the write-ahead log, if it is present. */
58007 /* Return an integer that records the current (uncommitted) write
58020 Wal *pWal, /* Write-ahead log connection */
58039 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
58044 /* Return true if the argument is non-NULL and the WAL module is using
58045 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
58046 ** WAL module is using shared-memory, return false.
58060 ** stored in each frame (i.e. the db page-size when the WAL was created).
58121 ** (3) Writes to the database file are an integer multiple of the page size
58125 ** an integer multiple of the page size in length or are taken from the
58131 ** (6) If a super-journal file is used, then all writes to the database file
58132 ** are synced prior to the super-journal being deleted.
58148 ** method is a no-op, but that does not change the fact the SQLite will
58159 ** (11) A database file is well-formed at the beginning and at the conclusion
58162 ** (12) An EXCLUSIVE lock is held on the database file when writing to
58183 ** to print out file-descriptors.
58186 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
58189 #define PAGERID(p) (SQLITE_PTR_TO_INT(p->fd))
58197 ** OPEN <------+------+
58200 ** +---------> READER-------+ |
58203 ** |<-------WRITER_LOCKED------> ERROR
58206 ** |<------WRITER_CACHEMOD-------->|
58209 ** |<-------WRITER_DBMOD---------->|
58212 ** +<------WRITER_FINISHED-------->+
58217 ** OPEN -> READER [sqlite3PagerSharedLock]
58218 ** READER -> OPEN [pager_unlock]
58220 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
58221 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
58222 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
58223 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
58224 ** WRITER_*** -> READER [pager_end_transaction]
58226 ** WRITER_*** -> ERROR [pager_error]
58227 ** ERROR -> OPEN [pager_unlock]
58233 ** state - the file may or may not be locked and the database size is
58243 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
58244 ** was) in exclusive-locking mode, a user-level read transaction is
58248 ** it opens a read-transaction on the database and returns to state
58249 ** OPEN after the read-transaction is completed. However a connection
58251 ** this state even after the read-transaction is closed. The only way
58255 ** * A read transaction may be active (but a write-transaction cannot).
58257 ** * The dbSize variable may be trusted (even if a user-level read
58261 ** * Even if a read-transaction is not open, it is guaranteed that
58262 ** there is no hot-journal in the file-system.
58266 ** The pager moves to this state from READER when a write-transaction
58268 ** required to start a write-transaction are held, but no actual
58279 ** If the connection is running with locking_mode=exclusive, an attempt
58280 ** is made to obtain an EXCLUSIVE lock on the database file.
58283 ** * If the connection is open in rollback-mode, a RESERVED or greater
58285 ** * If the connection is open in WAL-mode, a WAL write transaction
58314 ** * An EXCLUSIVE or greater lock is held on the database file.
58324 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
58332 ** * An EXCLUSIVE or greater lock is held on the database file.
58335 ** commit the transaction. If an error did occur, the caller will need
58340 ** The ERROR state is entered when an IO or disk-full error (including
58342 ** difficult to be sure that the in-memory pager state (cache contents,
58343 ** db size etc.) are consistent with the contents of the file-system.
58345 ** Temporary pager files may enter the ERROR state, but in-memory pagers
58348 ** For example, if an IO error occurs while performing a rollback,
58349 ** the contents of the page-cache may be left in an inconsistent state.
58355 ** instead of READER following such an error.
58358 ** to read or write data returns an error. Eventually, once all
58361 ** page-cache and any other in-memory state at the same time. Everything
58362 ** is reloaded from disk (and, if necessary, hot-journal rollback performed)
58363 ** when a read-transaction is next opened on the pager (transitioning
58369 ** 1. An error occurs while attempting a rollback. This happens in
58372 ** 2. An error occurs while attempting to finalize a journal file
58375 ** 3. An error occurs while attempting to write to the journal or
58379 ** In other cases, the error is returned to the b-tree layer. The b-tree
58383 ** Condition (3) is necessary because it can be triggered by a read-only
58385 ** code were simply returned to the user, the b-tree layer would not
58386 ** automatically attempt a rollback, as it assumes that an error in a
58387 ** read-only statement cannot leave the pager in an internally inconsistent
58393 ** * The pager is not an in-memory pager.
58403 ** state. There are two exceptions: immediately after exclusive-mode has
58419 ** following locking-states, according to the lock currently held on
58424 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
58427 ** pagerUnlockDb() take a conservative approach - eLock is always updated
58433 ** This is usually safe. If an xUnlock fails or appears to fail, there may
58438 ** from ERROR to OPEN state. At this point there may be a hot-journal file
58439 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
58441 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
58443 ** of hot-journal detection.
58447 ** return true because the caller itself is holding an EXCLUSIVE lock (but
58449 ** a hot-journal may be mistaken for a journal being created by an active
58456 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
58457 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
58458 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
58471 ** such a system. This is currently an undocumented limit.
58477 ** An instance of the following structure is allocated for each active
58483 ** set to 0. If a journal-header is written into the main journal while
58486 ** journal before the journal-header. This is required during savepoint
58495 Pgno iSubRec; /* Index of first record in sub-journal */
58510 ** An open page cache is an instance of struct Pager. A description of
58520 ** For a real on-disk database, the current lock held on the database file -
58523 ** For a temporary or in-memory database (neither of which require any
58535 ** This boolean variable is used to make sure that the change-counter
58536 ** (the 4-byte header field at byte offset 24 of the database file) is
58539 ** It is set to true when the change-counter field is updated, which
58540 ** can only happen if an exclusive lock is held on the database file.
58541 ** It is cleared (set to false) whenever an exclusive lock is
58544 ** updating the change-counter is omitted for the current transaction.
58547 ** need only update the change-counter once, for the first transaction
58553 ** (or may not) specify a super-journal name to be written into the
58556 ** Whether or not a journal file contains a super-journal pointer affects
58559 ** If a journal file does not contain a super-journal pointer, it is
58561 ** it does contain a super-journal pointer the journal file is finalized
58565 ** Journal files that contain super-journal pointers cannot be finalized
58566 ** simply by overwriting the first journal-header with zeroes, as the
58567 ** super-journal pointer could interfere with hot-journal rollback of any
58571 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
58577 ** This variables control the behavior of cache-spills (calls made by
58579 ** to the file-system in order to free up memory).
58591 ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
58592 ** is larger than the database page-size in order to prevent a journal sync
58597 ** This is a boolean variable. If true, then any required sub-journal
58598 ** is opened as an in-memory journal file. If false, then in-memory
58599 ** sub-journals are only used for in-memory pager files.
58602 ** write-transaction is opened.
58613 ** is not an integer multiple of the page-size, the value stored in
58614 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
58616 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
58619 ** During a write-transaction, if pages with page-numbers greater than
58630 ** Throughout a write-transaction, dbFileSize contains the size of
58632 ** write-transaction is first opened, and updated when VFS calls are made
58652 ** write-transaction is opened (at the same time as dbFileSize and
58655 ** size-hint passed to the method call. See pager_write_pagelist() for
58663 ** sub-codes.
58689 u8 readOnly; /* True for a read-only database */
58691 u8 memVfs; /* VFS-implemented memory database */
58704 u8 changeCountDone; /* Set after incrementing the change-counter */
58705 u8 setSuper; /* Super-jrnl name is written into jrnl */
58706 u8 doNotSpill; /* Do not spill the cache when non-zero */
58707 u8 subjInMemory; /* True to use in-memory sub-journals */
58715 int nRec; /* Pages journalled since last j-header written */
58716 u32 cksumInit; /* Quasi-random value added to every checksum */
58717 u32 nSubRec; /* Number of records written to sub-journal */
58721 sqlite3_file *sjfd; /* File descriptor for sub-journal */
58734 ** End of the routinely-changing class members
58737 u16 nExtra; /* Add this many bytes to each in-memory page */
58758 Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
58759 char *zWal; /* File name for write-ahead log */
58779 ** a non-testing build. These variables are not thread-safe.
58798 ** written, semi-random garbage data might appear in the journal
58799 ** file after power is restored. If an attempt is then made
58801 ** sanity checking data is an attempt to discover the garbage in the
58805 ** of a 32-bit checksum on each page of data. The checksum covers both
58806 ** the page number and the pPager->pageSize bytes of data for the page.
58807 ** This cksum is initialized to a 32-bit random value that appears in the
58811 ** garbage data came from an obsolete journal file, the checksums might
58823 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
58829 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
58832 ** The macro MEMDB is true if we are dealing with an in-memory database.
58840 # define MEMDB pPager->memDb
58845 ** interfaces to access the database using memory-mapped I/O.
58848 # define USEFETCH(x) ((x)->bUseFetch)
58856 ** by the b-tree layer. This is the case if:
58859 ** (2) the VFS for the database is able to do unaligned sub-page reads
58865 assert( pPager->fd!=0 );
58866 if( pPager->fd->pMethods==0 ) return 0; /* Case (1) */
58867 if( sqlite3PCacheIsDirty(pPager->pPCache) ) return 0; /* Failed (3) */
58869 if( pPager->pWal ){
58871 (void)sqlite3WalFindFrame(pPager->pWal, pgno, &iRead);
58875 assert( pPager->fd->pMethods->xDeviceCharacteristics!=0 );
58876 if( (pPager->fd->pMethods->xDeviceCharacteristics(pPager->fd)
58885 # define pagerUseWal(x) ((x)->pWal!=0)
58907 assert( p->eState==PAGER_OPEN
58908 || p->eState==PAGER_READER
58909 || p->eState==PAGER_WRITER_LOCKED
58910 || p->eState==PAGER_WRITER_CACHEMOD
58911 || p->eState==PAGER_WRITER_DBMOD
58912 || p->eState==PAGER_WRITER_FINISHED
58913 || p->eState==PAGER_ERROR
58916 /* Regardless of the current state, a temp-file connection always behaves
58917 ** as if it has an exclusive lock on the database file. It never updates
58918 ** the change-counter field, so the changeCountDone flag is always set.
58920 assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
58921 assert( p->tempFile==0 || pPager->changeCountDone );
58923 /* If the useJournal flag is clear, the journal-mode must be "OFF".
58924 ** And if the journal-mode is "OFF", the journal file must not be open.
58926 assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
58927 assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
58929 /* Check that MEMDB implies noSync. And an in-memory journal. Since
58930 ** this means an in-memory pager performs no IO at all, it cannot encounter
58932 ** a journal file. (although the in-memory journal implementation may
58934 ** is therefore not possible for an in-memory pager to enter the ERROR
58938 assert( !isOpen(p->fd) );
58939 assert( p->noSync );
58940 assert( p->journalMode==PAGER_JOURNALMODE_OFF
58941 || p->journalMode==PAGER_JOURNALMODE_MEMORY
58943 assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
58950 assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
58951 assert( p->eLock!=PENDING_LOCK );
58953 switch( p->eState ){
58956 assert( pPager->errCode==SQLITE_OK );
58957 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
58961 assert( pPager->errCode==SQLITE_OK );
58962 assert( p->eLock!=UNKNOWN_LOCK );
58963 assert( p->eLock>=SHARED_LOCK );
58967 assert( p->eLock!=UNKNOWN_LOCK );
58968 assert( pPager->errCode==SQLITE_OK );
58970 assert( p->eLock>=RESERVED_LOCK );
58972 assert( pPager->dbSize==pPager->dbOrigSize );
58973 assert( pPager->dbOrigSize==pPager->dbFileSize );
58974 assert( pPager->dbOrigSize==pPager->dbHintSize );
58975 assert( pPager->setSuper==0 );
58979 assert( p->eLock!=UNKNOWN_LOCK );
58980 assert( pPager->errCode==SQLITE_OK );
58987 assert( p->eLock>=RESERVED_LOCK );
58988 assert( isOpen(p->jfd)
58989 || p->journalMode==PAGER_JOURNALMODE_OFF
58990 || p->journalMode==PAGER_JOURNALMODE_WAL
58993 assert( pPager->dbOrigSize==pPager->dbFileSize );
58994 assert( pPager->dbOrigSize==pPager->dbHintSize );
58998 assert( p->eLock==EXCLUSIVE_LOCK );
58999 assert( pPager->errCode==SQLITE_OK );
59001 assert( p->eLock>=EXCLUSIVE_LOCK );
59002 assert( isOpen(p->jfd)
59003 || p->journalMode==PAGER_JOURNALMODE_OFF
59004 || p->journalMode==PAGER_JOURNALMODE_WAL
59005 || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
59007 assert( pPager->dbOrigSize<=pPager->dbHintSize );
59011 assert( p->eLock==EXCLUSIVE_LOCK );
59012 assert( pPager->errCode==SQLITE_OK );
59014 assert( isOpen(p->jfd)
59015 || p->journalMode==PAGER_JOURNALMODE_OFF
59016 || p->journalMode==PAGER_JOURNALMODE_WAL
59017 || (sqlite3OsDeviceCharacteristics(p->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
59026 assert( pPager->errCode!=SQLITE_OK );
59027 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
59038 ** containing the state of the Pager object passed as an argument. This
59039 ** is intended to be used within debuggers. For example, as an alternative
59045 ** about an unused function. It is enclosed within SQLITE_DEBUG and so does
59060 , p->zFilename
59061 , p->eState==PAGER_OPEN ? "OPEN" :
59062 p->eState==PAGER_READER ? "READER" :
59063 p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
59064 p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
59065 p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
59066 p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
59067 p->eState==PAGER_ERROR ? "ERROR" : "?error?"
59068 , (int)p->errCode
59069 , p->eLock==NO_LOCK ? "NO_LOCK" :
59070 p->eLock==RESERVED_LOCK ? "RESERVED" :
59071 p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
59072 p->eLock==SHARED_LOCK ? "SHARED" :
59073 p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
59074 , p->exclusiveMode ? "exclusive" : "normal"
59075 , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
59076 p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
59077 p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
59078 p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
59079 p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
59080 p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
59081 , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
59082 , p->journalOff, p->journalHdr
59083 , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
59102 if( pPager->errCode ){
59103 pPager->xGet = getPageError;
59106 pPager->xGet = getPageMMap;
59109 pPager->xGet = getPageNormal;
59114 ** Return true if it is necessary to write page *pPg into the sub-journal.
59115 ** A page needs to be written into the sub-journal if there exists one
59118 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
59119 ** * The bit corresponding to the page-number is not set in
59123 Pager *pPager = pPg->pPager;
59125 Pgno pgno = pPg->pgno;
59127 for(i=0; i<pPager->nSavepoint; i++){
59128 p = &pPager->aSavepoint[i];
59129 if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
59130 for(i=i+1; i<pPager->nSavepoint; i++){
59131 pPager->aSavepoint[i].bTruncateOnRelease = 0;
59144 return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
59149 ** Read a 32-bit integer from the given file descriptor. Store the integer
59150 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
59153 ** All values are stored on disk as big-endian.
59165 ** Write a 32-bit integer into a string buffer in big-endian byte order.
59171 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
59172 ** on success or an error code is something goes wrong.
59187 ** UNKNOWN_LOCK for an explanation of this.
59192 assert( !pPager->exclusiveMode || pPager->eLock==eLock );
59195 if( isOpen(pPager->fd) ){
59196 assert( pPager->eLock>=eLock );
59197 rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
59198 if( pPager->eLock!=UNKNOWN_LOCK ){
59199 pPager->eLock = (u8)eLock;
59203 pPager->changeCountDone = pPager->tempFile; /* ticket fb3b3024ea238d5c */
59214 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
59221 if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
59222 rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
59223 if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
59224 pPager->eLock = (u8)eLock;
59232 ** This function determines whether or not the atomic-write or
59233 ** atomic-batch-write optimizations can be used with this pager. The
59234 ** atomic-write optimization can be used if:
59244 ** The atomic-batch-write optimization can be used if OsDeviceCharacteristics()
59245 ** returns a value with the SQLITE_IOCAP_BATCH_ATOMIC bit set. -1 is
59257 assert( isOpen(pPager->fd) );
59258 dc = sqlite3OsDeviceCharacteristics(pPager->fd);
59264 if( pPager->dbSize>0 && (dc&SQLITE_IOCAP_BATCH_ATOMIC) ){
59265 return -1;
59271 int nSector = pPager->sectorSize;
59272 int szPage = pPager->pageSize;
59294 ** Return a 32-bit hash of the page data for pPage.
59305 return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
59308 pPage->pageHash = pager_pagehash(pPage);
59312 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
59313 ** is defined, and NDEBUG is not defined, an assert() statement checks
59314 ** that the page is either dirty or still matches the calculated page-hash.
59318 Pager *pPager = pPg->pPager;
59319 assert( pPager->eState!=PAGER_ERROR );
59320 assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
59332 ** This function attempts to read a super-journal file name from the
59335 ** used to store a super-journal file name at the end of a journal file.
59339 ** enough space to write the super-journal name). If the super-journal
59341 ** nul-terminator), then this is handled as if no super-journal name
59344 ** If a super-journal file name is present at the end of the journal
59346 ** nul-terminator byte is appended to the buffer following the
59347 ** super-journal file name.
59349 ** If it is determined that no super-journal file name is present
59352 ** If an error occurs while reading from the journal file, an SQLite
59357 u32 len; /* Length in bytes of super-journal name */
59366 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
59368 || len>szJ-16
59370 || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
59371 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
59373 || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zSuper, len, szJ-16-len))
59378 /* See if the checksum matches the super-journal name */
59380 cksum -= zSuper[u];
59384 ** containing the super-journal filename is corrupted. This means
59386 ** super-journal filename.
59398 ** following the value in pPager->journalOff, assuming a sector
59399 ** size of pPager->sectorSize bytes.
59404 ** ---------------------------------------
59413 i64 c = pPager->journalOff;
59415 offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
59419 assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
59426 ** This function is a no-op if the journal file has not been written to
59429 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
59431 ** zero the 28-byte header at the start of the journal file. In either case,
59432 ** if the pager is not in no-sync mode, sync the journal file immediately
59435 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
59441 ** If an IO error occurs, abandon processing and return the IO error code.
59446 assert( isOpen(pPager->jfd) );
59447 assert( !sqlite3JournalIsInMemory(pPager->jfd) );
59448 if( pPager->journalOff ){
59449 const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
59453 rc = sqlite3OsTruncate(pPager->jfd, 0);
59456 rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
59458 if( rc==SQLITE_OK && !pPager->noSync ){
59459 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
59470 rc = sqlite3OsFileSize(pPager->jfd, &sz);
59472 rc = sqlite3OsTruncate(pPager->jfd, iLimit);
59485 ** - 8 bytes: Magic identifying journal format.
59486 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
59487 ** - 4 bytes: Random number used for page hash.
59488 ** - 4 bytes: Initial database page count.
59489 ** - 4 bytes: Sector size used by the process that wrote this journal.
59490 ** - 4 bytes: Database page size.
59492 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
59496 char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
59497 u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
59501 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
59511 for(ii=0; ii<pPager->nSavepoint; ii++){
59512 if( pPager->aSavepoint[ii].iHdrOffset==0 ){
59513 pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
59517 pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
59520 ** Write the nRec Field - the number of page records that follow this
59523 ** if in full-sync mode), the zero is overwritten with the true number
59533 ** * When the pager is in no-sync mode. Corruption can follow a
59539 assert( isOpen(pPager->fd) || pPager->noSync );
59540 if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
59541 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
59551 /* The random check-hash initializer */
59552 if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
59553 sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
59567 sqlite3OsFileSize(pPager->jfd, &sz);
59569 assert( pPager->journalOff==journalHdrOffset(pPager) );
59570 assert( sqlite3JournalIsInMemory(pPager->jfd) );
59573 put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
59576 put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
59578 put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
59581 put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
59589 nHeader-(sizeof(aJournalMagic)+20));
59600 ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
59603 ** The loop is required here in case the sector-size is larger than the
59609 IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
59610 rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
59611 assert( pPager->journalHdr <= pPager->journalOff );
59612 pPager->journalOff += nHeader;
59622 ** pPager->journalOff. See comments above function writeJournalHdr() for
59627 ** database before the transaction began, in pages. Also, pPager->cksumInit
59633 ** cannot be read from the journal file an error code is returned.
59646 assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
59652 pPager->journalOff = journalHdrOffset(pPager);
59653 if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
59656 iHdrOff = pPager->journalOff;
59660 ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
59663 if( isHot || iHdrOff!=pPager->journalHdr ){
59664 rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
59673 /* Read the first three 32-bit fields of the journal header: The nRec
59674 ** field, the checksum-initializer and the database size at the start
59675 ** of the transaction. Return an error code if anything goes wrong.
59677 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
59678 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
59679 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
59684 if( pPager->journalOff==0 ){
59685 u32 iPageSize; /* Page-size field of journal header */
59686 u32 iSectorSize; /* Sector-size field of journal header */
59688 /* Read the page-size and sector-size journal header fields. */
59689 if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
59690 || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
59695 /* Versions of SQLite prior to 3.5.8 set the page-size field of the
59700 iPageSize = pPager->pageSize;
59703 /* Check that the values read from the page-size and sector-size fields
59710 || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
59712 /* If the either the page-size or sector-size in the journal-header is
59713 ** invalid, then the process that wrote the journal-header must have
59720 /* Update the page-size to match the value read from the journal.
59724 rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
59727 /* Update the assumed sector-size to match the value used by
59733 pPager->sectorSize = iSectorSize;
59736 pPager->journalOff += JOURNAL_HDR_SZ(pPager);
59742 ** Write the supplied super-journal name into the journal file for pager
59743 ** pPager at the current location. The super-journal name must be the last
59744 ** thing written to a journal file. If the pager is in full-sync mode, the
59749 ** + N bytes: super-journal filename in utf-8.
59750 ** + 4 bytes: N (length of super-journal name in bytes, no nul-terminator).
59751 ** + 4 bytes: super-journal name checksum.
59754 ** The super-journal page checksum is the sum of the bytes in the super-journal
59755 ** name, where each byte is interpreted as a signed 8-bit integer.
59758 ** this call is a no-op.
59767 assert( pPager->setSuper==0 );
59771 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
59772 || !isOpen(pPager->jfd)
59776 pPager->setSuper = 1;
59777 assert( pPager->journalHdr <= pPager->journalOff );
59784 /* If in full-sync mode, advance to the next disk sector before writing
59785 ** the super-journal name. This is in case the previous page written to
59788 if( pPager->fullSync ){
59789 pPager->journalOff = journalHdrOffset(pPager);
59791 iHdrOff = pPager->journalOff;
59793 /* Write the super-journal data to the end of the journal file. If
59794 ** an error occurs, return the error code to the caller.
59796 if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_SJ_PGNO(pPager))))
59797 || (0 != (rc = sqlite3OsWrite(pPager->jfd, zSuper, nSuper, iHdrOff+4)))
59798 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper, nSuper)))
59799 || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nSuper+4, cksum)))
59800 || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
59805 pPager->journalOff += (nSuper+20);
59807 /* If the pager is in persistent-journal mode, then the physical
59808 ** journal-file may extend past the end of the super-journal name
59810 ** dangerous because the code to rollback a hot-journal file
59811 ** will not be able to find the super-journal name to determine
59817 if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
59818 && jrnlSize>pPager->journalOff
59820 rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
59826 ** Discard the entire contents of the in-memory page-cache.
59829 pPager->iDataVersion++;
59830 sqlite3BackupRestart(pPager->pBackup);
59831 sqlite3PcacheClear(pPager->pPCache);
59835 ** Return the pPager->iDataVersion value
59838 return pPager->iDataVersion;
59843 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
59848 for(ii=0; ii<pPager->nSavepoint; ii++){
59849 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
59851 if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
59852 sqlite3OsClose(pPager->sjfd);
59854 sqlite3_free(pPager->aSavepoint);
59855 pPager->aSavepoint = 0;
59856 pPager->nSavepoint = 0;
59857 pPager->nSubRec = 0;
59869 for(ii=0; ii<pPager->nSavepoint; ii++){
59870 PagerSavepoint *p = &pPager->aSavepoint[ii];
59871 if( pgno<=p->nOrig ){
59872 rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
59881 ** This function is a no-op if the pager is in exclusive mode and not
59885 ** If the pager is not in exclusive-access mode, the database file is
59886 ** completely unlocked. If the file is unlocked and the file-system does
59892 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
59893 ** or not, any journal file left in the file-system will be treated
59894 ** as a hot-journal and rolled back the next time a read-transaction
59899 assert( pPager->eState==PAGER_READER
59900 || pPager->eState==PAGER_OPEN
59901 || pPager->eState==PAGER_ERROR
59904 sqlite3BitvecDestroy(pPager->pInJournal);
59905 pPager->pInJournal = 0;
59909 assert( !isOpen(pPager->jfd) );
59910 if( pPager->eState==PAGER_ERROR ){
59911 /* If an IO error occurs in wal.c while attempting to wrap the wal file,
59912 ** then the Wal object may be holding a write-lock but no read-lock.
59913 ** This call ensures that the write-lock is dropped as well. We cannot
59914 ** have sqlite3WalEndReadTransaction() drop the write-lock, as it once
59917 sqlite3WalEndWriteTransaction(pPager->pWal);
59919 sqlite3WalEndReadTransaction(pPager->pWal);
59920 pPager->eState = PAGER_OPEN;
59921 }else if( !pPager->exclusiveMode ){
59923 int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
59937 || 1!=(pPager->journalMode & 5)
59939 sqlite3OsClose(pPager->jfd);
59944 ** above the #define for UNKNOWN_LOCK for an explanation of why this
59948 if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
59949 pPager->eLock = UNKNOWN_LOCK;
59953 ** without clearing the error code. This is intentional - the error
59956 assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
59957 pPager->eState = PAGER_OPEN;
59963 ** normal and exclusive-locking mode.
59965 assert( pPager->errCode==SQLITE_OK || !MEMDB );
59966 if( pPager->errCode ){
59967 if( pPager->tempFile==0 ){
59969 pPager->changeCountDone = 0;
59970 pPager->eState = PAGER_OPEN;
59972 pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
59974 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
59975 pPager->errCode = SQLITE_OK;
59979 pPager->journalOff = 0;
59980 pPager->journalHdr = 0;
59981 pPager->setSuper = 0;
59985 ** This function is called whenever an IOERR or FULL error that requires
59988 ** the error-code about to be returned by a pager API function. The
59992 ** IOERR sub-codes, the pager enters the ERROR state and the error code
59996 ** The ERROR state indicates that the contents of the pager-cache
59998 ** the contents of the pager-cache. If a transaction was active when
60001 ** it were a hot-journal).
60007 pPager->errCode==SQLITE_FULL ||
60008 pPager->errCode==SQLITE_OK ||
60009 (pPager->errCode & 0xff)==SQLITE_IOERR
60012 pPager->errCode = rc;
60013 pPager->eState = PAGER_ERROR;
60029 ** * For non-TEMP databases, always sync to disk. This is necessary
60038 if( pPager->tempFile==0 ) return 1;
60040 if( !isOpen(pPager->fd) ) return 0;
60041 return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
60047 ** after rollback of a hot-journal, or if an error occurs while opening
60048 ** the journal file or writing the very first journal-header of a
60053 ** exclusive than a RESERVED lock, it is a no-op.
60059 ** transaction. Nor will it be considered to be a hot-journal by this
60062 ** the current journal-mode (Pager.journalMode value), as follows:
60065 ** Journal file descriptor is simply closed. This destroys an
60066 ** in-memory journal.
60074 ** file. An invalid journal file cannot be rolled back.
60085 ** If running in non-exclusive rollback mode, the lock on the file is
60088 ** SQLITE_OK is returned if no error occurs. If an error occurs during
60101 /* Do nothing if the pager does not have an open write transaction
60103 ** is no write-transaction active but a RESERVED or greater lock is
60106 ** 1. After a successful hot-journal rollback, it is called with
60109 ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
60111 ** read-transaction, this function is called with eState==PAGER_READER
60112 ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
60115 assert( pPager->eState!=PAGER_ERROR );
60116 if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
60121 assert( isOpen(pPager->jfd) || pPager->pInJournal==0
60122 || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_BATCH_ATOMIC)
60124 if( isOpen(pPager->jfd) ){
60128 if( sqlite3JournalIsInMemory(pPager->jfd) ){
60129 /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
60130 sqlite3OsClose(pPager->jfd);
60131 }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
60132 if( pPager->journalOff==0 ){
60135 rc = sqlite3OsTruncate(pPager->jfd, 0);
60136 if( rc==SQLITE_OK && pPager->fullSync ){
60142 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
60145 pPager->journalOff = 0;
60146 }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
60147 || (pPager->exclusiveMode && pPager->journalMode<PAGER_JOURNALMODE_WAL)
60149 rc = zeroJournalHdr(pPager, hasSuper||pPager->tempFile);
60150 pPager->journalOff = 0;
60153 ** a hot-journal was just rolled back. In this case the journal
60155 ** the database file, it will do so using an in-memory journal.
60157 int bDelete = !pPager->tempFile;
60158 assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
60159 assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
60160 || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
60161 || pPager->journalMode==PAGER_JOURNALMODE_WAL
60163 sqlite3OsClose(pPager->jfd);
60165 rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
60171 sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
60172 if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
60175 p->pageHash = 0;
60181 sqlite3BitvecDestroy(pPager->pInJournal);
60182 pPager->pInJournal = 0;
60183 pPager->nRec = 0;
60186 sqlite3PcacheCleanAll(pPager->pPCache);
60188 sqlite3PcacheClearWritable(pPager->pPCache);
60190 sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
60194 /* Drop the WAL write-lock, if any. Also, if the connection was in
60198 rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
60200 }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
60201 /* This branch is taken when committing a transaction in rollback-journal
60207 assert( pPager->eLock==EXCLUSIVE_LOCK );
60208 rc = pager_truncate(pPager, pPager->dbSize);
60212 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
60216 if( !pPager->exclusiveMode
60217 && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
60221 pPager->eState = PAGER_READER;
60222 pPager->setSuper = 0;
60236 ** call to pager_unlock() will discard all in-memory pages, unlock
60238 ** means that there is a hot-journal left in the file-system, the next
60242 ** If the pager has not already entered the ERROR state, but an IO or
60248 if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
60250 if( pPager->eState>=PAGER_WRITER_LOCKED ){
60254 }else if( !pPager->exclusiveMode ){
60255 assert( pPager->eState==PAGER_READER );
60258 }else if( pPager->eState==PAGER_ERROR
60259 && pPager->journalMode==PAGER_JOURNALMODE_MEMORY
60260 && isOpen(pPager->jfd)
60262 /* Special case for a ROLLBACK due to I/O error with an in-memory
60265 int errCode = pPager->errCode;
60266 u8 eLock = pPager->eLock;
60267 pPager->eState = PAGER_OPEN;
60268 pPager->errCode = SQLITE_OK;
60269 pPager->eLock = EXCLUSIVE_LOCK;
60271 pPager->errCode = errCode;
60272 pPager->eLock = eLock;
60278 ** Parameter aData must point to a buffer of pPager->pageSize bytes
60280 ** page of data and the current value of pPager->cksumInit.
60283 ** random initial value (pPager->cksumInit) and every 200th byte
60284 ** of the page data, starting with byte offset (pPager->pageSize%200).
60285 ** Each byte is interpreted as an 8-bit unsigned integer.
60287 ** Changing the formula used to compute this checksum results in an
60297 u32 cksum = pPager->cksumInit; /* Checksum value to return */
60298 int i = pPager->pageSize-200; /* Loop counter */
60301 i -= 200;
60308 ** from the sub-journal (if isMainJrnl==0) and playback that page.
60312 ** The main rollback journal uses checksums - the statement journal does
60315 ** If the page number of the page record read from the (sub-)journal file
60325 ** If the page record is successfully read from the (sub-)journal file
60326 ** and played back, then SQLITE_OK is returned. If an IO error occurs
60327 ** while reading the record from the (sub-)journal file or while writing
60329 ** is successfully read from the (sub-)journal file but appears to be
60333 ** * If the record page-number is illegal (0 or PAGER_SJ_PGNO), or
60340 ** allocated by this function. If this is the case and an allocation fails,
60347 int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
60351 PgHdr *pPg; /* An existing page in the cache */
60360 assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
60361 assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
60363 aData = pPager->pTmpSpace;
60369 ** a hot-journal rollback. If it is a hot-journal rollback, the pager
60370 ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
60371 ** only reads from the main journal, not the sub-journal.
60373 assert( pPager->eState>=PAGER_WRITER_CACHEMOD
60374 || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
60376 assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
60378 /* Read the page number and page data from the journal or sub-journal
60379 ** file. Return an error code to the caller if an IO error occurs.
60381 jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
60384 rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
60386 *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
60397 if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
60401 rc = read32bits(jfd, (*pOffset)-4, &cksum);
60417 if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
60418 pPager->nReserve = ((u8*)aData)[20];
60425 ** An exception to the above rule: If the database is in no-sync mode
60426 ** and a page is moved during an incremental vacuum then the page may
60435 ** a hot-journal rollback, it is guaranteed that the page-cache is empty
60445 ** database file without an entry in the rollback journal that can
60452 ** 2008-04-14: When attempting to vacuum a corrupt database file, it
60462 assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
60464 PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
60465 (isMainJrnl?"main-journal":"sub-journal")
60468 isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
60470 isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
60472 if( isOpen(pPager->fd)
60473 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
60476 i64 ofst = (pgno-1)*(i64)pPager->pageSize;
60477 testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
60481 ** This is usually safe even for an encrypted database - as the data
60483 ** is if the data was just read from an in-memory sub-journal. In that
60486 rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
60488 if( pgno>pPager->dbFileSize ){
60489 pPager->dbFileSize = pgno;
60491 if( pPager->pBackup ){
60492 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
60496 ** the database and the page is not in-memory, there is a potential
60497 ** problem. When the page is next fetched by the b-tree layer, it
60503 ** if the page is on the free-list at the start of the transaction, then
60506 ** The solution is to add an in-memory page to the cache containing
60507 ** the data just read from the sub-journal. Mark the page as dirty
60508 ** and if the pager requires a journal-sync, then mark the page as
60509 ** requiring a journal-sync before it is written.
60512 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
60513 pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
60515 assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
60516 pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
60524 ** of an internal error resulting in an automatic call to
60528 pData = pPg->pData;
60529 memcpy(pData, (u8*)aData, pPager->pageSize);
60530 pPager->xReiniter(pPg);
60540 memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
60548 ** Parameter zSuper is the name of a super-journal file. A single journal
60549 ** file that referred to the super-journal file has just been rolled back.
60550 ** This routine checks if it is possible to delete the super-journal file,
60556 ** When a super-journal file is created, it is populated with the names
60557 ** of all of its child journals, one after another, formatted as utf-8
60559 ** nul-terminator byte (0x00). i.e. the entire contents of a super-journal
60562 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
60564 ** A super-journal file may only be deleted once all of its child
60567 ** This function reads the contents of the super-journal file into
60572 ** * if the child journal contains a reference to super-journal
60578 ** the file-system using sqlite3OsDelete().
60580 ** If an IO error within this function, an error code is returned. This
60581 ** function allocates memory by calling sqlite3Malloc(). If an allocation
60586 ** the entire contents of the super-journal file. This could be
60587 ** a couple of kilobytes or so - potentially larger than the page
60591 sqlite3_vfs *pVfs = pPager->pVfs;
60593 sqlite3_file *pSuper; /* Malloc'd super-journal file descriptor */
60594 sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
60595 char *zSuperJournal = 0; /* Contents of super-journal file */
60596 i64 nSuperJournal; /* Size of super-journal file */
60598 char *zSuperPtr; /* Space to hold super-journal filename */
60603 ** If successful, open the super-journal file for reading.
60605 pSuper = (sqlite3_file *)sqlite3MallocZero(2 * (i64)pVfs->szOsFile);
60612 pJournal = (sqlite3_file *)(((u8 *)pSuper) + pVfs->szOsFile);
60616 /* Load the entire super-journal file into space obtained from
60618 ** sufficient space (in zSuperPtr) to hold the names of super-journal
60619 ** files extracted from regular rollback-journals.
60623 nSuperPtr = 1 + (i64)pVfs->mxPathname;
60641 while( (zJournal-zSuperJournal)<nSuperJournal ){
60648 /* One of the journals pointed to by the super-journal exists.
60649 ** Open it and check if it points at the super-journal. If
60650 ** so, return without deleting the super-journal file.
60670 /* We have a match. Do not delete the super-journal file. */
60693 ** file in the file-system. This only happens when committing a transaction,
60694 ** or rolling back a transaction (including rolling back a hot-journal).
60697 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
60698 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
60708 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
60713 assert( pPager->eState!=PAGER_ERROR );
60714 assert( pPager->eState!=PAGER_READER );
60718 if( isOpen(pPager->fd)
60719 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
60722 int szPage = pPager->pageSize;
60723 assert( pPager->eLock==EXCLUSIVE_LOCK );
60725 rc = sqlite3OsFileSize(pPager->fd, ¤tSize);
60729 rc = sqlite3OsTruncate(pPager->fd, newSize);
60731 char *pTmp = pPager->pTmpSpace;
60733 testcase( (newSize-szPage) == currentSize );
60734 testcase( (newSize-szPage) > currentSize );
60735 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &newSize);
60736 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
60739 pPager->dbFileSize = nPage;
60747 ** Return a sanitized version of the sector-size of OS file pFile. The
60766 ** super-journal pointers within created journal files.
60770 ** Otherwise, for non-temporary files, the effective sector size is
60777 ** pPager->sectorSize is to define the "blast radius" of bytes that
60785 assert( isOpen(pPager->fd) || pPager->tempFile );
60787 if( pPager->tempFile
60788 || (sqlite3OsDeviceCharacteristics(pPager->fd) &
60794 pPager->sectorSize = 512;
60796 pPager->sectorSize = sqlite3SectorSize(pPager->fd);
60807 ** (2) 4 byte big-endian integer which is the number of valid page records
60810 ** (3) 4 byte big-endian integer which is the initial value for the
60814 ** (5) 4 byte big-endian integer which is the sector size. The header
60816 ** (6) 4 byte big-endian integer which is the page size.
60820 ** + pPager->pageSize bytes of data.
60824 ** Each entry in the journal is an instance of the 8th item.
60837 ** no-sync option for the journal. A power failure could lead to corruption
60841 ** If the file opened as the journal file is not a well-formed
60847 ** If an I/O or malloc() error occurs, the journal-file is not deleted
60848 ** and an error code is returned.
60858 sqlite3_vfs *pVfs = pPager->pVfs;
60865 char *zSuper = 0; /* Name of super-journal file if any */
60868 u32 savedPageSize = pPager->pageSize;
60873 assert( isOpen(pPager->jfd) );
60874 rc = sqlite3OsFileSize(pPager->jfd, &szJ);
60879 /* Read the super-journal name from the journal, if it is present.
60880 ** If a super-journal file name is specified, but the file is not
60884 ** TODO: Technically the following is an error because it assumes that
60886 ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
60890 zSuper = pPager->pTmpSpace;
60891 rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname);
60899 pPager->journalOff = 0;
60903 ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
60921 ** working in no-sync mode. This means that the rest of the journal
60926 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
60927 nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
60945 pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
60946 nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
60952 if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
60957 pPager->dbSize = mxPg;
60958 if( pPager->mxPgno<mxPg ){
60959 pPager->mxPgno = mxPg;
60971 rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
60976 pPager->journalOff = szJ;
61002 rc = sqlite3PagerSetPagesize(pPager, &savedPageSize, -1);
61006 ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
61010 sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
61013 /* If this playback is happening automatically as a result of an IO or
61014 ** malloc error that occurred after the change-counter was updated but
61015 ** before the transaction was committed, then the change-counter
61018 ** update the change-counter at all. This may lead to cache inconsistency
61022 pPager->changeCountDone = pPager->tempFile;
61025 /* Leave 4 bytes of space before the super-journal filename in memory.
61029 zSuper = &pPager->pTmpSpace[4];
61030 rc = readSuperJournal(pPager->jfd, zSuper, 1+(i64)pPager->pVfs->mxPathname);
61034 && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
61043 /* If there was a super-journal and this routine will return success,
61044 ** see if it is possible to delete the super-journal.
61046 assert( zSuper==&pPager->pTmpSpace[4] );
61047 memset(pPager->pTmpSpace, 0, 4);
61053 nPlayback, pPager->zJournal);
61068 ** pPg->pData. A shared lock or greater must be held on the database
61074 ** If an IO error occurs, then the IO error is returned to the caller.
61078 Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
61084 assert( pPager->eState>=PAGER_READER && !MEMDB );
61085 assert( isOpen(pPager->fd) );
61088 rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
61092 rc = sqlite3WalReadFrame(pPager->pWal, iFrame,pPager->pageSize,pPg->pData);
61096 i64 iOffset = (pPg->pgno-1)*(i64)pPager->pageSize;
61097 rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
61103 if( pPg->pgno==1 ){
61110 ** pPager->dbFileVers[] with all 0xff bytes should suffice.
61112 ** For an encrypted database, the situation is more complex: bytes
61117 memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
61119 u8 *dbFileVers = &((u8*)pPg->pData)[24];
61120 memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
61124 PAGER_INCR(pPager->nRead);
61125 IOTRACE(("PGIN %p %d\n", pPager, pPg->pgno));
61127 PAGERID(pPager), pPg->pgno, pager_pagehash(pPg)));
61133 ** Update the value of the change-counter at offsets 24 and 92 in
61136 ** This is an unconditional update. See also the pager_incr_changecounter()
61137 ** routine which only updates the change-counter if the update is actually
61138 ** needed, as determined by the pPager->changeCountDone state variable.
61145 change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
61146 put32bits(((char*)pPg->pData)+24, change_counter);
61151 put32bits(((char*)pPg->pData)+92, change_counter);
61152 put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
61166 ** return an SQLite error code. Otherwise, SQLITE_OK.
61181 pPager->xReiniter(pPg);
61195 sqlite3BackupRestart(pPager->pBackup);
61214 pPager->dbSize = pPager->dbOrigSize;
61215 rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
61216 pList = sqlite3PcacheDirtyList(pPager->pPCache);
61218 PgHdr *pNext = pList->pDirty;
61219 rc = pagerUndoCallback((void *)pPager, pList->pgno);
61245 assert( pPager->pWal );
61249 for(p=pList; p && p->pDirty; p=p->pDirty){
61250 assert( p->pgno < p->pDirty->pgno );
61254 assert( pList->pDirty==0 || isCommit );
61262 for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
61263 if( p->pgno<=nTruncate ){
61264 ppNext = &p->pDirty;
61272 pPager->aStat[PAGER_STAT_WRITE] += nList;
61274 if( pList->pgno==1 ) pager_write_changecounter(pList);
61275 rc = sqlite3WalFrames(pPager->pWal,
61276 pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
61278 if( rc==SQLITE_OK && pPager->pBackup ){
61279 for(p=pList; p; p=p->pDirty){
61280 sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
61285 pList = sqlite3PcacheDirtyList(pPager->pPCache);
61286 for(p=pList; p; p=p->pDirty){
61307 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
61314 sqlite3WalEndReadTransaction(pPager->pWal);
61316 rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
61319 if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
61332 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
61338 /* Query the WAL sub-system for the database size. The WalDbsize()
61341 ** available from the WAL sub-system if the log file is empty or
61344 assert( pPager->eState==PAGER_OPEN );
61345 assert( pPager->eLock>=SHARED_LOCK );
61346 assert( isOpen(pPager->fd) );
61347 assert( pPager->tempFile==0 );
61348 nPage = sqlite3WalDbsize(pPager->pWal);
61351 ** WAL sub-system, determine the page count based on the size of
61352 ** the database file. If the size of the database file is not an
61353 ** integer multiple of the page-size, round up the result.
61355 if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
61357 int rc = sqlite3OsFileSize(pPager->fd, &n);
61361 nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
61368 if( nPage>pPager->mxPgno ){
61369 pPager->mxPgno = (Pgno)nPage;
61378 ** Check if the *-wal file that corresponds to the database opened by pPager
61379 ** exists if the database is not empty, or verify that the *-wal file does
61382 ** If the database is not empty and the *-wal file exists, open the pager
61383 ** in WAL mode. If the database is empty or if no *-wal file exists and
61387 ** Return SQLITE_OK or an error code.
61390 ** function. Because an EXCLUSIVE lock on the db file is required to delete
61391 ** a WAL on a none-empty database, this ensures there is no race condition
61392 ** between the xAccess() below and an xDelete() being executed by some
61397 assert( pPager->eState==PAGER_OPEN );
61398 assert( pPager->eLock>=SHARED_LOCK );
61400 if( !pPager->tempFile ){
61403 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
61412 rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
61414 testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
61417 }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
61418 pPager->journalMode = PAGER_JOURNALMODE_DELETE;
61428 ** the entire super-journal file. The case pSavepoint==NULL occurs when
61432 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
61445 ** * Pages are then played back from the sub-journal file, starting
61459 ** (or transaction). No page with a page-number greater than this value
61464 i64 iHdrOff; /* End of first segment of main-journal records */
61468 assert( pPager->eState!=PAGER_ERROR );
61469 assert( pPager->eState>=PAGER_WRITER_LOCKED );
61473 pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
61482 pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
61483 pPager->changeCountDone = pPager->tempFile;
61489 /* Use pPager->journalOff as the effective size of the main rollback
61492 ** past pPager->journalOff is off-limits to us.
61494 szJ = pPager->journalOff;
61500 ** greater than the current database size (pPager->dbSize) but those
61505 iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
61506 pPager->journalOff = pSavepoint->iOffset;
61507 while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
61508 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
61512 pPager->journalOff = 0;
61517 ** of the main journal file. Continue to skip out-of-range pages and
61520 while( rc==SQLITE_OK && pPager->journalOff<szJ ){
61528 ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
61533 && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
61535 nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
61537 for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
61538 rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
61542 assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
61544 /* Finally, rollback pages from the sub-journal. Page that were
61546 ** will be skipped. Out-of-range pages are also skipped.
61550 i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
61553 rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
61555 for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
61556 assert( offset==(i64)ii*(4+pPager->pageSize) );
61564 pPager->journalOff = szJ;
61571 ** Change the maximum number of in-memory pages that are allowed
61575 sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
61579 ** Change the maximum number of in-memory pages that are allowed
61583 return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
61591 sqlite3_file *fd = pPager->fd;
61592 if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
61594 sz = pPager->szMmap;
61595 pPager->bUseFetch = (sz>0);
61597 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
61606 pPager->szMmap = szMmap;
61614 sqlite3PcacheShrink(pPager->pPCache);
61631 ** that an inopertune power failure could leave the journal
61636 ** database (with some additional information - the nRec field
61637 ** of the journal header - being written in between the two
61647 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
61652 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
61658 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
61659 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
61673 if( pPager->tempFile ){
61674 pPager->noSync = 1;
61675 pPager->fullSync = 0;
61676 pPager->extraSync = 0;
61678 pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
61679 pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
61680 pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
61682 if( pPager->noSync ){
61683 pPager->syncFlags = 0;
61685 pPager->syncFlags = SQLITE_SYNC_FULL;
61687 pPager->syncFlags = SQLITE_SYNC_NORMAL;
61689 pPager->walSyncFlags = (pPager->syncFlags<<2);
61690 if( pPager->fullSync ){
61691 pPager->walSyncFlags |= pPager->syncFlags;
61693 if( (pgFlags & PAGER_CKPT_FULLFSYNC) && !pPager->noSync ){
61694 pPager->walSyncFlags |= (SQLITE_SYNC_FULL<<2);
61697 pPager->doNotSpill &= ~SPILLFLAG_OFF;
61699 pPager->doNotSpill |= SPILLFLAG_OFF;
61740 rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
61748 ** The pager invokes the busy-handler if sqlite3OsLock() returns
61749 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
61750 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
61753 ** (which occurs during hot-journal rollback). Summary:
61756 ** --------------------------------------------------------
61757 ** NO_LOCK -> SHARED_LOCK | Yes
61758 ** SHARED_LOCK -> RESERVED_LOCK | No
61759 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
61760 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
61762 ** If the busy-handler callback returns non-zero, the lock is
61768 int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
61772 pPager->xBusyHandler = xBusyHandler;
61773 pPager->pBusyHandlerArg = pBusyHandlerArg;
61774 ap = (void **)&pPager->xBusyHandler;
61777 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
61785 ** is a no-op. The value returned is the error state error code (i.e.
61786 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
61795 ** * the database is either not an in-memory database or it is
61796 ** an in-memory database that currently consists of zero pages.
61817 ** At one point this function returned an error if the pager was in
61820 ** is a no-op for that case anyhow.
61825 if( (pPager->memDb==0 || pPager->dbSize==0)
61826 && sqlite3PcacheRefCount(pPager->pPCache)==0
61827 && pageSize && pageSize!=(u32)pPager->pageSize
61832 if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
61833 rc = sqlite3OsFileSize(pPager->fd, &nByte);
61836 /* 8 bytes of zeroed overrun space is sufficient so that the b-tree
61848 rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
61851 sqlite3PageFree(pPager->pTmpSpace);
61852 pPager->pTmpSpace = pNew;
61853 pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
61854 pPager->pageSize = pageSize;
61855 pPager->lckPgno = (Pgno)(PENDING_BYTE/pageSize) + 1;
61861 *pPageSize = pPager->pageSize;
61863 if( nReserve<0 ) nReserve = pPager->nReserve;
61865 pPager->nReserve = (i16)nReserve;
61880 return pPager->pTmpSpace;
61892 pPager->mxPgno = mxPage;
61894 assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
61895 /* assert( pPager->mxPgno>=pPager->dbSize ); */
61899 return pPager->mxPgno;
61907 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
61916 sqlite3_io_error_pending = -1;
61943 assert( isOpen(pPager->fd) || pPager->tempFile );
61946 ** the Pager object. There has not been an opportunity to transition
61951 if( isOpen(pPager->fd) ){
61953 rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
61962 ** This function may only be called when a read-transaction is open on
61965 ** However, if the file is between 1 and <page-size> bytes in size, then
61969 assert( pPager->eState>=PAGER_READER );
61970 assert( pPager->eState!=PAGER_WRITER_FINISHED );
61971 *pnPage = (int)pPager->dbSize;
61977 ** a similar or greater lock is already held, this function is a no-op
61985 ** Return SQLITE_OK on success and an error code if we cannot obtain
61992 /* Check that this is either a no-op (because the requested lock is
61993 ** already held), or one of the transitions that the busy-handler
61997 assert( (pPager->eLock>=locktype)
61998 || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
61999 || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
62004 }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
62010 ** following is true for all dirty pages currently in the page-cache:
62016 ** be necessary to write the current content out to the sub-journal.
62025 ** sub-journal rolled back the content could not be restored and the
62031 Pager *pPager = pPg->pPager;
62032 assert( pPg->flags&PGHDR_DIRTY );
62033 if( pPg->pgno>pPager->dbSize ){ /* if (a) is false */
62034 Pgno pgno = pPg->pgno;
62036 for(i=0; i<pPg->pPager->nSavepoint; i++){
62037 PagerSavepoint *p = &pPager->aSavepoint[i];
62038 assert( p->nOrig<pgno || sqlite3BitvecTestNotNull(p->pInSavepoint,pgno) );
62043 sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
62050 ** Truncate the in-memory database file image to nPage pages. This
62061 assert( pPager->dbSize>=nPage || CORRUPT_DB );
62062 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
62063 pPager->dbSize = nPage;
62078 ** This function is called before attempting a hot-journal rollback. It
62079 ** syncs the journal file to disk, then sets pPager->journalHdr to the
62083 ** Syncing a hot-journal to disk before attempting to roll it back ensures
62084 ** that if a power-failure occurs during the rollback, the process that
62089 ** an SQLite error code.
62093 if( !pPager->noSync ){
62094 rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
62097 rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
62107 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
62121 if( pPager->pMmapFreelist ){
62122 *ppPage = p = pPager->pMmapFreelist;
62123 pPager->pMmapFreelist = p->pDirty;
62124 p->pDirty = 0;
62125 assert( pPager->nExtra>=8 );
62126 memset(p->pExtra, 0, 8);
62128 *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
62130 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
62133 p->pExtra = (void *)&p[1];
62134 assert( EIGHT_BYTE_ALIGNMENT( p->pExtra ) );
62135 p->flags = PGHDR_MMAP;
62136 p->nRef = 1;
62137 p->pPager = pPager;
62140 assert( p->pExtra==(void *)&p[1] );
62141 assert( p->pPage==0 );
62142 assert( p->flags==PGHDR_MMAP );
62143 assert( p->pPager==pPager );
62144 assert( p->nRef==1 );
62146 p->pgno = pgno;
62147 p->pData = pData;
62148 pPager->nMmapOut++;
62155 ** Release a reference to page pPg. pPg must have been returned by an
62159 Pager *pPager = pPg->pPager;
62160 pPager->nMmapOut--;
62161 pPg->pDirty = pPager->pMmapFreelist;
62162 pPager->pMmapFreelist = pPg;
62164 assert( pPager->fd->pMethods->iVersion>=3 );
62165 sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
62174 for(p=pPager->pMmapFreelist; p; p=pNext){
62175 pNext = p->pDirty;
62182 ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
62189 if( pPager->tempFile ) return SQLITE_OK;
62190 if( pPager->dbSize==0 ) return SQLITE_OK;
62191 assert( pPager->zFilename && pPager->zFilename[0] );
62192 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
62194 /* If the HAS_MOVED file-control is unimplemented, assume that the file
62214 ** This function always succeeds. If a transaction is active an attempt
62215 ** is made to roll it back. If an error occurs during the rollback
62220 u8 *pTmp = (u8*)pPager->pTmpSpace;
62226 /* pPager->errCode = 0; */
62227 pPager->exclusiveMode = 0;
62231 assert( db || pPager->pWal==0 );
62232 if( db && 0==(db->flags & SQLITE_NoCkptOnClose)
62237 sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags, pPager->pageSize,a);
62238 pPager->pWal = 0;
62246 ** If this is not done, then an unsynced portion of the open journal
62250 ** If an error occurs while trying to sync the journal, shift the pager
62253 ** back or finalize it. The next database user will have to do hot-journal
62256 if( isOpen(pPager->jfd) ){
62265 sqlite3OsClose(pPager->jfd);
62266 sqlite3OsClose(pPager->fd);
62268 sqlite3PcacheClose(pPager->pPCache);
62269 assert( !pPager->aSavepoint && !pPager->pInJournal );
62270 assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
62281 return pPg->pgno;
62295 ** disk and can be restored in the event of a hot-journal rollback.
62297 ** If the Pager.noSync flag is set, then this function is a no-op.
62298 ** Otherwise, the actions required depend on the journal-mode and the
62299 ** device characteristics of the file-system, as follows:
62301 ** * If the journal file is an in-memory journal file, no action need
62307 ** been written following it. If the pager is operating in full-sync
62313 ** Or, in pseudo-code:
62315 ** if( NOT <in-memory journal> ){
62317 ** if( <full-sync mode> ) xSync(<journal file>);
62324 ** page currently held in memory before returning SQLITE_OK. If an IO
62330 assert( pPager->eState==PAGER_WRITER_CACHEMOD
62331 || pPager->eState==PAGER_WRITER_DBMOD
62339 if( !pPager->noSync ){
62340 assert( !pPager->tempFile );
62341 if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
62342 const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
62343 assert( isOpen(pPager->jfd) );
62346 /* This block deals with an obscure problem. If the last connection
62347 ** that wrote to this database was operating in persistent-journal
62350 ** file happens to be a journal-header (written as part of the
62351 ** previous connection's transaction), and a crash or power-failure
62355 ** hot-journal rollback following recovery. It may roll back all
62357 ** out-of-date data that follows it. Database corruption.
62373 put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
62376 rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
62379 rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
62386 ** full-synchronous mode, sync the journal first. This ensures that
62396 if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
62399 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
62402 IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
62404 pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
62411 rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
62412 (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
62417 pPager->journalHdr = pPager->journalOff;
62419 pPager->nRec = 0;
62424 pPager->journalHdr = pPager->journalOff;
62432 sqlite3PcacheClearSyncFlags(pPager->pPCache);
62433 pPager->eState = PAGER_WRITER_DBMOD;
62441 ** in-memory pages in the list to the database file. The argument may
62442 ** be NULL, representing an empty list. In this case this function is
62443 ** a no-op.
62447 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
62450 ** If the pager is a temp-file pager and the actual file-system file
62466 ** If everything is successful, SQLITE_OK is returned. If an IO error
62467 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
62475 assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
62476 assert( pPager->eLock==EXCLUSIVE_LOCK );
62477 assert( isOpen(pPager->fd) || pList->pDirty==0 );
62479 /* If the file is a temp-file has not yet been opened, open it now. It
62481 ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
62483 if( !isOpen(pPager->fd) ){
62484 assert( pPager->tempFile && rc==SQLITE_OK );
62485 rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
62491 assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
62493 && pPager->dbHintSize<pPager->dbSize
62494 && (pList->pDirty || pList->pgno>pPager->dbHintSize)
62496 sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
62497 sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
62498 pPager->dbHintSize = pPager->dbSize;
62502 Pgno pgno = pList->pgno;
62506 ** make the file smaller (presumably by auto-vacuum code). Do not write
62512 if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
62513 i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
62516 assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
62517 if( pList->pgno==1 ) pager_write_changecounter(pList);
62519 pData = pList->pData;
62522 rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
62529 memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
62531 if( pgno>pPager->dbFileSize ){
62532 pPager->dbFileSize = pgno;
62534 pPager->aStat[PAGER_STAT_WRITE]++;
62537 sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
62547 pList = pList->pDirty;
62554 ** Ensure that the sub-journal file is open. If it is already open, this
62555 ** function is a no-op.
62557 ** SQLITE_OK is returned if everything goes according to plan. An
62563 if( !isOpen(pPager->sjfd) ){
62568 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
62569 nStmtSpill = -1;
62571 rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
62577 ** Append a record of the current state of page pPg to the sub-journal.
62579 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
62582 ** This function returns SQLITE_OK if everything is successful, an IO
62583 ** error code if the attempt to write to the sub-journal fails, or
62589 Pager *pPager = pPg->pPager;
62590 if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
62592 /* Open the sub-journal, if it has not already been opened */
62593 assert( pPager->useJournal );
62594 assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
62595 assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
62598 || pPg->pgno>pPager->dbOrigSize
62602 /* If the sub-journal was opened successfully (or was already open),
62605 void *pData = pPg->pData;
62606 i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
62609 PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
62610 rc = write32bits(pPager->sjfd, offset, pPg->pgno);
62612 rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
62617 pPager->nSubRec++;
62618 assert( pPager->nSavepoint>0 );
62619 rc = addToSavepointBitvecs(pPager, pPg->pgno);
62634 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
62645 ** SQLITE_OK returned. If an IO error occurs while trying to make the
62654 assert( pPg->pPager==pPager );
62655 assert( pPg->flags&PGHDR_DIRTY );
62666 ** Spilling is also prohibited when in an error state since that could
62673 if( NEVER(pPager->errCode) ) return SQLITE_OK;
62674 testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
62675 testcase( pPager->doNotSpill & SPILLFLAG_OFF );
62676 testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
62677 if( pPager->doNotSpill
62678 && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
62679 || (pPg->flags & PGHDR_NEED_SYNC)!=0)
62684 pPager->aStat[PAGER_STAT_SPILL]++;
62685 pPg->pDirty = 0;
62695 if( pPager->tempFile==0 ){
62696 rc = sqlite3JournalCreate(pPager->jfd);
62702 if( pPg->flags&PGHDR_NEED_SYNC
62703 || pPager->eState==PAGER_WRITER_CACHEMOD
62710 assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
62717 PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
62728 int rc = pPager->errCode;
62730 PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
62733 PgHdr *pNext = pList->pDirty;
62734 if( pList->nRef==0 ){
62750 ** If zFilename is NULL then a randomly-named temporary file is created
62754 ** This can be used to implement an in-memory database.
62771 ** the new pager object. If an error occurs, *ppPager is set to NULL
62780 int nExtra, /* Extra bytes append to each in-memory page */
62788 int tempFile = 0; /* True for temp files (incl. in-memory files) */
62789 int memDb = 0; /* True if this is an in-memory file */
62791 int readOnly = 0; /* True if this is a read-only file */
62802 /* Figure out how much space is required for each journal file-handle
62803 ** (there are two of them, the main journal and the sub-journal). */
62806 /* Set the output variable to NULL in case an error occurs. */
62821 /* Compute and store the full pathname in an allocated buffer pointed
62827 nPathname = pVfs->mxPathname + 1;
62849 nUriByte = (int)(&z[1] - zUri);
62851 if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
62853 ** the database being opened will be more than pVfs->mxPathname
62856 ** check for a hot-journal before reading.
62872 ** Database file handle (pVfs->szOsFile bytes)
62873 ** Sub-journal file handle (journalFileSize bytes)
62883 ** Some 3rd-party software, over which we have no control, depends on
62887 ** misuse of SQLite and a bug in the 3rd-party software, but the 3rd-party
62890 ** filename format expected by 3rd-party software should be as follows:
62892 ** - Main Database Path
62893 ** - \0
62894 ** - Multiple URI components consisting of:
62895 ** - Key
62896 ** - \0
62897 ** - Value
62898 ** - \0
62899 ** - \0
62900 ** - Journal Path
62901 ** - \0
62902 ** - WAL Path (zWALName)
62903 ** - \0
62914 ROUND8(pVfs->szOsFile) + /* The main db file */
62932 pPager->pPCache = (PCache*)pPtr; pPtr += ROUND8(pcacheSize);
62933 pPager->fd = (sqlite3_file*)pPtr; pPtr += ROUND8(pVfs->szOsFile);
62934 pPager->sjfd = (sqlite3_file*)pPtr; pPtr += journalFileSize;
62935 pPager->jfd = (sqlite3_file*)pPtr; pPtr += journalFileSize;
62936 assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
62941 pPager->zFilename = (char*)pPtr;
62954 pPager->zJournal = (char*)pPtr;
62956 memcpy(pPtr, "-journal",8); pPtr += 8 + 1;
62958 sqlite3FileSuffix3(zFilename,pPager->zJournal);
62959 pPtr = (u8*)(pPager->zJournal + sqlite3Strlen30(pPager->zJournal)+1);
62962 pPager->zJournal = 0;
62968 pPager->zWal = (char*)pPtr;
62970 memcpy(pPtr, "-wal", 4); pPtr += 4 + 1;
62972 sqlite3FileSuffix3(zFilename, pPager->zWal);
62973 pPtr = (u8*)(pPager->zWal + sqlite3Strlen30(pPager->zWal)+1);
62976 pPager->zWal = 0;
62982 pPager->pVfs = pVfs;
62983 pPager->vfsFlags = vfsFlags;
62989 rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
62991 pPager->memVfs = memJM = (fout&SQLITE_OPEN_MEMORY)!=0;
63003 int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
63007 if( szPageDflt<pPager->sectorSize ){
63008 if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
63011 szPageDflt = (u32)pPager->sectorSize;
63028 pPager->noLock = sqlite3_uri_boolean(pPager->zFilename, "nolock", 0);
63030 || sqlite3_uri_boolean(pPager->zFilename, "immutable", 0) ){
63040 ** This branch is also run for an in-memory database. An in-memory
63041 ** database is the same as a temp-file that is never written out to
63042 ** disk and uses an in-memory rollback journal.
63048 pPager->eState = PAGER_READER; /* Pretend we already have a lock */
63049 pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
63050 pPager->noLock = 1; /* Do no locking */
63058 assert( pPager->memDb==0 );
63059 rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
63068 !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
63071 /* If an error occurred above, free the Pager structure and close the file.
63074 sqlite3OsClose(pPager->fd);
63075 sqlite3PageFree(pPager->pTmpSpace);
63080 PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
63081 IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
63083 pPager->useJournal = (u8)useJournal;
63084 /* pPager->stmtOpen = 0; */
63085 /* pPager->stmtInUse = 0; */
63086 /* pPager->nRef = 0; */
63087 /* pPager->stmtSize = 0; */
63088 /* pPager->stmtJSize = 0; */
63089 /* pPager->nPage = 0; */
63090 pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
63091 /* pPager->state = PAGER_UNLOCK; */
63092 /* pPager->errMask = 0; */
63093 pPager->tempFile = (u8)tempFile;
63097 pPager->exclusiveMode = (u8)tempFile;
63098 pPager->changeCountDone = pPager->tempFile;
63099 pPager->memDb = (u8)memDb;
63100 pPager->readOnly = (u8)readOnly;
63101 assert( useJournal || pPager->tempFile );
63103 /* pPager->pFirst = 0; */
63104 /* pPager->pFirstSynced = 0; */
63105 /* pPager->pLast = 0; */
63106 pPager->nExtra = (u16)nExtra;
63107 pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
63108 assert( isOpen(pPager->fd) || tempFile );
63111 pPager->journalMode = PAGER_JOURNALMODE_OFF;
63113 pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
63115 /* pPager->xBusyHandler = 0; */
63116 /* pPager->pBusyHandlerArg = 0; */
63117 pPager->xReiniter = xReinit;
63119 /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
63120 /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
63134 while( zName[-1]!=0 || zName[-2]!=0 || zName[-3]!=0 || zName[-4]!=0 ){
63135 zName--;
63137 p = zName - 4 - sizeof(Pager*);
63140 return pPager->fd;
63147 ** the file-system for the given pager. A hot journal is one that
63148 ** needs to be played back. According to this function, a hot-journal
63157 ** exists, that is probably an old journal left over from a prior
63162 ** This routine does not check if there is a super-journal filename
63163 ** at the end of the file. If there is, and that super-journal file
63165 ** case this routine will return a false-positive. The pager_playback()
63169 ** If a hot-journal file is found to exist, *pExists is set to 1 and
63170 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
63171 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
63172 ** to determine whether or not a hot-journal file exists, the IO error
63176 sqlite3_vfs * const pVfs = pPager->pVfs;
63179 int jrnlOpen = !!isOpen(pPager->jfd);
63181 assert( pPager->useJournal );
63182 assert( isOpen(pPager->fd) );
63183 assert( pPager->eState==PAGER_OPEN );
63185 assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
63191 rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
63201 ** in fact there is none. This results in a false-positive which will
63204 rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
63208 assert( pPager->tempFile==0 );
63222 sqlite3OsDelete(pVfs, pPager->zJournal, 0);
63223 if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
63229 ** at least one non-zero bytes at the start of the journal file.
63235 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
63239 rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
63244 sqlite3OsClose(pPager->jfd);
63249 ** it has a zero header, that might be due to an I/O error, or
63254 ** with it under an EXCLUSIVE lock where we do not need to
63271 ** has been successfully called. If a shared-lock is already held when
63272 ** this function is called, it is a no-op.
63277 ** on the database file), then an attempt is made to obtain a
63279 ** the SHARED lock, the file-system is checked for a hot-journal,
63280 ** which is played back if present. Following any hot-journal
63282 ** the 'change-counter' field of the database file header and
63285 ** 2) If the pager is running in exclusive-mode, and there are currently
63287 ** then an attempt is made to clear the error state by discarding
63291 ** If everything is successful, SQLITE_OK is returned. If an IO error
63292 ** occurs while locking the database, checking for a hot-journal file or
63298 /* This routine is only called from b-tree and only when there are no
63302 assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
63304 assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
63305 assert( pPager->errCode==SQLITE_OK );
63307 if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
63308 int bHotJournal = 1; /* True if there exists a hot journal-file */
63311 assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
63315 assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
63322 if( pPager->eLock<=SHARED_LOCK ){
63329 if( pPager->readOnly ){
63334 /* Get an EXCLUSIVE lock on the database file. At this point it is
63339 ** hot-journal back.
63356 ** in exclusive-access mode the file descriptor will be kept open
63357 ** and possibly used for a transaction later on. Also, write-access
63364 ** may mean that the pager was in the error-state when this
63367 if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
63368 sqlite3_vfs * const pVfs = pPager->pVfs;
63371 pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
63375 assert( !pPager->tempFile );
63376 rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
63377 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
63380 sqlite3OsClose(pPager->jfd);
63387 ** playing back the hot-journal so that we don't end up with
63388 ** an inconsistent cache. Sync the hot journal before playing
63393 if( isOpen(pPager->jfd) ){
63397 rc = pager_playback(pPager, !pPager->tempFile);
63398 pPager->eState = PAGER_OPEN;
63400 }else if( !pPager->exclusiveMode ){
63405 /* This branch is taken if an error occurs while trying to open
63406 ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
63410 ** UNKNOWN_LOCK above for an explanation).
63425 assert( pPager->eState==PAGER_OPEN );
63426 assert( (pPager->eLock==SHARED_LOCK)
63427 || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
63431 if( !pPager->tempFile && pPager->hasHeldSharedLock ){
63432 /* The shared-lock has just been acquired then check to
63436 ** single unnecessary sqlite3OsRead() call at the start-up.
63440 ** a 32-bit counter that is incremented with each change. The
63445 ** detected. The chance of an undetected change is so small that
63448 char dbFileVers[sizeof(pPager->dbFileVers)];
63451 rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
63459 if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
63469 sqlite3OsUnfetch(pPager->fd, 0, 0);
63474 /* If there is a WAL file in the file-system, open this database in WAL
63475 ** mode. Otherwise, the following function call is a no-op.
63479 assert( pPager->pWal==0 || rc==SQLITE_OK );
63488 if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
63489 rc = pagerPagecount(pPager, &pPager->dbSize);
63496 assert( pPager->eState==PAGER_OPEN );
63498 pPager->eState = PAGER_READER;
63499 pPager->hasHeldSharedLock = 1;
63510 ** nothing to rollback, so this routine is a no-op.
63513 if( sqlite3PcacheRefCount(pPager->pPCache)==0 ){
63514 assert( pPager->nMmapOut==0 ); /* because page1 is never memory mapped */
63527 ** getPageNormal() -- The normal getter
63528 ** getPageError() -- Used if the pager is in an error state
63529 ** getPageMmap() -- Used if memory-mapped I/O is enabled
63534 ** choose not to allocate a new page object and may reuse an existing
63551 ** a) When reading a free-list leaf page from the database, and
63566 ** an appropriate error code is returned and *ppPage is set to NULL.
63569 ** to find a page in the in-memory cache first. If the page is not already
63571 ** just returns 0. This routine acquires a read-lock the first time it
63572 ** has to go to disk, and could also playback an old journal if necessary.
63587 assert( pPager->errCode==SQLITE_OK );
63588 assert( pPager->eState>=PAGER_READER );
63590 assert( pPager->hasHeldSharedLock==1 );
63593 pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
63596 rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
63603 pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
63605 assert( pPg->pgno==pgno );
63606 assert( pPg->pPager==pPager || pPg->pPager==0 );
63609 if( pPg->pPager && !noContent ){
63610 /* In this case the pcache already contains an initialized copy of
63613 pPager->aStat[PAGER_STAT_HIT]++;
63628 pPg->pPager = pPager;
63630 assert( !isOpen(pPager->fd) || !MEMDB );
63631 if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
63632 if( pgno>pPager->mxPgno ){
63634 if( pgno<=pPager->dbSize ){
63641 /* Failure to set the bits in the InJournal bit-vectors is benign.
63648 if( pgno<=pPager->dbOrigSize ){
63649 TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
63656 memset(pPg->pData, 0, pPager->pageSize);
63659 assert( pPg->pPager==pPager );
63660 pPager->aStat[PAGER_STAT_MISS]++;
63681 /* The page getter for when memory-mapped I/O is enabled */
63692 /* It is acceptable to use a read-only (mmap) page for any page except
63693 ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
63695 ** temporary or in-memory database. */
63697 && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
63709 assert( pPager->eState>=PAGER_READER );
63711 assert( pPager->hasHeldSharedLock==1 );
63712 assert( pPager->errCode==SQLITE_OK );
63715 rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
63723 rc = sqlite3OsFetch(pPager->fd,
63724 (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
63727 if( pPager->eState>PAGER_READER || pPager->tempFile ){
63733 sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
63750 /* The page getter method for when the pager is an error state */
63759 assert( pPager->errCode!=SQLITE_OK );
63761 return pPager->errCode;
63777 rc = pPager->xGet(pPager, pgno, ppPage, flags);
63784 /* Normal, high-speed version of sqlite3PagerGet() */
63785 return pPager->xGet(pPager, pgno, ppPage, flags);
63790 ** Acquire a page if it is already in the in-memory cache. Do
63804 assert( pPager->pPCache!=0 );
63805 pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
63806 assert( pPage==0 || pPager->hasHeldSharedLock );
63808 return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
63818 ** The assert() at tag-20230419-2 proves that this constraint is always
63826 TESTONLY( Pager *pPager = pPg->pPager; )
63828 if( pPg->flags & PGHDR_MMAP ){
63829 assert( pPg->pgno!=1 ); /* Page1 is never memory mapped */
63835 assert( sqlite3PcacheRefCount(pPager->pPCache)>0 ); /* tag-20230419-2 */
63843 assert( pPg->pgno==1 );
63844 assert( (pPg->flags & PGHDR_MMAP)==0 ); /* Page1 is never memory mapped */
63845 pPager = pPg->pPager;
63856 ** to the start of it. If there are active savepoints, open the sub-journal
63870 ** an IO error code if opening or writing the journal file fails.
63874 sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
63876 assert( pPager->eState==PAGER_WRITER_LOCKED );
63878 assert( pPager->pInJournal==0 );
63880 /* If already in the error state, this function is a no-op. But on
63882 ** an error state. */
63883 if( NEVER(pPager->errCode) ) return pPager->errCode;
63885 if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
63886 pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
63887 if( pPager->pInJournal==0 ){
63892 if( !isOpen(pPager->jfd) ){
63893 if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
63894 sqlite3MemJournalOpen(pPager->jfd);
63899 if( pPager->tempFile ){
63913 pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
63917 assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
63922 ** the sub-journal if necessary.
63926 pPager->nRec = 0;
63927 pPager->journalOff = 0;
63928 pPager->setSuper = 0;
63929 pPager->journalHdr = 0;
63935 sqlite3BitvecDestroy(pPager->pInJournal);
63936 pPager->pInJournal = 0;
63937 pPager->journalOff = 0;
63939 assert( pPager->eState==PAGER_WRITER_LOCKED );
63940 pPager->eState = PAGER_WRITER_CACHEMOD;
63947 ** Begin a write-transaction on the specified pager object. If a
63948 ** write-transaction has already been opened, this function is a no-op.
63952 ** an EXCLUSIVE lock. If such a lock is already held, no locking
63955 ** If the subjInMemory argument is non-zero, then any sub-journal opened
63956 ** within this transaction will be opened as an in-memory file. This
63957 ** has no effect if the sub-journal is already opened (as it may be when
63959 ** sub-journal. If the subjInMemory argument is zero, then any required
63960 ** sub-journal is implemented in-memory if pPager is an in-memory database,
63966 if( pPager->errCode ) return pPager->errCode;
63967 assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
63968 pPager->subjInMemory = (u8)subjInMemory;
63970 if( pPager->eState==PAGER_READER ){
63971 assert( pPager->pInJournal==0 );
63974 /* If the pager is configured to use locking_mode=exclusive, and an
63977 if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
63982 (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
63986 ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
63987 ** The busy-handler is not invoked if another connection already
63988 ** holds the write-lock. If possible, the upper layer will call it.
63990 rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
63993 ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
63994 ** busy-handler callback can be used when upgrading to the EXCLUSIVE
64007 ** when it has an open transaction, but never to DBMOD or FINISHED.
64009 ** transactions may copy data from the sub-journal into the database
64013 pPager->eState = PAGER_WRITER_LOCKED;
64014 pPager->dbHintSize = pPager->dbSize;
64015 pPager->dbFileSize = pPager->dbSize;
64016 pPager->dbOrigSize = pPager->dbSize;
64017 pPager->journalOff = 0;
64020 assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
64021 assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
64033 Pager *pPager = pPg->pPager;
64037 i64 iOff = pPager->journalOff;
64042 assert( pPg->pgno!=PAGER_SJ_PGNO(pPager) );
64044 assert( pPager->journalHdr<=pPager->journalOff );
64045 pData2 = pPg->pData;
64048 /* Even if an IO or diskfull error occurs while journalling the
64049 ** page in the block above, set the need-sync flag for the page.
64052 ** in the database file. And if an IO error occurs while doing so,
64055 pPg->flags |= PGHDR_NEED_SYNC;
64057 rc = write32bits(pPager->jfd, iOff, pPg->pgno);
64059 rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
64061 rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
64064 IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
64065 pPager->journalOff, pPager->pageSize));
64068 PAGERID(pPager), pPg->pgno,
64069 ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
64071 pPager->journalOff += 8 + pPager->pageSize;
64072 pPager->nRec++;
64073 assert( pPager->pInJournal!=0 );
64074 rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
64077 rc |= addToSavepointBitvecs(pPager, pPg->pgno);
64084 ** main journal or sub-journal as required. If the page is written into
64090 Pager *pPager = pPg->pPager;
64093 /* This routine is not called unless a write-transaction has already
64097 assert( pPager->eState==PAGER_WRITER_LOCKED
64098 || pPager->eState==PAGER_WRITER_CACHEMOD
64099 || pPager->eState==PAGER_WRITER_DBMOD
64102 assert( pPager->errCode==0 );
64103 assert( pPager->readOnly==0 );
64107 ** obtained the necessary locks to begin the write-transaction, but the
64112 ** an error might occur and the pager would end up in WRITER_LOCKED state
64115 if( pPager->eState==PAGER_WRITER_LOCKED ){
64119 assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
64129 assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
64130 if( pPager->pInJournal!=0
64131 && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
64134 if( pPg->pgno<=pPager->dbOrigSize ){
64140 if( pPager->eState!=PAGER_WRITER_DBMOD ){
64141 pPg->flags |= PGHDR_NEED_SYNC;
64144 PAGERID(pPager), pPg->pgno,
64145 ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
64149 /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
64154 pPg->flags |= PGHDR_WRITEABLE;
64159 if( pPager->nSavepoint>0 ){
64164 if( pPager->dbSize<pPg->pgno ){
64165 pPager->dbSize = pPg->pgno;
64188 Pager *pPager = pPg->pPager; /* The pager that owns pPg */
64189 Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
64196 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
64197 pPager->doNotSpill |= SPILLFLAG_NOSYNC;
64199 /* This trick assumes that both the page-size and sector-size are
64200 ** an integer power of 2. It sets variable pg1 to the identifier
64203 pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
64205 nPageCount = pPager->dbSize;
64206 if( pPg->pgno>nPageCount ){
64207 nPage = (pPg->pgno - pg1)+1;
64208 }else if( (pg1+nPagePerSector-1)>nPageCount ){
64209 nPage = nPageCount+1-pg1;
64214 assert(pg1<=pPg->pgno);
64215 assert((pg1+nPage)>pPg->pgno);
64220 if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
64225 if( pPage->flags&PGHDR_NEED_SYNC ){
64232 if( pPage->flags&PGHDR_NEED_SYNC ){
64250 pPage->flags |= PGHDR_NEED_SYNC;
64256 assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
64257 pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
64269 ** fit on a single disk sector. In this case all co-resident pages
64272 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
64276 Pager *pPager = pPg->pPager;
64277 assert( (pPg->flags & PGHDR_MMAP)==0 );
64278 assert( pPager->eState>=PAGER_WRITER_LOCKED );
64280 if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
64281 if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
64283 }else if( pPager->errCode ){
64284 return pPager->errCode;
64285 }else if( pPager->sectorSize > (u32)pPager->pageSize ){
64286 assert( pPager->tempFile==0 );
64300 return pPg->flags & PGHDR_WRITEABLE;
64318 ** This optimization cannot be used with a temp-file, as the page may
64325 Pager *pPager = pPg->pPager;
64326 if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
64327 PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
64328 IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
64329 pPg->flags |= PGHDR_DONT_WRITE;
64330 pPg->flags &= ~PGHDR_WRITEABLE;
64331 testcase( pPg->flags & PGHDR_NEED_SYNC );
64338 ** change-counter, stored as a 4-byte big-endian integer starting at
64342 ** But this only happens if the pPager->changeCountDone flag is false.
64344 ** See also the pager_write_changecounter() routine that does an
64352 ** The isDirectMode flag may only be non-zero if the library was compiled
64354 ** if isDirect is non-zero, then the database file is updated directly
64355 ** by writing an updated version of page 1 using a call to the
64361 assert( pPager->eState==PAGER_WRITER_CACHEMOD
64362 || pPager->eState==PAGER_WRITER_DBMOD
64367 ** atomic-write optimization is enabled in this build, then isDirect
64371 ** The idea is that if the atomic-write optimization is not
64384 if( !pPager->changeCountDone && pPager->dbSize>0 ){
64387 assert( !pPager->tempFile && isOpen(pPager->fd) );
64394 ** operating in direct-mode, make page 1 writable. When not in
64396 ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
64409 assert( pPager->dbFileSize>0 );
64410 zBuf = pPgHdr->pData;
64412 rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
64413 pPager->aStat[PAGER_STAT_WRITE]++;
64416 /* Update the pager's copy of the change-counter. Otherwise, the
64418 ** flushed (as the change-counter values will not match). */
64420 memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
64421 pPager->changeCountDone = 1;
64424 pPager->changeCountDone = 1;
64435 ** Sync the database file to disk. This is a no-op for in-memory databases
64438 ** If successful, or if called on a pager for which it is a no-op, this
64439 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
64444 rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
64446 if( rc==SQLITE_OK && !pPager->noSync ){
64448 rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
64454 ** This function may only be called while a write-transaction is active in
64455 ** rollback. If the connection is in WAL mode, this call is a no-op.
64456 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
64457 ** the database file, an attempt is made to obtain one.
64461 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
64465 int rc = pPager->errCode;
64468 assert( pPager->eState==PAGER_WRITER_CACHEMOD
64469 || pPager->eState==PAGER_WRITER_DBMOD
64470 || pPager->eState==PAGER_WRITER_LOCKED
64482 ** of a super-journal file that should be written into the individual
64484 ** super-journal (a single database transaction).
64488 ** * The database file change-counter is updated,
64489 ** * the journal is synced (unless the atomic-write optimization is used),
64496 ** delete the super-journal file if specified).
64499 ** passed to an sqlite3PagerCommitPhaseOne() call.
64501 ** If the final parameter - noSync - is true, then the database file itself
64508 const char *zSuper, /* If not NULL, the super-journal name */
64513 assert( pPager->eState==PAGER_WRITER_LOCKED
64514 || pPager->eState==PAGER_WRITER_CACHEMOD
64515 || pPager->eState==PAGER_WRITER_DBMOD
64516 || pPager->eState==PAGER_ERROR
64521 if( NEVER(pPager->errCode) ) return pPager->errCode;
64523 /* Provide the ability to easily simulate an I/O error during testing */
64527 pPager->zFilename, zSuper, pPager->dbSize));
64530 if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
64532 assert( MEMDB==0 || pPager->tempFile );
64533 assert( isOpen(pPager->fd) || pPager->tempFile );
64535 /* If this is an in-memory db, or no pages have been written to, or this
64536 ** function has already been called, it is mostly a no-op. However, any
64538 sqlite3BackupRestart(pPager->pBackup);
64543 pList = sqlite3PcacheDirtyList(pPager->pPCache);
64546 ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
64549 pList->pDirty = 0;
64553 rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
64557 sqlite3PcacheCleanAll(pPager->pPCache);
64560 /* The bBatch boolean is true if the batch-atomic-write commit method
64561 ** should be used. No rollback journal is created if batch-atomic-write
64565 sqlite3_file *fd = pPager->fd;
64566 int bBatch = zSuper==0 /* An SQLITE_IOCAP_BATCH_ATOMIC commit */
64568 && !pPager->noSync
64569 && sqlite3JournalIsInMemory(pPager->jfd);
64575 /* The following block updates the change-counter. Exactly how it
64576 ** does this depends on whether or not the atomic-update optimization
64580 ** * The file-system supports the atomic-write property for
64581 ** blocks of size page-size, and
64582 ** * This commit is not part of a multi-file transaction, and
64587 ** counter in 'indirect-mode'. If the optimization is compiled in but
64590 ** pager_incr_changecounter() to update the change-counter in indirect
64594 ** then call pager_incr_changecounter() to update the change-counter
64600 assert( isOpen(pPager->jfd)
64601 || pPager->journalMode==PAGER_JOURNALMODE_OFF
64602 || pPager->journalMode==PAGER_JOURNALMODE_WAL
64604 if( !zSuper && isOpen(pPager->jfd)
64605 && pPager->journalOff==jrnlBufferSize(pPager)
64606 && pPager->dbSize>=pPager->dbOrigSize
64607 && (!(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
64609 /* Update the db file change counter via the direct-write method. The
64610 ** following call will modify the in-memory representation of page 1
64612 ** directly to the database file. Because of the atomic-write
64613 ** property of the host file-system, this is safe.
64617 rc = sqlite3JournalCreate(pPager->jfd);
64626 rc = sqlite3JournalCreate(pPager->jfd);
64635 /* Write the super-journal name into the journal file. If a
64636 ** super-journal file name has already been written to the journal file,
64637 ** or if zSuper is NULL (no super-journal), then this call is a no-op.
64643 ** If the atomic-update optimization is being used, this sync will not
64646 ** Because the change-counter page was just modified, unless the
64647 ** atomic-update optimization is used it is almost certain that the
64651 ** xSync() call will be changed to a no-op by the OS anyhow.
64656 pList = sqlite3PcacheDirtyList(pPager->pPCache);
64662 if( rc==SQLITE_OK && pPager->dbSize>pPager->dbFileSize ){
64663 char *pTmp = pPager->pTmpSpace;
64664 int szPage = (int)pPager->pageSize;
64666 rc = sqlite3OsWrite(pPager->fd, pTmp, szPage,
64667 ((i64)pPager->dbSize*pPager->pageSize)-szPage);
64678 rc = sqlite3JournalCreate(pPager->jfd);
64680 sqlite3OsClose(pPager->jfd);
64685 sqlite3OsClose(pPager->jfd);
64697 sqlite3PcacheCleanAll(pPager->pPCache);
64702 ** last page in the db image moved to the free-list. In this case the
64705 if( pPager->dbSize>pPager->dbFileSize ){
64706 Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_SJ_PGNO(pPager));
64707 assert( pPager->eState==PAGER_WRITER_DBMOD );
64722 pPager->eState = PAGER_WRITER_FINISHED;
64731 ** synced to disk. The journal file still exists in the file-system
64733 ** be used as a hot-journal and the current transaction rolled back.
64737 ** for hot-journal rollback. Once this is done the transaction is
64740 ** If an error occurs, an IO error code is returned and the pager
64749 if( NEVER(pPager->errCode) ) return pPager->errCode;
64750 pPager->iDataVersion++;
64752 assert( pPager->eState==PAGER_WRITER_LOCKED
64753 || pPager->eState==PAGER_WRITER_FINISHED
64754 || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
64758 /* An optimization. If the database was not actually modified during
64759 ** this transaction, the pager is running in exclusive-mode and is
64760 ** using persistent journals, then this function is a no-op.
64764 ** a hot-journal during hot-journal rollback, 0 changes will be made
64769 if( pPager->eState==PAGER_WRITER_LOCKED
64770 && pPager->exclusiveMode
64771 && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
64773 assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
64774 pPager->eState = PAGER_READER;
64779 rc = pager_end_transaction(pPager, pPager->setSuper, 1);
64785 ** transaction are reverted and the current write-transaction is closed.
64787 ** state if an error occurs.
64795 ** in-memory cache pages to the state they were in when the transaction
64804 ** In WAL mode, all cache-entries containing data modified within the
64806 ** their pre-transaction state by re-reading data from the database or
64813 /* PagerRollback() is a no-op if called in READER or OPEN state. If
64818 if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
64819 if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
64823 rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
64824 rc2 = pager_end_transaction(pPager, pPager->setSuper, 0);
64826 }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
64827 int eState = pPager->eState;
64834 pPager->errCode = SQLITE_ABORT;
64835 pPager->eState = PAGER_ERROR;
64843 assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
64849 /* If an error occurs during a ROLLBACK, we can no longer trust the pager
64856 ** Return TRUE if the database file is opened read-only. Return FALSE
64860 return pPager->readOnly;
64868 return sqlite3PcacheRefCount(pPager->pPCache);
64877 int perPageSize = pPager->pageSize + pPager->nExtra
64879 return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
64881 + pPager->pageSize;
64897 a[0] = sqlite3PcacheRefCount(pPager->pPCache);
64898 a[1] = sqlite3PcachePagecount(pPager->pPCache);
64899 a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
64900 a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
64901 a[4] = pPager->eState;
64902 a[5] = pPager->errCode;
64903 a[6] = (int)pPager->aStat[PAGER_STAT_HIT] & 0x7fffffff;
64904 a[7] = (int)pPager->aStat[PAGER_STAT_MISS] & 0x7fffffff;
64905 a[8] = 0; /* Used to be pPager->nOvfl */
64906 a[9] = pPager->nRead;
64907 a[10] = (int)pPager->aStat[PAGER_STAT_WRITE] & 0x7fffffff;
64920 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
64936 eStat -= SQLITE_DBSTATUS_CACHE_HIT;
64937 *pnVal += pPager->aStat[eStat];
64939 pPager->aStat[eStat] = 0;
64944 ** Return true if this is an in-memory or temp-file backed pager.
64947 return pPager->tempFile || pPager->memVfs;
64954 ** equal to nSavepoint, then this function is a no-op.
64956 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
64957 ** occurs while opening the sub-journal file, then an IO error code is
64962 int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
64966 assert( pPager->eState>=PAGER_WRITER_LOCKED );
64968 assert( nSavepoint>nCurrent && pPager->useJournal );
64975 pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
64980 memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
64981 pPager->aSavepoint = aNew;
64985 aNew[ii].nOrig = pPager->dbSize;
64986 if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
64987 aNew[ii].iOffset = pPager->journalOff;
64991 aNew[ii].iSubRec = pPager->nSubRec;
64992 aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
64998 sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
65000 pPager->nSavepoint = ii+1;
65002 assert( pPager->nSavepoint==nSavepoint );
65007 assert( pPager->eState>=PAGER_WRITER_LOCKED );
65010 if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
65030 ** (the first created). A value of (Pager.nSavepoint-1) means operate
65032 ** (Pager.nSavepoint-1), then this function is a no-op.
65040 ** In any case, all savepoints with an index greater than iSavepoint
65045 ** or an IO error code if an IO error occurs while rolling back a
65049 int rc = pPager->errCode;
65058 if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
65067 for(ii=nNew; ii<pPager->nSavepoint; ii++){
65068 sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
65070 pPager->nSavepoint = nNew;
65072 /* Truncate the sub-journal so that it only includes the parts
65075 PagerSavepoint *pRel = &pPager->aSavepoint[nNew];
65076 if( pRel->bTruncateOnRelease && isOpen(pPager->sjfd) ){
65077 /* Only truncate if it is an in-memory sub-journal. */
65078 if( sqlite3JournalIsInMemory(pPager->sjfd) ){
65079 i64 sz = (pPager->pageSize+4)*(i64)pRel->iSubRec;
65080 rc = sqlite3OsTruncate(pPager->sjfd, sz);
65083 pPager->nSubRec = pRel->iSubRec;
65087 ** If this is a temp-file, it is possible that the journal file has
65091 else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
65092 PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
65103 pPager->journalMode==PAGER_JOURNALMODE_OFF
65104 && pPager->eState>=PAGER_WRITER_CACHEMOD
65106 pPager->errCode = SQLITE_ABORT;
65107 pPager->eState = PAGER_ERROR;
65119 ** Except, if the pager is in-memory only, then return an empty string if
65123 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
65124 ** participate in shared-cache.
65131 if( nullIfMemDb && (pPager->memDb || sqlite3IsMemdb(pPager->pVfs)) ){
65134 return pPager->zFilename;
65142 return pPager->pVfs;
65151 return pPager->fd;
65160 return pPager->jfd;
65162 return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
65170 return pPager->zJournal;
65183 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
65191 ** If the fourth argument, isCommit, is non-zero, then this page is being
65196 ** This function may return SQLITE_NOMEM or an IO error code if an error
65201 Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
65205 assert( pPg->nRef>0 );
65206 assert( pPager->eState==PAGER_WRITER_CACHEMOD
65207 || pPager->eState==PAGER_WRITER_DBMOD
65211 /* In order to be able to rollback, an in-memory database must journal
65214 assert( pPager->tempFile || !MEMDB );
65215 if( pPager->tempFile ){
65222 ** sub-journal now. This is required to handle the following scenario:
65230 ** If page X were not written to the sub-journal here, it would not
65234 ** subjournalPage() may need to allocate space to store pPg->pgno into
65238 if( (pPg->flags & PGHDR_DIRTY)!=0
65245 PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
65246 IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
65248 /* If the journal needs to be sync()ed before page pPg->pgno can
65249 ** be written to, store pPg->pgno in local variable needSyncPgno.
65252 ** the journal needs to be sync()ed before database page pPg->pgno
65255 if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
65256 needSyncPgno = pPg->pgno;
65257 assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
65258 pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
65259 assert( pPg->flags&PGHDR_DIRTY );
65262 /* If the cache contains a page with page-number pgno, remove it
65267 pPg->flags &= ~PGHDR_NEED_SYNC;
65269 assert( !pPgOld || pPgOld->nRef==1 || CORRUPT_DB );
65271 if( NEVER(pPgOld->nRef>1) ){
65275 pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
65276 if( pPager->tempFile ){
65277 /* Do not discard pages from an in-memory database since we might
65279 sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
65285 origPgno = pPg->pgno;
65289 /* For an in-memory database, make sure the original page continues
65293 if( pPager->tempFile && pPgOld ){
65299 /* If needSyncPgno is non-zero, then the journal file needs to be
65301 ** Currently, no such page exists in the page-cache and the
65303 ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
65306 ** If the attempt to load the page into the page-cache fails, (due
65316 if( needSyncPgno<=pPager->dbOrigSize ){
65317 assert( pPager->pTmpSpace!=0 );
65318 sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
65322 pPgHdr->flags |= PGHDR_NEED_SYNC;
65338 assert( pPg->pgno!=iNew );
65339 pPg->flags = flags;
65347 assert( pPg->nRef>0 || pPg->pPager->memDb );
65348 return pPg->pData;
65356 return pPg->pExtra;
65360 ** Get/set the locking-mode for this pager. Parameter eMode must be one
65363 ** the locking-mode is set to the value specified.
65367 ** locking-mode.
65375 assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
65376 if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
65377 pPager->exclusiveMode = (u8)eMode;
65379 return (int)pPager->exclusiveMode;
65383 ** Set the journal-mode for this pager. Parameter eMode must be one of:
65395 ** * An in-memory database can only have its journal_mode set to _OFF
65400 ** The returned indicate the current (possibly updated) journal-mode.
65403 u8 eOld = pPager->journalMode; /* Prior journalmode */
65417 assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
65419 /* Do allow the journalmode of an in-memory database to be set to
65432 assert( pPager->eState!=PAGER_ERROR );
65433 pPager->journalMode = (u8)eMode;
65446 assert( isOpen(pPager->fd) || pPager->exclusiveMode );
65447 if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
65450 ** here is an optimization only.
65456 sqlite3OsClose(pPager->jfd);
65457 if( pPager->eLock>=RESERVED_LOCK ){
65458 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
65461 int state = pPager->eState;
65466 if( pPager->eState==PAGER_READER ){
65471 sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
65478 assert( state==pPager->eState );
65481 sqlite3OsClose(pPager->jfd);
65486 return (int)pPager->journalMode;
65493 return (int)pPager->journalMode;
65503 if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
65504 if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
65509 ** Get/set the size-limit used for persistent journal files.
65511 ** Setting the size limit to -1 means no limit is enforced.
65512 ** An attempt to set a limit smaller than -1 is a no-op.
65515 if( iLimit>=-1 ){
65516 pPager->journalSizeLimit = iLimit;
65517 sqlite3WalLimit(pPager->pWal, iLimit);
65519 return pPager->journalSizeLimit;
65523 ** Return a pointer to the pPager->pBackup variable. The backup module
65525 ** uses it opaquely as an argument to sqlite3BackupRestart() and
65529 return &pPager->pBackup;
65534 ** Unless this is an in-memory or temporary database, clear the pager cache.
65537 assert( MEMDB==0 || pPager->tempFile );
65538 if( pPager->tempFile==0 ) pager_reset(pPager);
65559 if( pPager->pWal==0 && pPager->journalMode==PAGER_JOURNALMODE_WAL ){
65571 if( pPager->pWal ){
65572 rc = sqlite3WalCheckpoint(pPager->pWal, db, eMode,
65573 (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
65574 pPager->pBusyHandlerArg,
65575 pPager->walSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
65583 return sqlite3WalCallback(pPager->pWal);
65588 ** primitives necessary for write-ahead logging.
65591 const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
65592 if( pPager->noLock ) return 0;
65593 return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
65597 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
65604 assert( pPager->eLock>=SHARED_LOCK );
65605 eOrigLock = pPager->eLock;
65618 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
65619 ** lock on the database file and use heap-memory to store the wal-index
65620 ** in. Otherwise, use the normal shared-memory.
65625 assert( pPager->pWal==0 && pPager->tempFile==0 );
65626 assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
65628 /* If the pager is already in exclusive-mode, the WAL module will use
65629 ** heap-memory for the wal-index instead of the VFS shared-memory
65633 if( pPager->exclusiveMode ){
65638 ** (e.g. due to malloc() failure), return an error code.
65641 rc = sqlite3WalOpen(pPager->pVfs,
65642 pPager->fd, pPager->zWal, pPager->exclusiveMode,
65643 pPager->journalSizeLimit, &pPager->pWal
65647 sqlite3WalDb(pPager->pWal, pPager->dbWal);
65662 ** file (not a temp file or an in-memory database), and the WAL file
65663 ** is not already open, make an attempt to open it now. If successful,
65664 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
65665 ** not support the xShmXXX() methods, return an error code. *pbOpen is
65668 ** If the pager is open on a temp-file (or in-memory database), or if
65674 int *pbOpen /* OUT: Set to true if call is a no-op */
65679 assert( pPager->eState==PAGER_OPEN || pbOpen );
65680 assert( pPager->eState==PAGER_READER || !pbOpen );
65682 assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
65684 if( !pPager->tempFile && !pPager->pWal ){
65688 sqlite3OsClose(pPager->jfd);
65692 pPager->journalMode = PAGER_JOURNALMODE_WAL;
65693 pPager->eState = PAGER_OPEN;
65706 ** Before closing the log file, this function attempts to take an
65707 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
65714 assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
65716 /* If the log file is not already open, but does exist in the file-system,
65720 if( !pPager->pWal ){
65725 pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
65733 /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
65734 ** the database file, the log and log-summary files will be deleted.
65736 if( rc==SQLITE_OK && pPager->pWal ){
65739 rc = sqlite3WalClose(pPager->pWal, db, pPager->walSyncFlags,
65740 pPager->pageSize, (u8*)pPager->pTmpSpace);
65741 pPager->pWal = 0;
65743 if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
65751 ** If pager pPager is a wal-mode database not in exclusive locking mode,
65754 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
65758 if( pagerUseWal(pPager) && pPager->exclusiveMode==0 ){
65759 rc = sqlite3WalWriteLock(pPager->pWal, bLock);
65769 pPager->dbWal = db;
65771 sqlite3WalDb(pPager->pWal, db);
65779 ** currently open. Otherwise, return an error.
65783 if( pPager->pWal ){
65784 rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
65792 ** identifies. If this is not a WAL database, return an error.
65799 if( pPager->pWal ){
65800 sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
65809 ** is not a WAL database, return an error.
65813 if( pPager->pWal ){
65814 rc = sqlite3WalSnapshotRecover(pPager->pWal);
65835 if( pPager->pWal ){
65836 rc = sqlite3WalSnapshotCheck(pPager->pWal, pSnapshot);
65844 ** Release a lock obtained by an earlier successful call to
65848 assert( pPager->pWal );
65849 sqlite3WalSnapshotUnlock(pPager->pWal);
65857 ** A read-lock must be held on the pager when this function is called. If
65864 assert( pPager->eState>=PAGER_READER );
65865 return sqlite3WalFramesize(pPager->pWal);
65871 return sqlite3WalSystemErrno(pPager->pWal);
65891 ** This file contains the implementation of a write-ahead log (WAL) used in
65894 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
65902 ** transferred back into the database file in an operation called a
65913 ** big-endian 32-bit unsigned integer values:
65919 ** 16: Salt-1, random integer incremented with each checkpoint
65920 ** 20: Salt-2, a different random integer changing with each ckpt
65921 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
65922 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
65924 ** Immediately following the wal-header are zero or more frames. Each
65925 ** frame consists of a 24-byte frame-header followed by <page-size> bytes
65926 ** of page data. The frame-header is six big-endian 32-bit unsigned
65932 ** 8: Salt-1 (copied from the header)
65933 ** 12: Salt-2 (copied from the header)
65934 ** 16: Checksum-1.
65935 ** 20: Checksum-2.
65940 ** (1) The salt-1 and salt-2 values in the frame-header match
65941 ** salt values in the wal-header
65943 ** (2) The checksum values in the final 8 bytes of the frame-header
65948 ** The checksum is computed using 32-bit big-endian integers if the
65950 ** is computed using little-endian if the magic number is 0x377f0682.
65952 ** big-endian format regardless of which byte order is used to compute
65954 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
65957 ** for i from 0 to n-1 step 2:
65964 ** of the sequence being summed.) The s1 value spans all 32-bit
65967 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
65968 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
65969 ** The VFS.xSync operations serve as write barriers - all writes launched
65973 ** After each checkpoint, the salt-1 value is incremented and the salt-2
66002 ** data structure called the wal-index is maintained to expedite the
66005 ** WAL-INDEX FORMAT
66007 ** Conceptually, the wal-index is shared memory, though VFS implementations
66008 ** might choose to implement the wal-index using a mmapped file. Because
66009 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
66013 ** In the default unix and windows implementation, the wal-index is a mmapped
66014 ** file whose name is the database name with a "-shm" suffix added. For that
66015 ** reason, the wal-index is sometimes called the "shm" file.
66017 ** The wal-index is transient. After a crash, the wal-index can (and should
66019 ** to either truncate or zero the header of the wal-index when the last
66020 ** connection to it closes. Because the wal-index is transient, it can
66021 ** use an architecture-specific format; it does not have to be cross-platform.
66023 ** as big endian, the wal-index can store multi-byte values in the native
66026 ** The purpose of the wal-index is to answer this question quickly: Given
66031 ** The wal-index consists of a header region, followed by an one or
66034 ** The wal-index header contains the total number of frames within the WAL
66040 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
66042 ** wal-index. The values are:
66047 ** Each index block contains two sections, a page-mapping that contains the
66048 ** database page number associated with each wal frame, and a hash-table
66049 ** that allows readers to query an index block for a specific page number.
66050 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
66051 ** for the first index block) 32-bit page numbers. The first entry in the
66052 ** first index-block contains the database page number corresponding to the
66057 ** The last index block in a wal-index usually contains less than the full
66058 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
66060 ** allocated size of the page-mapping array - the page-mapping array merely
66064 ** can be found by scanning the page-mapping sections of each index block
66070 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
66074 ** prior to finding a match is 1. Each entry of the hash table is an
66075 ** 1-based index of an entry in the mapping section of the same
66076 ** index block. Let K be the 1-based index of the largest entry in
66089 ** reached) until an unused hash slot is found. Let the first unused slot
66091 ** wrap-around.) Because the hash table is never more than half full,
66092 ** the search is guaranteed to eventually hit an unused entry. Let
66096 ** current index block. Otherwise the iMax-th mapping entry of the
66114 ** and to the wal-index) might be using a different value K1, where K1>K0.
66118 ** slots in the hash table and so the first reader will get an answer as
66120 ** in the first place - which is what reader one wants. Meanwhile, the
66143 ** The maximum (and only) versions of the wal and wal-index formats
66147 ** values in the wal-header are correct and (b) the version field is not
66150 ** Similarly, if a client successfully reads a wal-index header (i.e. the
66152 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
66167 ** WalCkptInfo.aLock[] array in the wal-index header. In other words, all
66177 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
66187 ** The following object holds a copy of the wal-index header content.
66189 ** The actual header in the wal-index consists of two copies of this
66196 ** Or it can be 1 to represent a 65536-byte page. The latter case was
66200 u32 iVersion; /* Wal-index version */
66204 u8 bigEndCksum; /* True if checksums in WAL are big-endian */
66214 ** A copy of the following object occurs in the wal-index immediately
66237 ** holds read-lock K, then the value in aReadMark[K] is no greater than
66240 ** a special case; its value is never used and it exists as a place-holder
66246 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
66254 ** largest value and will increase an unused aReadMark[] to mxFrame if there
66255 ** is not already an aReadMark[] equal to mxFrame. The exception to the
66269 ** We assume that 32-bit loads are atomic and so no locks are needed in
66282 ** This is a schematic view of the complete 136-byte header of the
66283 ** wal-index file (also known as the -shm file):
66285 ** +-----------------------------+
66287 ** +-----------------------------+ |
66289 ** +-----------------------------+ |
66291 ** +-------+-------+-------------+ |
66293 ** +-------+-------+-------------+ |
66295 ** +-----------------------------+ | WalIndexHdr object
66297 ** +-----------------------------+ |
66300 ** +-----------------------------+ |
66303 ** +-----------------------------+ |
66306 ** +-----------------------------+
66308 ** +-----------------------------+ |
66310 ** +-----------------------------+ |
66312 ** +-------+-------+-------------+ |
66314 ** +-------+-------+-------------+ | Second copy of the
66316 ** +-----------------------------+ |
66318 ** +-----------------------------+ |
66321 ** +-----------------------------+ |
66324 ** +-----------------------------+ |
66327 ** +-----------------------------+
66329 ** +-----------------------------+
66335 ** +-------+-------+------+------+
66337 ** +-------+-------+------+------+ ) 8 lock bytes
66339 ** +-------+-------+------+------+
66341 ** +-----------------------------+
66343 ** +-----------------------------+
66348 ** only support mandatory file-locks, we do not read or write data
66361 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
66362 ** big-endian format in the first 4 bytes of a WAL file.
66365 ** file are calculated by treating all data as an array of 32-bit
66366 ** big-endian words. Otherwise, they are calculated by interpreting
66367 ** all data as 32-bit little-endian words.
66372 ** Return the offset of frame iFrame in the write-ahead log file,
66374 ** is to the start of the write-ahead log frame-header.
66377 WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
66381 ** An open write-ahead log file is represented by an instance of the
66397 volatile u32 **apWiData; /* Pointer to wal-index content in memory */
66399 i16 readLock; /* Which read lock is being held. -1 for none */
66401 u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
66408 u8 bShmUnreliable; /* SHM content is read-only and unreliable */
66409 WalIndexHdr hdr; /* Wal-index header for current transaction */
66413 u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
66449 ** Each page of the wal-index mapping contains a hash-table made up of
66450 ** an array of HASHTABLE_NSLOT elements of the following type.
66455 ** This structure is used to implement an iterator that loops through
66463 ** walIteratorInit() - Create a new iterator,
66464 ** walIteratorNext() - Step an iterator,
66465 ** walIteratorFree() - Free an iterator.
66478 } aSegment[FLEXARRAY]; /* One for every 32KB page in the wal-index */
66486 ** Define the parameters of the hash tables in the wal-index file. There
66487 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
66488 ** wal-index.
66490 ** Changing any of these constants will alter the wal-index format and
66498 ** The block of page numbers associated with the first hash-table in a
66499 ** wal-index is smaller than usual. This is so that there is a complete
66500 ** hash-table on each aligned 32KB page of the wal-index.
66502 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
66504 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
66510 ** Structured Exception Handling (SEH) is a Windows-specific technique
66511 ** for catching exceptions raised while accessing memory-mapped files.
66513 ** The -DSQLITE_USE_SEH compile-time option means to use SEH to catch and
66514 ** deal with system-level errors that arise during WAL -shm file processing.
66515 ** Without this compile-time option, any system-level faults that appear
66516 ** while accessing the memory-mapped -shm file will cause a process-wide
66523 /* Beginning of a block of code in which an exception might occur */
66525 assert( walAssertLockmask(pWal) && pWal->nSehTry==0 ); \
66526 VVA_ONLY(pWal->nSehTry++);
66528 /* The end of a block of code in which an exception might occur */
66530 VVA_ONLY(pWal->nSehTry--); \
66531 assert( pWal->nSehTry==0 ); \
66534 /* Simulate a memory-mapping fault in the -shm file for testing purposes */
66540 ** indicates that the exception may have been caused by accessing the *-shm
66544 VVA_ONLY(pWal->nSehTry--);
66546 if( p && p->ExceptionRecord && p->ExceptionRecord->NumberParameters>=3 ){
66548 ** ExceptionInformation[] array is a read-write flag - 0 if the exception
66552 pWal->iSysErrno = (int)p->ExceptionRecord->ExceptionInformation[2];
66562 ** thrown by the system if the *-shm file mapping is accessed after it
66567 assert( pWal->nSehTry>0 );
66581 ** if an exception is thrown:
66593 assert( (X==0 || Y==0) && pWal->pFree==X ); pWal->pFree = Y
66596 ** There are two ways to use this macro. To arrange for pWal->apWiData[iPg]
66597 ** to be set to pValue if an exception is thrown:
66605 #define SEH_SET_ON_ERROR(X,Y) pWal->iWiPg = X; pWal->pWiValue = Y
66608 # define SEH_TRY VVA_ONLY(pWal->nSehTry++);
66609 # define SEH_EXCEPT(X) VVA_ONLY(pWal->nSehTry--); assert( pWal->nSehTry==0 );
66610 # define SEH_INJECT_FAULT assert( pWal->nSehTry>0 );
66617 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
66618 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
66621 ** If the wal-index is currently smaller the iPage pages then the size
66622 ** of the wal-index might be increased, but only if it is safe to do
66623 ** so. It is safe to enlarge the wal-index if pWal->writeLock is true
66624 ** or pWal->exclusiveMode==WAL_HEAPMEMORY_MODE.
66628 ** (1) rc==SQLITE_OK and *ppPage==Requested-Wal-Index-Page
66632 ** Scenario (3) can only occur when pWal->writeLock is false and iPage==0
66641 /* Enlarge the pWal->apWiData[] array if required */
66642 if( pWal->nWiData<=iPage ){
66645 apNew = (volatile u32 **)sqlite3Realloc((void *)pWal->apWiData, nByte);
66650 memset((void*)&apNew[pWal->nWiData], 0,
66651 sizeof(u32*)*(iPage+1-pWal->nWiData));
66652 pWal->apWiData = apNew;
66653 pWal->nWiData = iPage+1;
66657 assert( pWal->apWiData[iPage]==0 );
66658 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
66659 pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
66660 if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
66662 rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
66663 pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
66665 assert( pWal->apWiData[iPage]!=0
66667 || (pWal->writeLock==0 && iPage==0) );
66668 testcase( pWal->apWiData[iPage]==0 && rc==SQLITE_OK );
66672 pWal->readOnly |= WAL_SHM_RDONLY;
66679 *ppPage = pWal->apWiData[iPage];
66689 if( pWal->nWiData<=iPage || (*ppPage = pWal->apWiData[iPage])==0 ){
66696 ** Return a pointer to the WalCkptInfo structure in the wal-index.
66699 assert( pWal->nWiData>0 && pWal->apWiData[0] );
66701 return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
66705 ** Return a pointer to the WalIndexHdr structure in the wal-index.
66708 assert( pWal->nWiData>0 && pWal->apWiData[0] );
66710 return (volatile WalIndexHdr*)pWal->apWiData[0];
66714 ** The argument to this macro must be of type u32. On a little-endian
66716 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
66718 ** of the input value as a little-endian integer.
66726 ** Generate or extend an 8 byte checksum based on the data in
66735 int nativeCksum, /* True for native byte-order, false for non-native */
66797 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
66798 sqlite3OsShmBarrier(pWal->pDbFd);
66803 ** Add the SQLITE_NO_TSAN as part of the return-type of a function
66805 ** might give false-positive TSAN warnings.
66807 ** See tag-20200519-1.
66816 ** Write the header information in pWal->hdr into the wal-index.
66818 ** The checksum on pWal->hdr is updated before it is written.
66824 assert( pWal->writeLock );
66825 pWal->hdr.isInit = 1;
66826 pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
66827 walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
66828 /* Possible TSAN false-positive. See tag-20200519-1 */
66829 memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
66831 memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
66836 ** supplied by the caller. A frame-header is made up of a series of
66837 ** 4-byte big-endian integers, as follows:
66842 ** 8: Salt-1 (copied from the wal-header)
66843 ** 12: Salt-2 (copied from the wal-header)
66844 ** 16: Checksum-1.
66845 ** 20: Checksum-2.
66848 Wal *pWal, /* The write-ahead log */
66850 u32 nTruncate, /* New db size (or 0 for non-commit frames) */
66854 int nativeCksum; /* True for native byte-order checksums */
66855 u32 *aCksum = pWal->hdr.aFrameCksum;
66859 if( pWal->iReCksum==0 ){
66860 memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
66862 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
66864 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
66879 Wal *pWal, /* The write-ahead log */
66885 int nativeCksum; /* True for native byte-order checksums */
66886 u32 *aCksum = pWal->hdr.aFrameCksum;
66890 /* A frame is only valid if the salt values in the frame-header
66891 ** match the salt values in the wal-header.
66893 if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
66905 ** all prior frames, the first 16 bytes of this frame-header,
66906 ** and the frame-data matches the checksum in the last 8
66907 ** bytes of this frame-header.
66909 nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
66911 walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
66931 ** a part of an ordinary build.
66935 return "WRITE-LOCK";
66937 return "CKPT-LOCK";
66939 return "RECOVER-LOCK";
66942 sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
66943 lockIdx-WAL_READ_LOCK(0));
66952 ** A lock cannot be moved directly between shared and exclusive - it must go
66955 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
66959 if( pWal->exclusiveMode ) return SQLITE_OK;
66960 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
66962 WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
66964 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
66966 if( rc==SQLITE_OK ) pWal->lockMask |= (1 << lockIdx);
66971 if( pWal->exclusiveMode ) return;
66972 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
66975 pWal->lockMask &= ~(1 << lockIdx);
66977 WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
66981 if( pWal->exclusiveMode ) return SQLITE_OK;
66982 rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
66984 WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
66986 VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && (rc&0xFF)!=SQLITE_BUSY); )
66989 pWal->lockMask |= (((1<<n)-1) << (SQLITE_SHM_NLOCK+lockIdx));
66995 if( pWal->exclusiveMode ) return;
66996 (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
66999 pWal->lockMask &= ~(((1<<n)-1) << (SQLITE_SHM_NLOCK+lockIdx));
67001 WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
67007 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
67012 assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
67013 return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
67016 return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
67020 ** An instance of the WalHashLoc object is used to describe the location
67021 ** of a page hash table in the wal-index. This becomes the return value
67026 volatile ht_slot *aHash; /* Start of the wal-index hash table */
67033 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
67036 ** Set output variable pLoc->aHash to point to the start of the hash table
67037 ** in the wal-index file. Set pLoc->iZero to one less than the frame
67040 ** (pLoc->iZero+N) in the log.
67042 ** Finally, set pLoc->aPgno so that pLoc->aPgno[0] is the page number of the
67043 ** first frame indexed by the hash table, frame (pLoc->iZero).
67052 rc = walIndexPage(pWal, iHash, &pLoc->aPgno);
67055 if( pLoc->aPgno ){
67056 pLoc->aHash = (volatile ht_slot *)&pLoc->aPgno[HASHTABLE_NPAGE];
67058 pLoc->aPgno = &pLoc->aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
67059 pLoc->iZero = 0;
67061 pLoc->iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
67070 ** Return the number of the wal-index page that contains the hash-table
67071 ** and page-number array that contain entries corresponding to WAL frame
67072 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
67076 int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
67094 return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
67096 return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
67101 ** than pWal->hdr.mxFrame.
67103 ** This function is called whenever pWal->hdr.mxFrame is decreased due
67106 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
67108 ** pWal->hdr.mxFrame advances to the point where those hash tables are
67117 assert( pWal->writeLock );
67118 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
67119 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
67120 testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
67122 if( pWal->hdr.mxFrame==0 ) return;
67124 /* Obtain pointers to the hash-table and page-number array containing
67125 ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
67126 ** that the page said hash-table and array reside on is already mapped.(1)
67128 assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
67129 assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
67130 i = walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &sLoc);
67131 if( NEVER(i) ) return; /* Defense-in-depth, in case (1) above is wrong */
67133 /* Zero all hash-table entries that correspond to frame numbers greater
67134 ** than pWal->hdr.mxFrame.
67136 iLimit = pWal->hdr.mxFrame - sLoc.iZero;
67145 ** frame numbers greater than pWal->hdr.mxFrame.
67147 nByte = (int)((char *)sLoc.aHash - (char *)&sLoc.aPgno[iLimit]);
67170 ** Set an entry in the wal-index that will map database page number
67175 WalHashLoc sLoc; /* Wal-index hash table location */
67179 /* Assuming the wal-index file was successfully mapped, populate the
67184 int idx; /* Value to write to hash-table slot */
67187 idx = iFrame - sLoc.iZero;
67190 /* If this is the first entry to be added to this hash-table, zero the
67194 int nByte = (int)((u8*)&sLoc.aHash[HASHTABLE_NSLOT] - (u8*)sLoc.aPgno);
67203 ** the hash-table before writing any new entries.
67205 if( sLoc.aPgno[idx-1] ){
67207 assert( !sLoc.aPgno[idx-1] );
67210 /* Write the aPgno[] array entry and the hash-table slot. */
67213 if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
67215 sLoc.aPgno[idx-1] = iPage;
67231 ** thing to check, so only do this occasionally - not on every
67253 ** Recover the wal-index by reading the write-ahead log file.
67255 ** This routine first tries to establish an exclusive lock on the
67256 ** wal-index to prevent other threads/processes from doing anything
67257 ** with the WAL or wal-index while recovery is running. The
67268 /* Obtain an exclusive lock on all byte in the locking range not already
67274 assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
67277 assert( pWal->writeLock );
67278 iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
67279 rc = walLockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
67286 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
67288 rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
67295 u32 *aPrivate = 0; /* Heap copy of *-shm hash being populated */
67303 u32 iPg; /* Current 32KB wal-index page */
67307 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
67320 || szPage&(szPage-1)
67326 pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
67327 pWal->szPage = szPage;
67328 pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
67329 memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
67332 walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
67333 aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
67335 if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
67336 || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
67361 iLastFrame = (nSize - WAL_HDRSIZE) / szFrame;
67366 u32 iFirst = 1 + (iPg==0?0:HASHTABLE_NPAGE_ONE+(iPg-1)*HASHTABLE_NPAGE);
67372 pWal->apWiData[iPg] = aPrivate;
67380 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
67387 /* If nTruncate is non-zero, this is a commit record. */
67389 pWal->hdr.mxFrame = iFrame;
67390 pWal->hdr.nPage = nTruncate;
67391 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
67394 aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
67395 aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
67398 pWal->apWiData[iPg] = aShare;
67411 memcpy(&aShare[nHdr32], &aPrivate[nHdr32], WALINDEX_PGSZ-nHdr);
67442 pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
67443 pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
67446 /* Reset the checkpoint-header. This is safe because this thread is
67448 ** checkpointers. Then set the values of read-mark slots 1 through N.
67451 pInfo->nBackfill = 0;
67452 pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
67453 pInfo->aReadMark[0] = 0;
67457 if( i==1 && pWal->hdr.mxFrame ){
67458 pInfo->aReadMark[i] = pWal->hdr.mxFrame;
67460 pInfo->aReadMark[i] = READMARK_NOT_USED;
67469 /* If more than one frame was recovered from the log file, report an
67474 if( pWal->hdr.nPage ){
67477 pWal->hdr.mxFrame, pWal->zWalName
67484 walUnlockExclusive(pWal, iLock, WAL_READ_LOCK(0)-iLock);
67489 ** Close an open wal-index.
67492 if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE || pWal->bShmUnreliable ){
67494 for(i=0; i<pWal->nWiData; i++){
67495 sqlite3_free((void *)pWal->apWiData[i]);
67496 pWal->apWiData[i] = 0;
67499 if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
67500 sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
67511 ** client from unlinking the WAL or wal-index file. If another process
67516 ** *ppWal is set to point to a new WAL handle. If an error occurs,
67517 ** an SQLite error code is returned and *ppWal is left unmodified.
67520 sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
67523 int bNoShm, /* True to run in heap-memory mode */
67535 ** of these constants would result in an incompatible on-disk format
67536 ** for the -shm file. Any change that causes one of these asserts to
67540 ** This table also serves as a helpful cross-reference when trying to
67541 ** interpret hex dumps of the -shm file.
67569 ** value of 120, we need to know that so there is an assert() to check it.
67579 /* Allocate an instance of struct Wal to return. */
67581 pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
67586 pRet->pVfs = pVfs;
67587 pRet->pWalFd = (sqlite3_file *)&pRet[1];
67588 pRet->pDbFd = pDbFd;
67589 pRet->readLock = -1;
67590 pRet->mxWalSize = mxWalSize;
67591 pRet->zWalName = zWalName;
67592 pRet->syncHeader = 1;
67593 pRet->padToSectorBoundary = 1;
67594 pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
67596 /* Open file handle on the write-ahead log file. */
67598 rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
67600 pRet->readOnly = WAL_RDONLY;
67605 sqlite3OsClose(pRet->pWalFd);
67609 if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
67611 pRet->padToSectorBoundary = 0;
67623 if( pWal ) pWal->mxWalSize = iLimit;
67645 iMin = p->iPrior;
67647 for(i=p->nSegment-1; i>=0; i--){
67648 struct WalSegment *pSegment = &p->aSegment[i];
67649 while( pSegment->iNext<pSegment->nEntry ){
67650 u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
67654 *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
67658 pSegment->iNext++;
67662 *piPage = p->iPrior = iRet;
67690 const u32 *aContent, /* Pages in wal - keys for the sort */
67754 ht_slot *aList; /* Pointer to sub-list content */
67762 struct Sublist aSub[13]; /* Array of sub-lists */
67766 assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
67775 assert( p->aList && p->nList<=(1<<iSub) );
67776 assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
67777 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
67788 assert( p->nList<=(1<<iSub) );
67789 assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
67790 walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
67800 assert( aContent[aList[i]] > aContent[aList[i-1]] );
67807 ** Free an iterator allocated by walIteratorInit().
67816 ** nBackfill or earlier may be included - excluding them is an optimization
67820 ** return SQLITE_OK. Otherwise, return an error code. If this routine
67821 ** returns an error, the value of *pp is undefined.
67832 ht_slot *aTmp; /* Temp space used by merge-sort */
67838 assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
67839 iLast = pWal->hdr.mxFrame;
67852 p->nSegment = nSegment;
67865 nEntry = (int)(iLast - sLoc.iZero);
67867 nEntry = (int)((u32*)sLoc.aHash - (u32*)sLoc.aPgno);
67869 aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[sLoc.iZero];
67876 p->aSegment[i].iZero = sLoc.iZero;
67877 p->aSegment[i].nEntry = nEntry;
67878 p->aSegment[i].aIndex = aIndex;
67879 p->aSegment[i].aPgno = (u32 *)sLoc.aPgno;
67900 pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&nMs
67908 ** with a busy-timeout. Return 1 if blocking locks are successfully enabled,
67913 if( pWal->db ){
67914 int tmout = pWal->db->setlkTimeout;
67927 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_LOCK_TIMEOUT, (void*)&tmout);
67934 ** an SQLite error code if an error occurs, or SQLITE_OK otherwise. It is not
67935 ** an error if blocking locks can not be enabled.
67941 assert( pWal->readLock<0 || bLock==0 );
67943 assert( pWal->db );
67947 pWal->writeLock = 1;
67951 }else if( pWal->writeLock ){
67953 pWal->writeLock = 0;
67962 pWal->db = db;
67976 ** busy-handler function. Invoke it and retry the lock until either the
67977 ** lock is successfully obtained or the busy-handler returns 0.
68000 ** The cache of the wal-index header must be valid to call this function.
68001 ** Return the page-size in bytes used by the database.
68004 return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
68013 ** file - there are no readers that may attempt to read a frame from
68016 ** This function updates the shared-memory structures so that the next
68021 ** new wal-index header. It should be passed a pseudo-random value (i.e.
68027 u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
68028 pWal->nCkpt++;
68029 pWal->hdr.mxFrame = 0;
68031 memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
68033 AtomicStore(&pInfo->nBackfill, 0);
68034 pInfo->nBackfillAttempted = 0;
68035 pInfo->aReadMark[1] = 0;
68036 for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
68037 assert( pInfo->aReadMark[0]==0 );
68042 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
68049 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
68055 ** in the WAL and can be recovered following a power-loss or hard reset.
68062 ** This routine uses and updates the nBackfill field of the wal-index header.
68081 int szPage; /* Database page-size */
68094 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
68096 /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
68105 mxSafeFrame = pWal->hdr.mxFrame;
68106 mxPage = pWal->hdr.nPage;
68108 u32 y = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT;
68110 assert( y<=pWal->hdr.mxFrame );
68114 AtomicStore(pInfo->aReadMark+i, iMark); SEH_INJECT_FAULT;
68126 if( pInfo->nBackfill<mxSafeFrame ){
68127 rc = walIteratorInit(pWal, pInfo->nBackfill, &pIter);
68134 u32 nBackfill = pInfo->nBackfill;
68135 pInfo->nBackfillAttempted = mxSafeFrame; SEH_INJECT_FAULT;
68138 rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
68146 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_START, 0);
68147 rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
68149 if( (nSize+65536+(i64)pWal->hdr.mxFrame*szPage)<nReq ){
68152 ** maximum size of the pending-byte page (65536 bytes), then
68156 sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT,&nReq);
68167 if( AtomicLoad(&db->u1.isInterrupted) ){
68168 rc = db->mallocFailed ? SQLITE_NOMEM_BKPT : SQLITE_INTERRUPT;
68176 rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
68178 iOffset = (iDbpage-1)*(i64)szPage;
68180 rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
68183 sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_CKPT_DONE, 0);
68187 if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
68188 i64 szDb = pWal->hdr.nPage*(i64)szPage;
68190 rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
68192 rc = sqlite3OsSync(pWal->pDbFd, CKPT_SYNC_FLAGS(sync_flags));
68196 AtomicStore(&pInfo->nBackfill, mxSafeFrame); SEH_INJECT_FAULT;
68211 /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
68217 assert( pWal->writeLock );
68219 if( pInfo->nBackfill<pWal->hdr.mxFrame ){
68224 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
68225 rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
68228 /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
68234 ** wal-index header in shared memory, as all subsequent reader or
68238 ** the wal-index header do not match the contents of the
68239 ** file-system. To avoid this, update the wal-index header to
68242 rc = sqlite3OsTruncate(pWal->pWalFd, 0);
68244 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
68257 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
68263 rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
68265 rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
68269 sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
68276 ** an exception thrown by reading from the *-shm mapping after it has become
68291 ** 3) Set pWal->apWiData[pWal->iWiPg] to pWal->pWiValue if not NULL
68296 if( pWal->exclusiveMode==0 ){
68301 if( pWal->writeLock==2 ) pWal->writeLock = 0;
68302 mUnlock = pWal->lockMask & ~(
68303 (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)))
68304 | (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0)
68305 | (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0)
68312 sqlite3_free(pWal->pFree);
68313 pWal->pFree = 0;
68314 if( pWal->pWiValue ){
68315 pWal->apWiData[pWal->iWiPg] = pWal->pWiValue;
68316 pWal->pWiValue = 0;
68329 if( pWal->exclusiveMode==0 ){
68333 (pWal->readLock<0 ? 0 : (S << WAL_READ_LOCK(pWal->readLock)))
68334 | (pWal->writeLock ? (E << WAL_WRITE_LOCK) : 0)
68335 | (pWal->ckptLock ? (E << WAL_CKPT_LOCK) : 0)
68337 | (pWal->pSnapshot ? (pWal->lockMask & (1 << WAL_CKPT_LOCK)) : 0)
68340 assert( mExpect==pWal->lockMask );
68346 ** Return and zero the "system error" field set when an
68352 iRet = pWal->iSysErrno;
68353 pWal->iSysErrno = 0;
68374 int isDelete = 0; /* True to unlink wal and wal-index files */
68378 /* If an EXCLUSIVE lock can be obtained on the database file (using the
68379 ** ordinary, rollback-mode locking methods, this guarantees that the
68382 ** the wal and wal-index files.
68387 && SQLITE_OK==(rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE))
68389 if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
68390 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
68396 int bPersist = -1;
68398 pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
68402 ** fsynced (rc==SQLITE_OK) and if we are not in persistent-wal
68405 }else if( pWal->mxWalSize>=0 ){
68409 ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
68418 sqlite3OsClose(pWal->pWalFd);
68421 sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
68425 sqlite3_free((void *)pWal->apWiData);
68432 ** Try to read the wal-index header. Return 0 on success and 1 if
68435 ** The wal-index is in shared memory. Another thread or process might
68442 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
68445 ** If the checksum cannot be verified return non-zero. If the header
68453 /* The first page of the wal-index must be mapped at this point. */
68454 assert( pWal->nWiData>0 && pWal->apWiData[0] );
68458 ** meaning it is possible that an inconsistent snapshot is read
68459 ** from the file. If this happens, return non-zero.
68461 ** tag-20200519-1:
68462 ** There are two copies of the header at the beginning of the wal-index.
68466 ** give false-positive warnings about these accesses because the tools do not
68467 ** account for the double-read and the memory barrier. The use of mutexes
68473 memcpy(&h1, (void *)&aHdr[0], sizeof(h1)); /* Possible TSAN false-positive */
68481 return 1; /* Malformed header - probably all zeros */
68483 walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
68488 if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
68490 memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
68491 pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
68492 testcase( pWal->szPage<=32768 );
68493 testcase( pWal->szPage>=65536 );
68504 #define WAL_RETRY (-1)
68507 ** Read the wal-index header from the wal-index and into pWal->hdr.
68508 ** If the wal-header appears to be corrupt, try to reconstruct the
68509 ** wal-index from the WAL before returning.
68511 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
68512 ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
68515 ** If the wal-index header is successfully read, return SQLITE_OK.
68516 ** Otherwise an SQLite error code.
68521 volatile u32 *page0; /* Chunk of wal-index containing header */
68523 /* Ensure that page 0 of the wal-index (the page that contains the
68524 ** wal-index header) is mapped. Return early if an error occurs here.
68531 /* The SQLITE_READONLY_CANTINIT return means that the shared-memory
68533 ** confirm that another write-capable connection has the shared-memory
68534 ** open, and hence the content of the shared-memory is unreliable,
68535 ** since the shared-memory might be inconsistent with the WAL file
68538 assert( pWal->writeLock==0 );
68539 assert( pWal->readOnly & WAL_SHM_RDONLY );
68540 pWal->bShmUnreliable = 1;
68541 pWal->exclusiveMode = WAL_HEAPMEMORY_MODE;
68544 return rc; /* Any other non-OK return is just an error */
68547 /* page0 can be NULL if the SHM is zero bytes in size and pWal->writeLock
68551 assert( page0!=0 || pWal->writeLock==0 );
68553 /* If the first page of the wal-index has been mapped, try to read the
68554 ** wal-index header immediately, without holding any lock. This usually
68555 ** works, but may fail if the wal-index header is corrupt or currently
68564 if( pWal->bShmUnreliable==0 && (pWal->readOnly & WAL_SHM_RDONLY) ){
68570 int bWriteLock = pWal->writeLock;
68574 /* If the write-lock was just obtained, set writeLock to 2 instead of
68576 ** write-lock were held (so that it allocates new pages as required),
68577 ** and walHandleException() to unlock the write-lock if a SEH exception
68579 if( !bWriteLock ) pWal->writeLock = 2;
68583 /* If the wal-index header is still malformed even while holding
68593 pWal->writeLock = 0;
68601 ** sure the wal-index was not constructed with some future format that
68604 if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
68607 if( pWal->bShmUnreliable ){
68610 pWal->bShmUnreliable = 0;
68611 assert( pWal->nWiData>0 && pWal->apWiData[0]==0 );
68617 pWal->exclusiveMode = WAL_NORMAL_MODE;
68624 ** Open a transaction in a connection where the shared-memory is read-only
68625 ** and where we cannot verify that there is a separate write-capable connection
68626 ** on hand to keep the shared-memory up-to-date with the WAL file.
68628 ** This can happen, for example, when the shared-memory is implemented by
68629 ** memory-mapping a *-shm file, where a prior writer has shut down and
68630 ** left the *-shm file on disk, and now the present connection is trying
68631 ** to use that database but lacks write permission on the *-shm file.
68636 ** The *-wal file has been read and an appropriate wal-index has been
68637 ** constructed in pWal->apWiData[] using heap memory instead of shared
68644 ** WAL_RETRY, then the heap memory wal-index has been discarded and
68646 ** beginning (including attempting to map the *-shm file).
68648 ** If an error occurs, an SQLite error code is returned.
68659 u32 aSaveCksum[2]; /* Saved copy of pWal->hdr.aFrameCksum */
68661 assert( pWal->bShmUnreliable );
68662 assert( pWal->readOnly & WAL_SHM_RDONLY );
68663 assert( pWal->nWiData>0 && pWal->apWiData[0] );
68673 pWal->readLock = 0;
68675 /* Check to see if a separate writer has attached to the shared-memory area,
68676 ** thus making the shared-memory "reliable" again. Do this by invoking
68680 ** If the shared-memory is now "reliable" return WAL_RETRY, which will
68681 ** cause the heap-memory WAL-index to be discarded and the actual
68690 ** Once sqlite3OsShmMap() has been called for an sqlite3_file and has
68693 ** even if some external agent does a "chmod" to make the shared-memory
68697 rc = sqlite3OsShmMap(pWal->pDbFd, 0, WALINDEX_PGSZ, 0, &pDummy);
68698 assert( rc!=SQLITE_OK ); /* SQLITE_OK not possible for read-only connection */
68704 /* We reach this point only if the real shared-memory is still unreliable.
68705 ** Assume the in-memory WAL-index substitute is correct and load it
68706 ** into pWal->hdr.
68708 memcpy(&pWal->hdr, (void*)walIndexHdr(pWal), sizeof(WalIndexHdr));
68713 rc = sqlite3OsFileSize(pWal->pWalFd, &szWal);
68718 /* If the wal file is too small to contain a wal-header and the
68719 ** wal-index header has mxFrame==0, then it must be safe to proceed
68725 rc = (pWal->hdr.mxFrame==0 ? SQLITE_OK : WAL_RETRY);
68730 rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
68734 if( memcmp(&pWal->hdr.aSalt, &aBuf[16], 8) ){
68736 ** Return WAL_RETRY which will cause the in-memory WAL-index to be
68743 assert( (pWal->szPage & (pWal->szPage-1))==0 );
68744 assert( pWal->szPage>=512 && pWal->szPage<=65536 );
68745 szFrame = pWal->szPage + WAL_FRAME_HDRSIZE;
68754 ** wal file since the heap-memory wal-index was created. If so, the
68755 ** heap-memory wal-index is discarded and WAL_RETRY returned to
68757 aSaveCksum[0] = pWal->hdr.aFrameCksum[0];
68758 aSaveCksum[1] = pWal->hdr.aFrameCksum[1];
68759 for(iOffset=walFrameOffset(pWal->hdr.mxFrame+1, pWal->szPage);
68767 rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
68771 /* If nTruncate is non-zero, then a complete transaction has been
68779 pWal->hdr.aFrameCksum[0] = aSaveCksum[0];
68780 pWal->hdr.aFrameCksum[1] = aSaveCksum[1];
68786 for(i=0; i<pWal->nWiData; i++){
68787 sqlite3_free((void*)pWal->apWiData[i]);
68788 pWal->apWiData[i] = 0;
68790 pWal->bShmUnreliable = 0;
68810 ** it reaches WAL_RETRY_PROTOCOL_LIMIT - indicating that walTryBeginRead()
68811 ** has many times been invoked and failed with WAL_RETRY - walTryBeginRead()
68817 ** the next invocation of walTryBeginRead() may omit an expected call to
68833 ** On success return SQLITE_OK. On a permanent failure (such an
68834 ** I/O error or an SQLITE_BUSY because another process is running
68840 ** to make a copy of the wal-index header into pWal->hdr. If the
68841 ** wal-index header has changed, *pChanged is set to 1 (as an indication
68843 ** flushed.) When useWal==1, the wal-index header is assumed to already
68849 ** race conditions after multiple WAL_RETRY returns, and after an excessive
68854 ** bad luck when there is lots of contention for the wal-index, but that
68858 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
68859 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
68862 ** including frame number aReadMark[pWal->readLock]. The reader will
68863 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
68864 ** Or if pWal->readLock==0, then the reader will ignore the WAL
68867 ** this routine will always set pWal->readLock>0 on success.
68869 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
68875 ** so it takes care to hold an exclusive lock on the corresponding
68879 volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
68885 assert( pWal->readLock<0 ); /* Not currently locked */
68888 assert( (pWal->readOnly & WAL_SHM_RDONLY)==0 || useWal==0 );
68896 ** paged out or take a page-fault that is time-consuming to resolve,
68902 ** is more of a scheduler yield than an actual delay. But on the 10th
68903 ** an subsequent retries, the delays start becoming longer and longer,
68912 VVA_ONLY( pWal->lockError = 1; )
68915 if( *pCnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
68917 /* In SQLITE_ENABLE_SETLK_TIMEOUT builds, configure the file-descriptor
68922 ** read-mark.
68924 ** If the previous call failed due to an SQLITE_BUSY_TIMEOUT error,
68926 ** an extra delay while it was blocking on the lock.
68933 sqlite3OsSleep(pWal->pVfs, nDelay);
68939 if( pWal->bShmUnreliable==0 ){
68958 if( pWal->apWiData[0]==0 ){
68963 ** code that determines whether or not the shared-memory region
68978 else if( pWal->bShmUnreliable ){
68983 assert( pWal->nWiData>0 );
68984 assert( pWal->apWiData[0]!=0 );
68992 if( !useWal && AtomicLoad(&pInfo->nBackfill)==pWal->hdr.mxFrame
68994 && ((pWal->bGetSnapshot==0 && pWal->pSnapshot==0) || pWal->hdr.mxFrame==0)
69003 if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr,sizeof(WalIndexHdr)) ){
69020 pWal->readLock = 0;
69030 ** but not exceeding pWal->hdr.mxFrame and lock that entry.
69034 mxFrame = pWal->hdr.mxFrame;
69036 if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
69037 mxFrame = pWal->pSnapshot->mxFrame;
69041 u32 thisMark = AtomicLoad(pInfo->aReadMark+i); SEH_INJECT_FAULT;
69048 if( (pWal->readOnly & WAL_SHM_RDONLY)==0
69054 AtomicStore(pInfo->aReadMark+i,mxFrame);
69065 assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
69083 /* Now that the read-lock has been obtained, check that neither the
69084 ** value in the aReadMark[] array or the contents of the wal-index
69087 ** It is necessary to check that the wal-index header did not change
69088 ** between the time it was read and when the shared-lock was obtained
69091 ** that occur later in the log than pWal->hdr.mxFrame may have been
69094 ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
69097 ** Before checking that the live wal-index header has not changed
69100 ** to read any frames earlier than minFrame from the wal file - they
69104 ** nBackfill and checking that the wal-header in shared-memory still
69105 ** matches the one cached in pWal->hdr, it is guaranteed that the
69106 ** checkpointer that set nBackfill was not working with a wal-index
69107 ** header newer than that cached in pWal->hdr. If it were, that could
69109 ** a version of page X that lies before pWal->minFrame (call that version
69112 ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
69115 ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
69117 pWal->minFrame = AtomicLoad(&pInfo->nBackfill)+1; SEH_INJECT_FAULT;
69119 if( AtomicLoad(pInfo->aReadMark+mxI)!=mxReadMark
69120 || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
69125 assert( mxReadMark<=pWal->hdr.mxFrame );
69126 pWal->readLock = (i16)mxI;
69138 void *pBuf1, /* Temp buffer pWal->szPage bytes in size */
69139 void *pBuf2 /* Temp buffer pWal->szPage bytes in size */
69141 int szPage = (int)pWal->szPage;
69145 rc = sqlite3OsFileSize(pWal->pDbFd, &szDb);
69148 u32 i = pInfo->nBackfillAttempted;
69149 for(i=pInfo->nBackfillAttempted; i>AtomicLoad(&pInfo->nBackfill); i--){
69157 assert( i - sLoc.iZero - 1 >=0 );
69158 pgno = sLoc.aPgno[i-sLoc.iZero-1];
69159 iDbOff = (i64)(pgno-1) * szPage;
69163 rc = sqlite3OsRead(pWal->pWalFd, pBuf1, szPage, iWalOff);
69166 rc = sqlite3OsRead(pWal->pDbFd, pBuf2, szPage, iDbOff);
69174 pInfo->nBackfillAttempted = i-1;
69189 ** This is only really safe if the file-system is such that any page
69193 ** contains content that duplicate of an earlier version of the same
69196 ** SQLITE_OK is returned if successful, or an SQLite error code if an
69197 ** error occurs. It is not an error if nBackfillAttempted cannot be
69203 assert( pWal->readLock>=0 );
69206 void *pBuf1 = sqlite3_malloc(pWal->szPage);
69207 void *pBuf2 = sqlite3_malloc(pWal->szPage);
69211 pWal->ckptLock = 1;
69216 pWal->ckptLock = 0;
69230 ** below). That function simply calls this one inside an SEH_TRY{...} block.
69238 WalIndexHdr *pSnapshot = pWal->pSnapshot;
69241 assert( pWal->ckptLock==0 );
69242 assert( pWal->nSehTry>0 );
69246 if( memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
69254 ** has not yet set the pInfo->nBackfillAttempted variable to indicate
69257 ** before checking pInfo->nBackfillAttempted. */
69279 if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
69280 /* At this point the client has a lock on an aReadMark[] slot holding
69281 ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
69282 ** is populated with the wal-index header corresponding to the head
69290 ** pSnapshot->mxFrame into the database file. Note that the
69295 assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
69296 assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
69300 ** frames beyond pSnapshot->mxFrame. If either of these conditions are
69301 ** true, return SQLITE_ERROR_SNAPSHOT. Otherwise, overwrite pWal->hdr
69304 if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
69305 && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
69307 assert( pWal->readLock>0 );
69308 memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
69314 /* A client using a non-current snapshot may not ignore any frames
69320 pWal->minFrame = 1;
69341 ** it takes a snapshot of the state of the WAL and wal-index for the current
69343 ** Other threads might append new content to the WAL and wal-index but
69362 ** read-lock.
69366 assert( pWal->writeLock==0 || pWal->readLock<0 );
69368 if( pWal->readLock>=0 ){
69370 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
69371 pWal->readLock = -1;
69380 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
69389 u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
69394 assert( pWal->readLock>=0 || pWal->lockError );
69396 /* If the "last page" field of the wal-index header snapshot is 0, then
69398 ** in this case as an optimization. Likewise, if pWal->readLock==0,
69402 if( iLast==0 || (pWal->readLock==0 && pWal->bShmUnreliable==0) ){
69407 /* Search the hash table or tables for an entry matching page number
69412 ** that adds entries to the wal-index (and possibly to this hash
69416 ** read transaction was opened may have been written incorrectly -
69423 ** if we had exclusive access to the hash-table:
69426 ** This condition filters out normal hash-table collisions.
69430 ** table after the current read-transaction had started.
69432 iMinHash = walFramePage(pWal->minFrame);
69433 for(iHash=walFramePage(iLast); iHash>=iMinHash; iHash--){
69449 if( iFrame<=iLast && iFrame>=pWal->minFrame && sLoc.aPgno[iH-1]==pgno ){
69453 if( (nCollide--)==0 ){
69464 ** of the wal-index file content. Make sure the results agree with the
69469 assert( pWal->bShmUnreliable || pWal->minFrame>0 );
69470 for(iTest=iLast; iTest>=pWal->minFrame && iTest>0; iTest--){
69489 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
69493 ** function wraps walFindFrame() in an SEH_TRY{...} block.
69510 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
69521 sz = pWal->hdr.szPage;
69527 return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
69534 if( pWal && ALWAYS(pWal->readLock>=0) ){
69535 return pWal->hdr.nPage;
69558 /* If the write-lock is already held, then it was obtained before the
69559 ** read-transaction was even opened, making this call a no-op.
69561 if( pWal->writeLock ){
69562 assert( !memcmp(&pWal->hdr,(void*)pWal->apWiData[0],sizeof(WalIndexHdr)) );
69569 assert( pWal->readLock>=0 );
69570 assert( pWal->writeLock==0 && pWal->iReCksum==0 );
69572 if( pWal->readOnly ){
69583 pWal->writeLock = 1;
69590 if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
69598 pWal->writeLock = 0;
69608 if( pWal->writeLock ){
69610 pWal->writeLock = 0;
69611 pWal->iReCksum = 0;
69612 pWal->truncateOnCommit = 0;
69619 ** function moves the write-pointer back to the start of the transaction.
69626 ** Otherwise, if the callback function does not return an error, this
69631 if( ALWAYS(pWal->writeLock) ){
69632 Pgno iMax = pWal->hdr.mxFrame;
69636 /* Restore the clients cache of the wal-index header to the state it
69639 memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
69641 for(iFrame=pWal->hdr.mxFrame+1;
69647 ** (b) has an outstanding reference, then xUndo is either a no-op
69659 if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
69662 pWal->iReCksum = 0;
69668 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
69674 assert( pWal->writeLock );
69675 aWalData[0] = pWal->hdr.mxFrame;
69676 aWalData[1] = pWal->hdr.aFrameCksum[0];
69677 aWalData[2] = pWal->hdr.aFrameCksum[1];
69678 aWalData[3] = pWal->nCkpt;
69683 ** the values in the aWalData[] array. aWalData must point to an array
69690 assert( pWal->writeLock );
69691 assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
69693 if( aWalData[3]!=pWal->nCkpt ){
69694 /* This savepoint was opened immediately after the write-transaction
69699 aWalData[3] = pWal->nCkpt;
69702 if( aWalData[0]<pWal->hdr.mxFrame ){
69703 pWal->hdr.mxFrame = aWalData[0];
69704 pWal->hdr.aFrameCksum[0] = aWalData[1];
69705 pWal->hdr.aFrameCksum[1] = aWalData[2];
69710 if( pWal->iReCksum>pWal->hdr.mxFrame ){
69711 pWal->iReCksum = 0;
69723 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
69727 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
69728 ** if an error occurs.
69734 if( pWal->readLock==0 ){
69736 assert( pInfo->nBackfill==pWal->hdr.mxFrame );
69737 if( pInfo->nBackfill>0 ){
69740 rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
69745 ** wal-index header to reflect this.
69748 ** at this point. But updating the actual wal-index header is also
69752 walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
69758 pWal->readLock = -1;
69774 ** the next fsync should occur - passed from sqlite3WalFrames() into
69787 ** Do a sync when crossing the p->iSyncPoint boundary.
69800 if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
69801 int iFirstAmt = (int)(p->iSyncPoint - iOffset);
69802 rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
69805 iAmt -= iFirstAmt;
69807 assert( WAL_SYNC_FLAGS(p->syncFlags)!=0 );
69808 rc = sqlite3OsSync(p->pFd, WAL_SYNC_FLAGS(p->syncFlags));
69811 rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
69826 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
69827 pData = pPage->pData;
69828 walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
69832 rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
69842 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
69845 const int szPage = pWal->szPage;/* Database page size */
69848 u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
69858 ** wal-file header. Otherwise, read them from the frame header of the
69860 assert( pWal->iReCksum>0 );
69861 if( pWal->iReCksum==1 ){
69864 iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
69866 rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
69867 pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
69868 pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
69870 iRead = pWal->iReCksum;
69871 pWal->iReCksum = 0;
69874 rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
69881 rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
69890 ** Write a set of frames to the log. The caller must hold the write-lock
69895 int szPage, /* Database page-size in bytes */
69913 assert( pWal->writeLock );
69920 { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
69922 pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
69927 if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
69928 iFirst = pLive->mxFrame+1;
69932 ** log file, instead of appending to it at pWal->hdr.mxFrame.
69942 iFrame = pWal->hdr.mxFrame;
69944 u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
69945 u32 aCksum[2]; /* Checksum for wal-header */
69950 sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
69951 if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
69952 memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
69953 walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
69957 pWal->szPage = szPage;
69958 pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
69959 pWal->hdr.aFrameCksum[0] = aCksum[0];
69960 pWal->hdr.aFrameCksum[1] = aCksum[1];
69961 pWal->truncateOnCommit = 1;
69963 rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
69964 WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
69971 ** an out-of-order write following a WAL restart could result in
69976 if( pWal->syncHeader ){
69977 rc = sqlite3OsSync(pWal->pWalFd, CKPT_SYNC_FLAGS(sync_flags));
69981 if( (int)pWal->szPage!=szPage ){
69987 w.pFd = pWal->pWalFd;
69995 for(p=pList; p; p=p->pDirty){
70000 ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
70002 if( iFirst && (p->pDirty || isCommit==0) ){
70004 VVA_ONLY(rc =) walFindFrame(pWal, p->pgno, &iWrite);
70009 if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
70010 pWal->iReCksum = iWrite;
70012 pData = p->pData;
70013 rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
70015 p->flags &= ~PGHDR_WAL_APPEND;
70022 nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
70027 p->flags |= PGHDR_WAL_APPEND;
70031 if( isCommit && pWal->iReCksum ){
70052 if( pWal->padToSectorBoundary ){
70053 int sectorSize = sqlite3SectorSize(pWal->pWalFd);
70054 w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
70075 if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
70076 i64 sz = pWal->mxWalSize;
70077 if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
70081 pWal->truncateOnCommit = 0;
70084 /* Append data to the wal-index. It is not necessary to lock the
70085 ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
70089 iFrame = pWal->hdr.mxFrame;
70090 for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
70091 if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
70093 rc = walIndexAppend(pWal, iFrame, p->pgno);
70098 nExtra--;
70099 rc = walIndexAppend(pWal, iFrame, pLast->pgno);
70104 pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
70107 pWal->hdr.mxFrame = iFrame;
70109 pWal->hdr.iChange++;
70110 pWal->hdr.nPage = nTruncate;
70112 /* If this is a commit, update the wal-index header too. */
70115 pWal->iCallback = iFrame;
70124 ** Write a set of frames to the log. The caller must hold the write-lock
70128 ** function wraps walFrames() in an SEH_TRY{...} block.
70132 int szPage, /* Database page-size in bytes */
70153 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
70169 int isChanged = 0; /* True if a new wal-index header is loaded */
70173 assert( pWal->ckptLock==0 );
70174 assert( pWal->writeLock==0 );
70176 /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
70180 if( pWal->readOnly ) return SQLITE_READONLY;
70187 /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
70189 ** EVIDENCE-OF: R-10421-19736 If any other process is running a
70192 ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
70199 pWal->ckptLock = 1;
70201 /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
70205 ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
70206 ** immediately, and a busy-handler is configured, it is invoked and the
70207 ** writer lock retried until either the busy-handler returns 0 or the
70213 pWal->writeLock = 1;
70223 /* Read the wal-index header. */
70226 /* For a passive checkpoint, do not re-enable blocking locks after
70227 ** reading the wal-index header. A passive checkpoint should not block
70229 ** attempt to obtain is a lock on a read-slot, and it should give up
70234 if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
70235 sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
70241 if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
70249 if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
70251 if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
70258 /* If a new wal-index header was loaded before the checkpoint was
70259 ** performed, then the pager-cache associated with pWal is now
70260 ** out of date. So zero the cached wal-index header to ensure that
70264 memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
70272 if( pWal->ckptLock ){
70274 pWal->ckptLock = 0;
70291 ret = pWal->iCallback;
70292 pWal->iCallback = 0;
70303 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
70305 ** transition out of exclusive-mode is successful, return 1. This
70310 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
70312 ** WAL is already in exclusive-locking mode - meaning that this
70313 ** routine is a no-op. The pager must already hold the exclusive lock
70316 ** If op is negative, then do a dry-run of the op==1 case but do
70323 assert( pWal->writeLock==0 );
70324 assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
70326 /* pWal->readLock is usually set, but might be -1 if there was a
70327 ** prior error while attempting to acquire are read-lock. This cannot
70330 ** upgrade to exclusive-mode following such an error.
70333 assert( pWal->readLock>=0 || pWal->lockError );
70335 assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
70338 if( pWal->exclusiveMode!=WAL_NORMAL_MODE ){
70339 pWal->exclusiveMode = WAL_NORMAL_MODE;
70340 if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
70341 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
70343 rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
70349 assert( pWal->exclusiveMode==WAL_NORMAL_MODE );
70350 assert( pWal->readLock>=0 );
70351 walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
70352 pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
70355 rc = pWal->exclusiveMode==WAL_NORMAL_MODE;
70361 ** Return true if the argument is non-NULL and the WAL module is using
70362 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
70363 ** WAL module is using shared-memory, return false.
70366 return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
70379 assert( pWal->readLock>=0 && pWal->writeLock==0 );
70381 if( memcmp(&pWal->hdr.aFrameCksum[0],aZero,16)==0 ){
70389 memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
70396 /* Try to open on pSnapshot when the next read-transaction starts
70402 if( pSnapshot && ((WalIndexHdr*)pSnapshot)->iVersion==0 ){
70406 ** file, it does not take read-lock 0 if the wal file has been completely
70407 ** checkpointed. Taking read-lock 0 would work, but then it would be
70409 ** this connection is holding its read-transaction open. This is contrary
70410 ** to user expectations, so we avoid it by not taking read-lock 0. */
70411 pWal->bGetSnapshot = 1;
70413 pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
70414 pWal->bGetSnapshot = 0;
70419 ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
70428 if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
70429 if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
70430 if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
70431 if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
70452 if( memcmp(pNew->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
70453 || pNew->mxFrame<walCkptInfo(pWal)->nBackfillAttempted
70465 ** Release a lock obtained by an earlier successful call to
70479 ** read-lock. This function returns the database page-size if it is known,
70483 assert( pWal==0 || pWal->readLock>=0 );
70484 return (pWal ? pWal->szPage : 0);
70491 return pWal->pWalFd;
70528 ** This file implements an external (disk-based) database using BTrees.
70532 ** "Sorting And Searching", pages 473-480. Addison-Wesley
70538 ** ----------------------------------------------------------------
70539 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
70540 ** ----------------------------------------------------------------
70545 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
70556 ** bytes are stored on overflow pages. The payload for an entry
70566 ** Each page can be either a btree page, a freelist page, an overflow
70567 ** page, or a pointer-map page.
70586 ** 40 60 15 4-byte meta values passed to higher layers
70591 ** 52 4 Largest root-page (auto/incr_vacuum)
70592 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
70595 ** 68 4 Application-ID
70597 ** 92 4 The version-valid-for number
70600 ** All of the integer values are big-endian (most significant byte first).
70608 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
70613 ** payload is spilled to overflow pages. Once an overflow page is allocated,
70623 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
70626 ** |----------------|
70628 ** |----------------|
70630 ** |----------------|
70634 ** |----------------|
70637 ** |----------------| ^ Grows upwards
70640 ** |----------------|
70654 ** only keys and no data. The intkey flag means that the key is an integer
70659 ** The cell pointer array contains zero or more 2-byte numbers which are
70690 ** appears first. A variable-length integer may not be more than 9 bytes long.
70692 ** allows a 64-bit integer to be encoded in 9 bytes.
70715 ** filled with data (pagesize - 4 bytes). The last page can have as little
70738 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
70745 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
70756 ** You can change this value at compile-time by specifying a
70757 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
70758 ** header must be exactly 16 bytes including the zero-terminator so
70769 ** Page type flags. An ORed combination of these flags appear as the
70770 ** first byte of on-disk image of every BTree page.
70778 ** An instance of this object stores information about each a single database
70780 ** is derived from the raw on-disk page content.
70782 ** As each database page is loaded into memory, the pager allocates an
70787 ** stored in MemPage.pBt->mutex.
70791 u8 intKey; /* True if table b-trees. False for index b-trees */
70792 u8 intKeyLeaf; /* True if the leaf of an intKey table */
70804 int nFree; /* Number of free bytes on the page. -1 for unknown */
70807 u16 aiOvfl[4]; /* Insert the i-th overflow cell before the aiOvfl-th
70808 ** non-overflow cell */
70812 u8 *aDataEnd; /* One byte past the end of the entire page - not just
70814 ** corruption-induced buffer overflow. */
70842 ** A database connection contains a pointer to an instance of
70870 u32 iBDataVersion; /* Combines with pBt->pPager->iDataVersion */
70884 ** If the shared-data extension is enabled, there may be multiple users
70896 # error wrong numeric code for no-transaction
70899 # error wrong numeric code for read-transaction
70902 # error wrong numeric code for write-transaction
70907 ** An instance of this object represents a single database file.
70925 ** If a BtShared client fails to obtain a write-lock on a database
70926 ** table (because there exists one or more read-locks on the table),
70927 ** the shared-cache enters 'pending-lock' state and isPending is
70930 ** The shared-cache leaves the 'pending lock' state when either of
70936 ** while in the 'pending-lock' state, no connection may start a new
70939 ** This feature is included to help prevent writer-starvation.
70948 u8 autoVacuum; /* True if auto-vacuum is enabled */
70949 u8 incrVacuum; /* True if incr-vacuum is enabled */
70953 u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
70956 u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
70957 u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
70966 sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
70967 Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
70971 BtLock *pLock; /* List of locks held on this shared-btree struct */
70987 #define BTS_NO_WAL 0x0020 /* Do not open write-ahead-log files */
70988 #define BTS_EXCLUSIVE 0x0040 /* pWriter has an exclusive lock */
70989 #define BTS_PENDING 0x0080 /* Waiting for read-locks to clear */
70992 ** An instance of the following structure is used to hold information
71001 u16 nSize; /* Size of the cell content on the main b-tree page */
71005 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
71008 ** root-node and 3 for all other internal nodes.
71019 #define BT_MAX_LOCAL 65501 /* 65536 - 35 */
71023 ** b-tree within a database file.
71033 ** found at self->pBt->mutex.
71041 ** SKIPNEXT sqlite3BtreeNext() is a no-op if skipNext>0 and
71042 ** sqlite3BtreePrevious() is no-op if skipNext<0.
71067 u8 curIntKey; /* Value of apPage[0]->intKey */
71069 u16 aiIdx[BTCURSOR_MAX_DEPTH-1]; /* Current index in apPage[i] */
71072 MemPage *apPage[BTCURSOR_MAX_DEPTH-1]; /* Stack of parents of current page */
71082 #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
71098 ** Cursor is valid except that the Cursor.skipNext field is non-zero
71100 ** operation should be a no-op.
71110 ** An unrecoverable error (an I/O error or a malloc failure) has occurred
71112 ** cursor. The error has left the cache in an inconsistent state.
71125 #define PENDING_BYTE_PAGE(pBt) ((Pgno)((PENDING_BYTE/((pBt)->pageSize))+1))
71128 ** These macros define the location of the pointer-map entry for a
71133 ** PTRMAP_PAGENO returns the database page number of the pointer-map
71137 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
71139 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
71143 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
71160 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
71163 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
71171 ** overflow pages. The page-number identifies the previous
71174 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
71187 assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
71188 assert( p->pBt->inTransaction>=p->inTrans );
71193 ** if the database supports auto-vacuum or not. Because it is used
71194 ** within an expression that is an argument to another macro
71199 #define ISAUTOVACUUM(pBt) (pBt->autoVacuum)
71210 ** the database. As the integrity-check proceeds, for each page used in
71211 ** the database the corresponding bit is set. This allows integrity-check to
71218 Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
71230 u32 *heap; /* Min-heap used for analyzing cell coverage */
71236 ** Routines to read or write a two- and four-byte big-endian integer values.
71245 ** two-byte aligned address. get2byteAligned() is only used for accessing the
71264 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
71266 ** p->locked boolean to true.
71269 assert( p->locked==0 );
71270 assert( sqlite3_mutex_notheld(p->pBt->mutex) );
71271 assert( sqlite3_mutex_held(p->db->mutex) );
71273 sqlite3_mutex_enter(p->pBt->mutex);
71274 p->pBt->db = p->db;
71275 p->locked = 1;
71279 ** Release the BtShared mutex associated with B-Tree handle p and
71280 ** clear the p->locked boolean.
71283 BtShared *pBt = p->pBt;
71284 assert( p->locked==1 );
71285 assert( sqlite3_mutex_held(pBt->mutex) );
71286 assert( sqlite3_mutex_held(p->db->mutex) );
71287 assert( p->db==pBt->db );
71289 sqlite3_mutex_leave(pBt->mutex);
71290 p->locked = 0;
71300 ** and this routine is a no-op. The underlying mutex is non-recursive.
71305 ** by all database connections. The p->pNext is a list of other
71308 ** p, then first unlock all of the others on p->pNext, then wait
71317 assert( p->pNext==0 || p->pNext->pBt>p->pBt );
71318 assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
71319 assert( p->pNext==0 || p->pNext->db==p->db );
71320 assert( p->pPrev==0 || p->pPrev->db==p->db );
71321 assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
71324 assert( !p->locked || p->wantToLock>0 );
71325 assert( p->sharable || p->wantToLock==0 );
71328 assert( sqlite3_mutex_held(p->db->mutex) );
71332 assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
71334 if( !p->sharable ) return;
71335 p->wantToLock++;
71336 if( p->locked ) return;
71353 if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
71354 p->pBt->db = p->db;
71355 p->locked = 1;
71364 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
71365 assert( pLater->sharable );
71366 assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
71367 assert( !pLater->locked || pLater->wantToLock>0 );
71368 if( pLater->locked ){
71373 for(pLater=p->pNext; pLater; pLater=pLater->pNext){
71374 if( pLater->wantToLock ){
71385 assert( sqlite3_mutex_held(p->db->mutex) );
71386 if( p->sharable ){
71387 assert( p->wantToLock>0 );
71388 p->wantToLock--;
71389 if( p->wantToLock==0 ){
71398 ** B-Tree is not marked as sharable.
71403 assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
71404 assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
71405 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
71406 assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
71408 return (p->sharable==0 || p->locked);
71420 ** There is a corresponding leave-all procedures.
71431 assert( sqlite3_mutex_held(db->mutex) );
71432 for(i=0; i<db->nDb; i++){
71433 p = db->aDb[i].pBt;
71434 if( p && p->sharable ){
71439 db->noSharedCache = skipOk;
71442 if( db->noSharedCache==0 ) btreeEnterAll(db);
71447 assert( sqlite3_mutex_held(db->mutex) );
71448 for(i=0; i<db->nDb; i++){
71449 p = db->aDb[i].pBt;
71454 if( db->noSharedCache==0 ) btreeLeaveAll(db);
71466 if( !sqlite3_mutex_held(db->mutex) ){
71469 for(i=0; i<db->nDb; i++){
71471 p = db->aDb[i].pBt;
71472 if( p && p->sharable &&
71473 (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
71484 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
71488 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
71496 if( db->pVfs==0 && db->nDb==0 ) return 1;
71498 assert( iDb>=0 && iDb<db->nDb );
71499 if( !sqlite3_mutex_held(db->mutex) ) return 0;
71501 p = db->aDb[iDb].pBt;
71503 return p->sharable==0 || p->locked==1;
71511 ** these two routines, all mutex operations are no-ops in that case and
71515 ** the ones below, are no-ops and are null #defines in btree.h.
71519 p->pBt->db = p->db;
71523 for(i=0; i<db->nDb; i++){
71524 Btree *p = db->aDb[i].pBt;
71526 p->pBt->db = p->db;
71541 sqlite3BtreeEnter(pCur->pBtree);
71545 sqlite3BtreeLeave(pCur->pBtree);
71565 ** This file implements an external (disk-based) database using BTrees.
71567 ** Including a description of file format and an overview of operation.
71589 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
71594 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
71597 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
71610 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
71655 ** shared-cache table level locks. If the library is compiled with the
71656 ** shared-cache feature disabled, then there is only ever one user
71658 ** So define the lock related functions as no-ops.
71673 u64 n = pBt->nSeek;
71674 pBt->nSeek = 0;
71681 ** (MemPage*) as an argument. The (MemPage*) must not be NULL.
71685 ** normally produced as a side-effect of SQLITE_CORRUPT_BKPT is augmented
71693 p->pgno, sqlite3PagerFilename(p->pBt->pPager, 0)
71704 # define SQLITE_CORRUPT_PAGE(pMemPage) SQLITE_CORRUPT_PGNO(pMemPage->pgno)
71707 /* Default value for SHARED_LOCK_TRACE macro if shared-cache is disabled
71711 #define SHARED_LOCK_TRACE(X,MSG,TAB,TYPE) /*no-op*/
71716 /* ^---- Change to 1 and recompile to enable shared-lock tracing
71719 ** Print all shared-cache locks on a BtShared. Debugging use only.
71729 printf("%s-%p %u%s:", zMsg, pBt, iRoot, eLockType==READ_LOCK?"R":"W");
71731 printf("%s-%p:", zMsg, pBt);
71733 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
71734 printf(" %p/%u%s", pLock->pBtree, pLock->iTable,
71735 pLock->eLock==READ_LOCK ? "R" : "W");
71736 while( pLock->pNext && pLock->pBtree==pLock->pNext->pBtree ){
71737 pLock = pLock->pNext;
71738 printf(",%u%s", pLock->iTable, pLock->eLock==READ_LOCK ? "R" : "W");
71746 #endif /* Shared-lock tracing */
71750 **** This function is only used as part of an assert() statement. ***
71755 ** For example, when writing to a table with root-page iRoot via
71760 ** When writing to an index that resides in a sharable database, the
71768 ** hold a write-lock on the schema table (root page 1). This is also
71773 Pgno iRoot, /* Root page of b-tree */
71774 int isIndex, /* True if iRoot is the root of an index b-tree */
71777 Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
71782 ** and has the read-uncommitted flag set, then no lock is required.
71785 if( (pBtree->sharable==0)
71786 || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommit))
71791 /* If the client is reading or writing an index and the schema is
71793 ** the correct locks are held. So do not bother - just return true.
71796 if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
71800 /* Figure out the root-page that the lock should be held on. For table
71801 ** b-trees, this is just the root page of the b-tree being read or
71802 ** written. For index b-trees, it is the root page of the associated
71807 for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
71809 if( pIdx->tnum==iRoot ){
71816 iTab = pIdx->pTable->tnum;
71824 SHARED_LOCK_TRACE(pBtree->pBt,"hasLock",iRoot,eLockType);
71826 /* Search for the required lock. Either a write-lock on root-page iTab, a
71827 ** write-lock on the schema table, or (if the client is reading) a
71828 ** read-lock on iTab will suffice. Return 1 if any of these are found. */
71829 for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
71830 if( pLock->pBtree==pBtree
71831 && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
71832 && pLock->eLock>=eLockType
71854 ** read-uncommitted flag set, then it is OK for the other object to
71864 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
71865 if( p->pgnoRoot==iRoot
71866 && p->pBtree!=pBtree
71867 && 0==(p->pBtree->db->flags & SQLITE_ReadUncommit)
71878 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
71883 BtShared *pBt = p->pBt;
71888 assert( p->db!=0 );
71889 assert( !(p->db->flags&SQLITE_ReadUncommit)||eLock==WRITE_LOCK||iTab==1 );
71891 /* If requesting a write-lock, then the Btree must have an open write
71893 ** must be an open write transaction on the file itself.
71895 assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
71896 assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
71898 /* This routine is a no-op if the shared-cache is not enabled */
71899 if( !p->sharable ){
71903 /* If some other connection is holding an exclusive lock, the
71906 if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
71907 sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
71911 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
71912 /* The condition (pIter->eLock!=eLock) in the following if(...)
71915 ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
71921 assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
71922 assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
71923 if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
71924 sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
71926 assert( p==pBt->pWriter );
71927 pBt->btsFlags |= BTS_PENDING;
71938 ** Add a lock on the table with root-page iTable to the shared-btree used
71955 BtShared *pBt = p->pBt;
71963 assert( p->db!=0 );
71965 /* A connection with the read-uncommitted flag set will never try to
71966 ** obtain a read-lock using this function. The only read-lock obtained
71967 ** by a connection in read-uncommitted mode is on the sqlite_schema
71969 assert( 0==(p->db->flags&SQLITE_ReadUncommit) || eLock==WRITE_LOCK );
71971 /* This function should only be called on a sharable b-tree after it
71972 ** has been determined that no other b-tree holds a conflicting lock. */
71973 assert( p->sharable );
71976 /* First search the list for an existing lock on this table. */
71977 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
71978 if( pIter->iTable==iTable && pIter->pBtree==p ){
71992 pLock->iTable = iTable;
71993 pLock->pBtree = p;
71994 pLock->pNext = pBt->pLock;
71995 pBt->pLock = pLock;
71999 ** and the requested lock. This means if a write-lock was already held
72000 ** and a read-lock requested, we don't incorrectly downgrade the lock.
72003 if( eLock>pLock->eLock ){
72004 pLock->eLock = eLock;
72016 ** This function assumes that Btree p has an open read or write
72021 BtShared *pBt = p->pBt;
72022 BtLock **ppIter = &pBt->pLock;
72025 assert( p->sharable || 0==*ppIter );
72026 assert( p->inTrans>0 );
72032 assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
72033 assert( pLock->pBtree->inTrans>=pLock->eLock );
72034 if( pLock->pBtree==p ){
72035 *ppIter = pLock->pNext;
72036 assert( pLock->iTable!=1 || pLock==&p->lock );
72037 if( pLock->iTable!=1 ){
72041 ppIter = &pLock->pNext;
72045 assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
72046 if( pBt->pWriter==p ){
72047 pBt->pWriter = 0;
72048 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
72049 }else if( pBt->nTransaction==2 ){
72059 pBt->btsFlags &= ~BTS_PENDING;
72064 ** This function changes all write-locks held by Btree p into read-locks.
72067 BtShared *pBt = p->pBt;
72071 if( pBt->pWriter==p ){
72073 pBt->pWriter = 0;
72074 pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
72075 for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
72076 assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
72077 pLock->eLock = READ_LOCK;
72095 return sqlite3_mutex_held(p->pBt->mutex);
72099 ** database connetion. This is important in shared-cache mode. If the database
72100 ** connection pointers get out-of-sync, it is possible for routines like
72101 ** btreeInitPage() to reference an stale connection pointer that references a
72103 ** statements only and for the purpose of double-checking that the btree code
72104 ** does keep the database connection pointers up-to-date.
72108 return (p->pBtree->db==p->pBt->db);
72116 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
72119 ** Invalidate the overflow page-list cache for all cursors opened
72124 assert( sqlite3_mutex_held(pBt->mutex) );
72125 for(p=pBt->pCursor; p; p=p->pNext){
72138 ** cursors open on any row within the table with root-page pgnoRoot.
72151 assert( pBtree->hasIncrblobCur );
72153 pBtree->hasIncrblobCur = 0;
72154 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
72155 if( (p->curFlags & BTCF_Incrblob)!=0 ){
72156 pBtree->hasIncrblobCur = 1;
72157 if( p->pgnoRoot==pgnoRoot && (isClearTable || p->info.nKey==iRow) ){
72158 p->eState = CURSOR_INVALID;
72171 ** when a page that previously contained data becomes a free-list leaf
72174 ** The BtShared.pHasContent bitvec exists to work around an obscure
72176 ** free-list leaf pages:
72179 ** a free-list leaf page, the page is not written to the database
72180 ** (as free-list leaf pages contain no meaningful data). Sometimes
72184 ** 2) When a free-list leaf page is reused, its content is not read
72190 ** a page is moved to the free-list and then reused within the same
72192 ** it is moved to the free-list and it is also not journalled when it
72193 ** is extracted from the free-list and reused, then the original data
72198 ** moved to become a free-list leaf page, the corresponding bit is
72199 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
72206 if( !pBt->pHasContent ){
72207 assert( pgno<=pBt->nPage );
72208 pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
72209 if( !pBt->pHasContent ){
72213 if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
72214 rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
72222 ** This function is called when a free-list leaf page is removed from the
72223 ** free-list for reuse. It returns false if it is safe to retrieve the
72224 ** page from the pager layer with the 'no-content' flag set. True otherwise.
72227 Bitvec *p = pBt->pHasContent;
72233 ** invoked at the conclusion of each write-transaction.
72236 sqlite3BitvecDestroy(pBt->pHasContent);
72237 pBt->pHasContent = 0;
72245 if( pCur->iPage>=0 ){
72246 for(i=0; i<pCur->iPage; i++){
72247 releasePageNotNull(pCur->apPage[i]);
72249 releasePageNotNull(pCur->pPage);
72250 pCur->iPage = -1;
72257 ** function saves the current cursor key in variables pCur->nKey and
72258 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
72261 ** If the cursor is open on an intkey table, then the integer key
72262 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
72263 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
72264 ** set to point to a malloced buffer pCur->nKey bytes in size containing
72269 assert( CURSOR_VALID==pCur->eState );
72270 assert( 0==pCur->pKey );
72273 if( pCur->curIntKey ){
72275 pCur->nKey = sqlite3BtreeIntegerKey(pCur);
72277 /* For an index btree, save the complete key content. It is possible
72280 ** up to the size of 1 varint plus 1 8-byte value when the cursor
72284 pCur->nKey = sqlite3BtreePayloadSize(pCur);
72285 pKey = sqlite3Malloc( ((i64)pCur->nKey) + 9 + 8 );
72287 rc = sqlite3BtreePayload(pCur, 0, (int)pCur->nKey, pKey);
72289 memset(((u8*)pKey)+pCur->nKey, 0, 9+8);
72290 pCur->pKey = pKey;
72298 assert( !pCur->curIntKey || !pCur->pKey );
72312 assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
72313 assert( 0==pCur->pKey );
72316 if( pCur->curFlags & BTCF_Pinned ){
72319 if( pCur->eState==CURSOR_SKIPNEXT ){
72320 pCur->eState = CURSOR_VALID;
72322 pCur->skipNext = 0;
72328 pCur->eState = CURSOR_REQUIRESEEK;
72331 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl|BTCF_AtLast);
72340 ** the table with root-page iRoot. "Saving the cursor position" means that
72351 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
72361 assert( sqlite3_mutex_held(pBt->mutex) );
72362 assert( pExcept==0 || pExcept->pBt==pBt );
72363 for(p=pBt->pCursor; p; p=p->pNext){
72364 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
72367 if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
72382 if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
72383 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
72389 testcase( p->iPage>=0 );
72393 p = p->pNext;
72403 sqlite3_free(pCur->pKey);
72404 pCur->pKey = 0;
72405 pCur->eState = CURSOR_INVALID;
72415 const void *pKey, /* Packed key if the btree is an index */
72424 KeyInfo *pKeyInfo = pCur->pKeyInfo;
72429 if( pIdxKey->nField==0 || pIdxKey->nField>pKeyInfo->nAllField ){
72434 sqlite3DbFree(pCur->pKeyInfo->db, pIdxKey);
72453 assert( pCur->eState>=CURSOR_REQUIRESEEK );
72454 if( pCur->eState==CURSOR_FAULT ){
72455 return pCur->skipNext;
72457 pCur->eState = CURSOR_INVALID;
72461 rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
72464 sqlite3_free(pCur->pKey);
72465 pCur->pKey = 0;
72466 assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
72467 if( skipNext ) pCur->skipNext = skipNext;
72468 if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
72469 pCur->eState = CURSOR_SKIPNEXT;
72476 (p->eState>=CURSOR_REQUIRESEEK ? \
72496 assert( sizeof(pCur->eState)==1 );
72528 assert( pCur->eState!=CURSOR_VALID );
72534 if( pCur->eState!=CURSOR_VALID ){
72575 pCur->hints = (u8)x;
72582 ** number for the pointer-map page that contains the entry for the
72592 assert( sqlite3_mutex_held(pBt->mutex) );
72594 nPagesPerMapPage = (pBt->usableSize/5)+1;
72595 iPtrMap = (pgno-2)/nPagesPerMapPage;
72604 ** Write an entry into the pointer map.
72609 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
72610 ** a no-op. If an error occurs, the appropriate error code is written
72622 assert( sqlite3_mutex_held(pBt->mutex) );
72623 /* The super-journal page number must never be used as a pointer map page */
72626 assert( pBt->autoVacuum );
72632 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
72649 assert( offset <= (int)pBt->usableSize-5 );
72653 TRACE(("PTRMAP_UPDATE: %u->(%u,%u)\n", key, eType, parent));
72666 ** Read an entry from the pointer map.
72670 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
72679 assert( sqlite3_mutex_held(pBt->mutex) );
72682 rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
72693 assert( offset <= (int)pBt->usableSize-5 );
72715 ** 4-byte child pointer found on interior pages, if there is one.
72720 ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
72722 ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
72728 ** on a single B-tree page. Make necessary adjustments to the CellInfo
72743 ** way will result in an incompatible file format.
72749 minLocal = pPage->minLocal;
72750 maxLocal = pPage->maxLocal;
72751 surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
72755 pInfo->nLocal = (u16)surplus;
72757 pInfo->nLocal = (u16)minLocal;
72759 pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
72768 maxLocal = pPage->maxLocal;
72775 minLocal = pPage->minLocal;
72776 surplus = (int)(minLocal +(nPayload - minLocal)%(pPage->pBt->usableSize-4));
72800 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72801 assert( pPage->leaf==0 );
72802 assert( pPage->childPtrSize==4 );
72806 pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
72807 pInfo->nPayload = 0;
72808 pInfo->nLocal = 0;
72809 pInfo->pPayload = 0;
72821 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72822 assert( pPage->leaf==0 || pPage->leaf==1 );
72823 assert( pPage->intKeyLeaf );
72824 assert( pPage->childPtrSize==0 );
72845 ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
72848 ** This routine is a high-runner.
72882 pInfo->nKey = *(i64*)&iKey;
72883 pInfo->nPayload = nPayload;
72884 pInfo->pPayload = pIter;
72885 testcase( nPayload==pPage->maxLocal );
72886 testcase( nPayload==(u32)pPage->maxLocal+1 );
72888 assert( pPage->maxLocal <= BT_MAX_LOCAL );
72889 if( nPayload<=pPage->maxLocal ){
72893 pInfo->nSize = (u16)nPayload + (u16)(pIter - pCell);
72894 if( pInfo->nSize<4 ) pInfo->nSize = 4;
72895 pInfo->nLocal = (u16)nPayload;
72908 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
72909 assert( pPage->leaf==0 || pPage->leaf==1 );
72910 assert( pPage->intKeyLeaf==0 );
72911 pIter = pCell + pPage->childPtrSize;
72921 pInfo->nKey = nPayload;
72922 pInfo->nPayload = nPayload;
72923 pInfo->pPayload = pIter;
72924 testcase( nPayload==pPage->maxLocal );
72925 testcase( nPayload==(u32)pPage->maxLocal+1 );
72927 assert( pPage->maxLocal <= BT_MAX_LOCAL );
72928 if( nPayload<=pPage->maxLocal ){
72932 pInfo->nSize = (u16)nPayload + (u16)(pIter - pCell);
72933 if( pInfo->nSize<4 ) pInfo->nSize = 4;
72934 pInfo->nLocal = (u16)nPayload;
72944 pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
72952 ** data area of the btree-page. The return number includes the cell
72969 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
72972 pPage->xParseCell(pPage, pCell, &debuginfo);
72975 assert( pPage->childPtrSize==4 );
72985 testcase( nSize==pPage->maxLocal );
72986 testcase( nSize==(u32)pPage->maxLocal+1 );
72987 if( nSize<=pPage->maxLocal ){
72988 nSize += (u32)(pIter - pCell);
72991 int minLocal = pPage->minLocal;
72992 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
72993 testcase( nSize==pPage->maxLocal );
72994 testcase( nSize==(u32)pPage->maxLocal+1 );
72995 if( nSize>pPage->maxLocal ){
72998 nSize += 4 + (u16)(pIter - pCell);
73011 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
73014 pPage->xParseCell(pPage, pCell, &debuginfo);
73017 assert( pPage->childPtrSize==0 );
73027 testcase( nSize==pPage->maxLocal );
73028 testcase( nSize==(u32)pPage->maxLocal+1 );
73029 if( nSize<=pPage->maxLocal ){
73030 nSize += (u32)(pIter - pCell);
73033 int minLocal = pPage->minLocal;
73034 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
73035 testcase( nSize==pPage->maxLocal );
73036 testcase( nSize==(u32)pPage->maxLocal+1 );
73037 if( nSize>pPage->maxLocal ){
73040 nSize += 4 + (u16)(pIter - pCell);
73052 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
73055 pPage->xParseCell(pPage, pCell, &debuginfo);
73060 assert( pPage->childPtrSize==4 );
73063 assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
73064 return (u16)(pIter - pCell);
73074 ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
73077 pPage->xParseCell(pPage, pCell, &debuginfo);
73089 /* pIter now points at the 64-bit integer key value, a variable length
73100 testcase( nSize==pPage->maxLocal );
73101 testcase( nSize==(u32)pPage->maxLocal+1 );
73102 if( nSize<=pPage->maxLocal ){
73103 nSize += (u32)(pIter - pCell);
73106 int minLocal = pPage->minLocal;
73107 nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
73108 testcase( nSize==pPage->maxLocal );
73109 testcase( nSize==(u32)pPage->maxLocal+1 );
73110 if( nSize>pPage->maxLocal ){
73113 nSize += 4 + (u16)(pIter - pCell);
73124 return pPage->xCellSize(pPage, findCell(pPage, iCell));
73132 ** pointer to an overflow page, insert an entry into the pointer-map for
73139 pPage->xParseCell(pPage, pCell, &info);
73142 if( SQLITE_OVERFLOW(pSrc->aDataEnd, pCell, pCell+info.nLocal) ){
73147 ovfl = get4byte(&pCell[info.nSize-4]);
73148 ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
73156 ** page so that there are no free-blocks on the free-block list.
73161 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
73162 ** b-tree page so that there are no freeblocks or fragment bytes, all
73168 int pc; /* Address of the i-th cell */
73182 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
73183 assert( pPage->pBt!=0 );
73184 assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
73185 assert( pPage->nOverflow==0 );
73186 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
73187 data = pPage->aData;
73188 hdr = pPage->hdrOffset;
73189 cellOffset = pPage->cellOffset;
73190 nCell = pPage->nCell;
73193 usableSize = pPage->pBt->usableSize;
73198 ** offsets to each pointer in the cell-pointer array than it is to
73202 if( iFree>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
73205 if( iFree2>usableSize-4 ) return SQLITE_CORRUPT_PAGE(pPage);
73219 memmove(&data[iFree+sz+sz2], &data[iFree+sz], iFree2-(iFree+sz));
73226 assert( cbrk+(iFree-top) <= usableSize );
73227 memmove(&data[cbrk], &data[top], iFree-top);
73239 iCellLast = usableSize - 4;
73242 temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
73246 u8 *pAddr; /* The i-th cell pointer */
73258 size = pPage->xCellSize(pPage, &src[pc]);
73259 cbrk -= size;
73273 assert( pPage->nFree>=0 );
73274 if( data[hdr+7]+cbrk-iCellFirst!=pPage->nFree ){
73281 memset(&data[iCellFirst], 0, cbrk-iCellFirst);
73282 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
73287 ** Search the free-list on page pPg for space to store a cell nByte bytes in
73289 ** from the free-list.
73291 ** If no suitable space can be found on the free-list, return NULL.
73301 const int hdr = pPg->hdrOffset; /* Offset to page header */
73302 u8 * const aData = pPg->aData; /* Page data */
73307 int maxPC = pPg->pBt->usableSize - nByte; /* Max address for a usable slot */
73312 /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
73313 ** freeblock form a big-endian integer which is the size of the freeblock
73314 ** in bytes, including the 4-byte header. */
73317 if( (x = size - nByte)>=0 ){
73321 /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
73325 /* Remove the slot from the free-list. Update the number of
73335 /* The slot remains on the free-list. Reduce its size to account
73352 if( pc>maxPC+nByte-4 ){
73360 ** Allocate nByte bytes of space from within the B-Tree page passed
73361 ** as the first argument. Write into *pIdx the index into pPage->aData[]
73363 ** an error code (usually SQLITE_CORRUPT).
73373 const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
73374 u8 * const data = pPage->aData; /* Local cache of pPage->aData */
73380 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
73381 assert( pPage->pBt );
73382 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
73384 assert( pPage->nFree>=nByte );
73385 assert( pPage->nOverflow==0 );
73386 assert( nByte < (int)(pPage->pBt->usableSize-8) );
73388 assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
73389 gap = pPage->cellOffset + 2*pPage->nCell;
73391 /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
73393 ** then the cell content offset of an empty page wants to be 65536.
73394 ** However, that integer is too large to be stored in a 2-byte unsigned
73399 if( top==0 && pPage->pBt->usableSize==65536 ){
73404 }else if( top>(int)pPage->pBt->usableSize ){
73419 assert( pSpace+nByte<=data+pPage->pBt->usableSize );
73420 *pIdx = g2 = (int)(pSpace-data);
73436 assert( pPage->nCell>0 || CORRUPT_DB );
73437 assert( pPage->nFree>=0 );
73438 rc = defragmentPage(pPage, MIN(4, pPage->nFree - (2+nByte)));
73451 top -= nByte;
73453 assert( top+nByte <= (int)pPage->pBt->usableSize );
73459 ** Return a section of the pPage->aData to the freelist.
73460 ** The first byte of the new free block is pPage->aData[iStart]
73479 unsigned char *data = pPage->aData; /* Page content */
73482 assert( pPage->pBt!=0 );
73483 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
73484 assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
73485 assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
73486 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
73488 assert( CORRUPT_DB || iStart<=pPage->pBt->usableSize-4 );
73493 hdr = pPage->hdrOffset;
73505 if( iFreeBlk>(int)pPage->pBt->usableSize-4 ){ /* TH3: corrupt081.100 */
73517 nFrag = iFreeBlk - iEnd;
73520 if( iEnd > (int)pPage->pBt->usableSize ){
73523 iSize = iEnd - iStart;
73535 nFrag += iStart - iPtrEnd;
73536 iSize = iEnd - iPtr;
73541 data[hdr+7] -= (u8)nFrag;
73545 if( pPage->pBt->btsFlags & BTS_FAST_SECURE ){
73565 pPage->nFree += iOrigSize;
73582 BtShared *pBt; /* A copy of pPage->pBt */
73584 assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
73585 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
73586 pBt = pPage->pBt;
73587 pPage->max1bytePayload = pBt->max1bytePayload;
73589 pPage->childPtrSize = 0;
73590 pPage->leaf = 1;
73592 pPage->intKeyLeaf = 1;
73593 pPage->xCellSize = cellSizePtrTableLeaf;
73594 pPage->xParseCell = btreeParseCellPtr;
73595 pPage->intKey = 1;
73596 pPage->maxLocal = pBt->maxLeaf;
73597 pPage->minLocal = pBt->minLeaf;
73599 pPage->intKey = 0;
73600 pPage->intKeyLeaf = 0;
73601 pPage->xCellSize = cellSizePtrIdxLeaf;
73602 pPage->xParseCell = btreeParseCellPtrIndex;
73603 pPage->maxLocal = pBt->maxLocal;
73604 pPage->minLocal = pBt->minLocal;
73606 pPage->intKey = 0;
73607 pPage->intKeyLeaf = 0;
73608 pPage->xCellSize = cellSizePtrIdxLeaf;
73609 pPage->xParseCell = btreeParseCellPtrIndex;
73613 pPage->childPtrSize = 4;
73614 pPage->leaf = 0;
73616 pPage->intKey = 0;
73617 pPage->intKeyLeaf = 0;
73618 pPage->xCellSize = cellSizePtr;
73619 pPage->xParseCell = btreeParseCellPtrIndex;
73620 pPage->maxLocal = pBt->maxLocal;
73621 pPage->minLocal = pBt->minLocal;
73623 pPage->intKeyLeaf = 0;
73624 pPage->xCellSize = cellSizePtrNoPayload;
73625 pPage->xParseCell = btreeParseCellPtrNoPayload;
73626 pPage->intKey = 1;
73627 pPage->maxLocal = pBt->maxLeaf;
73628 pPage->minLocal = pBt->minLeaf;
73630 pPage->intKey = 0;
73631 pPage->intKeyLeaf = 0;
73632 pPage->xCellSize = cellSizePtr;
73633 pPage->xParseCell = btreeParseCellPtrIndex;
73642 ** in the pPage->nFree field.
73645 int pc; /* Address of a freeblock within pPage->aData[] */
73647 u8 *data; /* Equal to pPage->aData */
73654 assert( pPage->pBt!=0 );
73655 assert( pPage->pBt->db!=0 );
73656 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
73657 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
73658 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
73659 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
73660 assert( pPage->isInit==1 );
73661 assert( pPage->nFree<0 );
73663 usableSize = pPage->pBt->usableSize;
73664 hdr = pPage->hdrOffset;
73665 data = pPage->aData;
73666 /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
73670 iCellFirst = hdr + 8 + pPage->childPtrSize + 2*pPage->nCell;
73671 iCellLast = usableSize - 4;
73674 ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
73678 nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
73682 /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
73709 ** of the cell-content area plus the number of free bytes within
73710 ** the cell-content area. If this is greater than the usable-size
73712 ** serves to verify that the offset to the start of the cell-content
73718 pPage->nFree = (u16)(nFree - iCellFirst);
73731 int pc; /* Address of a freeblock within pPage->aData[] */
73732 u8 *data; /* Equal to pPage->aData */
73736 iCellFirst = pPage->cellOffset + 2*pPage->nCell;
73737 usableSize = pPage->pBt->usableSize;
73738 iCellLast = usableSize - 4;
73739 data = pPage->aData;
73740 cellOffset = pPage->cellOffset;
73741 if( !pPage->leaf ) iCellLast--;
73742 for(i=0; i<pPage->nCell; i++){
73749 sz = pPage->xCellSize(pPage, &data[pc]);
73762 ** not contain a well-formed database page, then return
73764 ** guarantee that the page is well-formed. It only shows that
73768 u8 *data; /* Equal to pPage->aData */
73771 assert( pPage->pBt!=0 );
73772 assert( pPage->pBt->db!=0 );
73773 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
73774 assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
73775 assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
73776 assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
73777 assert( pPage->isInit==0 );
73779 pBt = pPage->pBt;
73780 data = pPage->aData + pPage->hdrOffset;
73781 /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
73782 ** the b-tree page type. */
73786 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
73787 pPage->maskPage = (u16)(pBt->pageSize - 1);
73788 pPage->nOverflow = 0;
73789 pPage->cellOffset = (u16)(pPage->hdrOffset + 8 + pPage->childPtrSize);
73790 pPage->aCellIdx = data + pPage->childPtrSize + 8;
73791 pPage->aDataEnd = pPage->aData + pBt->pageSize;
73792 pPage->aDataOfst = pPage->aData + pPage->childPtrSize;
73793 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
73795 pPage->nCell = get2byte(&data[3]);
73796 if( pPage->nCell>MX_CELL(pBt) ){
73800 testcase( pPage->nCell==MX_CELL(pBt) );
73801 /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
73805 assert( pPage->nCell>0
73806 || get2byteNotZero(&data[5])==(int)pBt->usableSize
73808 pPage->nFree = -1; /* Indicate that this value is yet uncomputed */
73809 pPage->isInit = 1;
73810 if( pBt->db->flags & SQLITE_CellSizeCk ){
73821 unsigned char *data = pPage->aData;
73822 BtShared *pBt = pPage->pBt;
73823 int hdr = pPage->hdrOffset;
73826 assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno || CORRUPT_DB );
73827 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
73828 assert( sqlite3PagerGetData(pPage->pDbPage) == data );
73829 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
73830 assert( sqlite3_mutex_held(pBt->mutex) );
73831 if( pBt->btsFlags & BTS_FAST_SECURE ){
73832 memset(&data[hdr], 0, pBt->usableSize - hdr);
73838 put2byte(&data[hdr+5], pBt->usableSize);
73839 pPage->nFree = (u16)(pBt->usableSize - first);
73841 pPage->cellOffset = (u16)first;
73842 pPage->aDataEnd = &data[pBt->pageSize];
73843 pPage->aCellIdx = &data[first];
73844 pPage->aDataOfst = &data[pPage->childPtrSize];
73845 pPage->nOverflow = 0;
73846 assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
73847 pPage->maskPage = (u16)(pBt->pageSize - 1);
73848 pPage->nCell = 0;
73849 pPage->isInit = 1;
73859 if( pgno!=pPage->pgno ){
73860 pPage->aData = sqlite3PagerGetData(pDbPage);
73861 pPage->pDbPage = pDbPage;
73862 pPage->pBt = pBt;
73863 pPage->pgno = pgno;
73864 pPage->hdrOffset = pgno==1 ? 100 : 0;
73866 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
73891 assert( sqlite3_mutex_held(pBt->mutex) );
73892 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
73905 assert( sqlite3_mutex_held(pBt->mutex) );
73906 pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
73915 ** error, return ((unsigned int)-1).
73918 return pBt->nPage;
73922 return btreePagecount(p->pBt);
73932 int bReadOnly /* True for a read-only page */
73937 assert( sqlite3_mutex_held(pBt->mutex) );
73943 rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
73949 if( pPage->isInit==0 ){
73958 assert( pPage->pgno==pgno || CORRUPT_DB );
73959 assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
73971 assert( pPage->aData );
73972 assert( pPage->pBt );
73973 assert( pPage->pDbPage!=0 );
73974 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
73975 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
73976 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
73977 sqlite3PagerUnrefNotNull(pPage->pDbPage);
73984 assert( pPage->aData );
73985 assert( pPage->pBt );
73986 assert( pPage->pDbPage!=0 );
73987 assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
73988 assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
73989 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
73990 sqlite3PagerUnrefPageOne(pPage->pDbPage);
73994 ** Get an unused page.
73999 ** release it and return an SQLITE_CURRUPT error.
74010 if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
74015 (*ppPage)->isInit = 0;
74035 if( pPage->isInit ){
74036 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
74037 pPage->isInit = 0;
74039 /* pPage might not be a btree page; it might be an overflow page
74044 ** the call for every page that comes in for re-initializing. */
74055 assert( pBt->db );
74056 assert( sqlite3_mutex_held(pBt->db->mutex) );
74057 return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
74064 ** then an ephemeral database is created. The ephemeral database might
74065 ** be exclusively in memory, or it might use a disk-based memory cache.
74069 ** If zFilename is ":memory:" then an in-memory database is created
74076 ** and we are in shared cache mode, then the open will fail with an
74082 sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
74096 /* True if opening an ephemeral, temporary database */
74099 /* Set the variable isMemdb to true for an in-memory database, or
74100 ** false for a file-based database.
74112 assert( sqlite3_mutex_held(db->mutex) );
74131 p->inTrans = TRANS_NONE;
74132 p->db = db;
74134 p->lock.pBtree = p;
74135 p->lock.iTable = 1;
74140 ** If this Btree is a candidate for shared cache, try to find an
74146 int nFullPathname = pVfs->mxPathname+1;
74150 p->sharable = 1;
74176 for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
74177 assert( pBt->nRef>0 );
74178 if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
74179 && sqlite3PagerVfs(pBt->pPager)==pVfs ){
74181 for(iDb=db->nDb-1; iDb>=0; iDb--){
74182 Btree *pExisting = db->aDb[iDb].pBt;
74183 if( pExisting && pExisting->pBt==pBt ){
74191 p->pBt = pBt;
74192 pBt->nRef++;
74206 p->sharable = 1;
74223 /* Suppress false-positive compiler warning from PVS-Studio */
74231 rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
74234 sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
74235 rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
74240 pBt->openFlags = (u8)flags;
74241 pBt->db = db;
74242 sqlite3PagerSetBusyHandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
74243 p->pBt = pBt;
74245 pBt->pCursor = 0;
74246 pBt->pPage1 = 0;
74247 if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
74249 pBt->btsFlags |= BTS_SECURE_DELETE;
74251 pBt->btsFlags |= BTS_OVERWRITE;
74253 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
74254 ** determined by the 2-byte integer located at an offset of 16 bytes from
74256 pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
74257 if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
74258 || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
74259 pBt->pageSize = 0;
74261 /* If the magic name ":memory:" will create an in-memory database, then
74262 ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
74265 ** regular file-name. In this case the auto-vacuum applies as per normal.
74268 pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
74269 pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
74274 /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
74275 ** determined by the one-byte unsigned integer found at an offset of 20
74278 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
74280 pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
74281 pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
74284 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
74286 pBt->usableSize = pBt->pageSize - nReserve;
74287 assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
74292 pBt->nRef = 1;
74293 if( p->sharable ){
74297 pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
74298 if( pBt->mutex==0 ){
74304 pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
74316 if( p->sharable ){
74319 for(i=0; i<db->nDb; i++){
74320 if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
74321 while( pSib->pPrev ){ pSib = pSib->pPrev; }
74322 if( (uptr)p->pBt<(uptr)pSib->pBt ){
74323 p->pNext = pSib;
74324 p->pPrev = 0;
74325 pSib->pPrev = p;
74327 while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
74328 pSib = pSib->pNext;
74330 p->pNext = pSib->pNext;
74331 p->pPrev = pSib;
74332 if( p->pNext ){
74333 p->pNext->pPrev = p;
74335 pSib->pNext = p;
74346 if( pBt && pBt->pPager ){
74347 sqlite3PagerClose(pBt->pPager, 0);
74355 /* If the B-Tree was successfully opened, set the pager-cache size to the
74356 ** default value. Except, when opening on an existing shared pager-cache,
74357 ** do not change the pager-cache size.
74363 pFile = sqlite3PagerFile(pBt->pPager);
74364 if( pFile->pMethods ){
74365 sqlite3OsFileControlHint(pFile, SQLITE_FCNTL_PDB, (void*)&pBt->db);
74388 assert( sqlite3_mutex_notheld(pBt->mutex) );
74391 pBt->nRef--;
74392 if( pBt->nRef<=0 ){
74394 GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
74397 while( ALWAYS(pList) && pList->pNext!=pBt ){
74398 pList=pList->pNext;
74401 pList->pNext = pBt->pNext;
74405 sqlite3_mutex_free(pBt->mutex);
74417 ** Make sure pBt->pTmpSpace points to an allocation of
74418 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
74423 assert( pBt->pTmpSpace==0 );
74426 assert( pBt->pCursor!=0 && (pBt->pCursor->curFlags & BTCF_WriteFlag)!=0 );
74427 pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
74428 if( pBt->pTmpSpace==0 ){
74429 BtCursor *pCur = pBt->pCursor;
74430 pBt->pCursor = pCur->pNext; /* Unlink the cursor */
74435 /* One of the uses of pBt->pTmpSpace is to format cells before
74447 ** beginning of pTmpSpace as an area available to prepend the
74448 ** left-child pointer to the beginning of a cell.
74450 memset(pBt->pTmpSpace, 0, 8);
74451 pBt->pTmpSpace += 4;
74456 ** Free the pBt->pTmpSpace allocation
74459 if( pBt->pTmpSpace ){
74460 pBt->pTmpSpace -= 4;
74461 sqlite3PageFree(pBt->pTmpSpace);
74462 pBt->pTmpSpace = 0;
74467 ** Close an open database and invalidate all cursors.
74470 BtShared *pBt = p->pBt;
74473 assert( sqlite3_mutex_held(p->db->mutex) );
74479 BtCursor *pCur = pBt->pCursor;
74482 pCur = pCur->pNext;
74483 assert( pTmp->pBtree!=p );
74490 ** The call to sqlite3BtreeRollback() drops any table-locks held by
74496 /* If there are still other outstanding references to the shared-btree
74498 ** up the shared-btree.
74500 assert( p->wantToLock==0 && p->locked==0 );
74501 if( !p->sharable || removeFromSharingList(pBt) ){
74507 assert( !pBt->pCursor );
74508 sqlite3PagerClose(pBt->pPager, p->db);
74509 if( pBt->xFreeSchema && pBt->pSchema ){
74510 pBt->xFreeSchema(pBt->pSchema);
74512 sqlite3DbFree(0, pBt->pSchema);
74518 assert( p->wantToLock==0 );
74519 assert( p->locked==0 );
74520 if( p->pPrev ) p->pPrev->pNext = p->pNext;
74521 if( p->pNext ) p->pNext->pPrev = p->pPrev;
74536 BtShared *pBt = p->pBt;
74537 assert( sqlite3_mutex_held(p->db->mutex) );
74539 sqlite3PagerSetCachesize(pBt->pPager, mxPage);
74551 ** as an argument, no changes are made to the spill size setting, so
74555 BtShared *pBt = p->pBt;
74557 assert( sqlite3_mutex_held(p->db->mutex) );
74559 res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
74570 BtShared *pBt = p->pBt;
74571 assert( sqlite3_mutex_held(p->db->mutex) );
74573 sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
74584 ** is a very low but non-zero probability of damage. Level 3 reduces the
74592 BtShared *pBt = p->pBt;
74593 assert( sqlite3_mutex_held(p->db->mutex) );
74595 sqlite3PagerSetFlags(pBt->pPager, pgFlags);
74624 BtShared *pBt = p->pBt;
74627 pBt->nReserveWanted = (u8)nReserve;
74628 x = pBt->pageSize - pBt->usableSize;
74630 if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
74636 ((pageSize-1)&pageSize)==0 ){
74638 assert( !pBt->pCursor );
74640 pBt->pageSize = (u32)pageSize;
74643 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
74644 pBt->usableSize = pBt->pageSize - (u16)nReserve;
74645 if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
74654 return p->pBt->pageSize;
74659 ** may only be called if it is guaranteed that the b-tree mutex is already
74663 ** known that the shared b-tree mutex is held, but the mutex on the
74670 assert( sqlite3_mutex_held(p->pBt->mutex) );
74671 n = p->pBt->pageSize - p->pBt->usableSize;
74682 ** The amount of reserve can only grow - never shrink.
74687 n1 = (int)p->pBt->nReserveWanted;
74702 n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
74713 ** newFlag==(-1) No changes
74718 ** freelist leaf pages are not written back to the database. Thus in-page
74732 p->pBt->btsFlags &= ~BTS_FAST_SECURE;
74733 p->pBt->btsFlags |= (u16)(BTS_SECURE_DELETE*newFlag);
74735 b = (p->pBt->btsFlags & BTS_FAST_SECURE)/BTS_SECURE_DELETE;
74741 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
74742 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
74743 ** is disabled. The default value for the auto-vacuum property is
74750 BtShared *pBt = p->pBt;
74755 if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
74758 pBt->autoVacuum = av ?1:0;
74759 pBt->incrVacuum = av==2 ?1:0;
74767 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
74777 (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
74778 (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
74787 ** If the user has not set the safety-level for this database connection
74788 ** using "PRAGMA synchronous", and if the safety-level is not already
74797 if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
74798 while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
74799 if( pDb->bSyncSet==0
74800 && pDb->safety_level!=safety_level
74801 && pDb!=&db->aDb[1]
74803 pDb->safety_level = safety_level;
74804 sqlite3PagerSetFlags(pBt->pPager,
74805 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
74822 ** well-formed database file, then SQLITE_CORRUPT is returned.
74832 assert( sqlite3_mutex_held(pBt->mutex) );
74833 assert( pBt->pPage1==0 );
74834 rc = sqlite3PagerSharedLock(pBt->pPager);
74842 nPage = get4byte(28+(u8*)pPage1->aData);
74843 sqlite3PagerPagecount(pBt->pPager, (int*)&nPageFile);
74844 if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
74847 if( (pBt->db->flags & SQLITE_ResetDatabase)!=0 ){
74853 u8 *page1 = pPage1->aData;
74855 /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
74864 pBt->btsFlags |= BTS_READ_ONLY;
74871 pBt->btsFlags |= BTS_READ_ONLY;
74882 ** may not be the latest version - there may be a newer one in the log
74885 if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
74887 rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
74903 /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
74912 /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
74913 ** determined by the 2-byte integer located at an offset of 16 bytes from
74916 /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
74918 if( ((pageSize-1)&pageSize)!=0
74925 /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
74929 ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
74930 ** determined by the one-byte unsigned integer found at an offset of 20
74932 usableSize = pageSize - page1[20];
74933 if( (u32)pageSize!=pBt->pageSize ){
74935 ** of BtShared.pageSize, we have discovered that the page-size is
74936 ** actually pageSize. Unlock the database, leave pBt->pPage1 at
74938 ** again with the correct page-size.
74941 pBt->usableSize = usableSize;
74942 pBt->pageSize = pageSize;
74943 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
74945 rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
74946 pageSize-usableSize);
74950 if( sqlite3WritableSchema(pBt->db)==0 ){
74957 /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
74963 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
74964 pBt->pageSize = pageSize;
74965 pBt->usableSize = usableSize;
74967 pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
74968 pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
74974 ** cells can will fit on one page. We assume a 10-byte page header.
74976 ** 2-byte pointer to the cell
74977 ** 4-byte child pointer
74978 ** 9-byte nKey value
74979 ** 4-byte nData value
74980 ** 4-byte overflow page pointer
74981 ** So a cell consists of a 2-byte pointer, a header which is as much as
74982 ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
74985 pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
74986 pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
74987 pBt->maxLeaf = (u16)(pBt->usableSize - 35);
74988 pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
74989 if( pBt->maxLocal>127 ){
74990 pBt->max1bytePayload = 127;
74992 pBt->max1bytePayload = (u8)pBt->maxLocal;
74994 assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
74995 pBt->pPage1 = pPage1;
74996 pBt->nPage = nPage;
75001 pBt->pPage1 = 0;
75021 for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
75022 if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
75023 && pCur->eState!=CURSOR_FAULT ) r++;
75035 ** If there is a transaction in progress, this routine is a no-op.
75038 assert( sqlite3_mutex_held(pBt->mutex) );
75039 assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
75040 if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
75041 MemPage *pPage1 = pBt->pPage1;
75042 assert( pPage1->aData );
75043 assert( sqlite3PagerRefcount(pBt->pPager)==1 );
75044 pBt->pPage1 = 0;
75050 ** If pBt points to an empty file then convert that empty file
75059 assert( sqlite3_mutex_held(pBt->mutex) );
75060 if( pBt->nPage>0 ){
75063 pP1 = pBt->pPage1;
75065 data = pP1->aData;
75066 rc = sqlite3PagerWrite(pP1->pDbPage);
75070 data[16] = (u8)((pBt->pageSize>>8)&0xff);
75071 data[17] = (u8)((pBt->pageSize>>16)&0xff);
75074 assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
75075 data[20] = (u8)(pBt->pageSize - pBt->usableSize);
75079 memset(&data[24], 0, 100-24);
75081 pBt->btsFlags |= BTS_PAGESIZE_FIXED;
75083 assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
75084 assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
75085 put4byte(&data[36 + 4*4], pBt->autoVacuum);
75086 put4byte(&data[36 + 7*4], pBt->incrVacuum);
75088 pBt->nPage = 1;
75096 ** if successful, or an SQLite error code otherwise.
75101 p->pBt->nPage = 0;
75102 rc = newDatabase(p->pBt);
75108 ** Attempt to start a new transaction. A write-transaction
75109 ** is started if the second argument is nonzero, otherwise a read-
75113 ** upgraded to exclusive by calling this routine a second time - the
75116 ** A write-transaction must be started before attempting any
75128 ** If an initial attempt to acquire the lock fails because of lock contention
75130 ** if there is one. But if there was previously a read-lock, do not
75131 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
75132 ** returned when there is already a read-lock in order to avoid a deadlock.
75147 BtShared *pBt = p->pBt;
75148 Pager *pPager = pBt->pPager;
75154 /* If the btree is already in a write-transaction, or it
75155 ** is already in a read-transaction and a read-transaction
75156 ** is requested, this is a no-op.
75158 if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
75161 assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
75163 if( (p->db->flags & SQLITE_ResetDatabase)
75166 pBt->btsFlags &= ~BTS_READ_ONLY;
75169 /* Write transactions are not possible on a read-only database */
75170 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
75179 ** on this shared-btree structure and a second write transaction is
75182 if( (wrflag && pBt->inTransaction==TRANS_WRITE)
75183 || (pBt->btsFlags & BTS_PENDING)!=0
75185 pBlock = pBt->pWriter->db;
75188 for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
75189 if( pIter->pBtree!=p ){
75190 pBlock = pIter->pBtree->db;
75196 sqlite3ConnectionBlocked(p->db, pBlock);
75203 /* Any read-only or read-write transaction implies a read-lock on
75204 ** page 1. So if some other shared-cache client already has a write-lock
75209 pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
75210 if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
75212 sqlite3PagerWalDb(pPager, p->db);
75217 if( pBt->pPage1==0 && wrflag ){
75218 assert( pBt->inTransaction==TRANS_NONE );
75224 /* Call lockBtree() until either pBt->pPage1 is populated or
75226 ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
75227 ** reading page 1 it discovers that the page-size of the database
75228 ** file is not pBt->pageSize. In this case lockBtree() will update
75229 ** pBt->pageSize to the page-size of the file on disk.
75231 while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
75234 if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
75237 rc = sqlite3PagerBegin(pPager, wrflag>1, sqlite3TempInMemory(p->db));
75240 }else if( rc==SQLITE_BUSY_SNAPSHOT && pBt->inTransaction==TRANS_NONE ){
75256 ** the busy-handler is not invoked. */
75260 }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
75268 if( p->inTrans==TRANS_NONE ){
75269 pBt->nTransaction++;
75271 if( p->sharable ){
75272 assert( p->lock.pBtree==p && p->lock.iTable==1 );
75273 p->lock.eLock = READ_LOCK;
75274 p->lock.pNext = pBt->pLock;
75275 pBt->pLock = &p->lock;
75279 p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
75280 if( p->inTrans>pBt->inTransaction ){
75281 pBt->inTransaction = p->inTrans;
75284 MemPage *pPage1 = pBt->pPage1;
75286 assert( !pBt->pWriter );
75287 pBt->pWriter = p;
75288 pBt->btsFlags &= ~BTS_EXCLUSIVE;
75289 if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
75292 /* If the db-size header field is incorrect (as it may be if an old
75295 ** re-read the database size from page 1 if a savepoint or transaction
75298 if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
75299 rc = sqlite3PagerWrite(pPage1->pDbPage);
75301 put4byte(&pPage1->aData[28], pBt->nPage);
75310 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
75315 ** the sub-journal is not already open, then it will be opened here.
75317 rc = sqlite3PagerOpenSavepoint(pPager, p->db->nSavepoint);
75327 if( p->sharable
75328 || p->inTrans==TRANS_NONE
75329 || (p->inTrans==TRANS_READ && wrflag!=0)
75333 pBt = p->pBt;
75335 *pSchemaVersion = get4byte(&pBt->pPage1->aData[40]);
75340 ** the sub-journal is not already open, then it will be opened here.
75342 return sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
75351 ** Set the pointer-map entries for all children of page pPage. Also, if
75359 BtShared *pBt = pPage->pBt;
75360 Pgno pgno = pPage->pgno;
75362 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
75363 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
75365 nCell = pPage->nCell;
75372 if( !pPage->leaf ){
75378 if( !pPage->leaf ){
75379 Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
75391 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
75394 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
75397 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
75401 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
75402 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
75405 if( get4byte(pPage->aData)!=iFrom ){
75408 put4byte(pPage->aData, iTo);
75414 rc = pPage->isInit ? SQLITE_OK : btreeInitPage(pPage);
75416 nCell = pPage->nCell;
75422 pPage->xParseCell(pPage, pCell, &info);
75424 if( pCell+info.nSize > pPage->aData+pPage->pBt->usableSize ){
75427 if( iFrom==get4byte(pCell+info.nSize-4) ){
75428 put4byte(pCell+info.nSize-4, iTo);
75433 if( pCell+4 > pPage->aData+pPage->pBt->usableSize ){
75445 get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
75448 put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
75460 ** the journal needs to be sync()ed before database page pDbPage->pgno
75468 Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
75473 Pgno iDbPage = pDbPage->pgno;
75474 Pager *pPager = pBt->pPager;
75479 assert( sqlite3_mutex_held(pBt->mutex) );
75480 assert( pDbPage->pBt==pBt );
75486 rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
75490 pDbPage->pgno = iFreePage;
75492 /* If pDbPage was a btree-page, then it may have child pages and/or cells
75496 ** If pDbPage is an overflow page, then the first 4 bytes may store a
75506 Pgno nextOvfl = get4byte(pDbPage->aData);
75524 rc = sqlite3PagerWrite(pPtrPage->pDbPage);
75542 ** Perform a single step of an incremental-vacuum. If successful, return
75544 ** calling this function again), return SQLITE_DONE. Or, if an error
75547 ** More specifically, this function attempts to re-organize the database so
75553 ** If the bCommit parameter is non-zero, this function assumes that the
75555 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
75556 ** operation, or false for an incremental vacuum.
75559 Pgno nFreeList; /* Number of pages still on the free-list */
75562 assert( sqlite3_mutex_held(pBt->mutex) );
75569 nFreeList = get4byte(&pBt->pPage1->aData[36]);
75584 /* Remove the page from the files free-list. This is not required
75585 ** if bCommit is non-zero. In that case, the free-list will be
75613 ** looping until a free-page located within the first nFin pages
75646 iLastPg--;
75648 pBt->bDoTruncate = 1;
75649 pBt->nPage = iLastPg;
75655 ** The database opened by the first argument is an auto-vacuum database
75657 ** size of the database in pages following an auto-vacuum operation.
75664 nEntry = pBt->usableSize/5;
75665 nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
75666 nFin = nOrig - nFree - nPtrmap;
75668 nFin--;
75671 nFin--;
75678 ** A write-transaction must be opened before calling this function.
75679 ** It performs a single unit of work towards an incremental vacuum.
75683 ** SQLITE_OK is returned. Otherwise an SQLite error code.
75687 BtShared *pBt = p->pBt;
75690 assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
75691 if( !pBt->autoVacuum ){
75695 Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
75707 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
75708 put4byte(&pBt->pPage1->aData[28], pBt->nPage);
75720 ** is committed for an auto-vacuum database.
75730 pBt = p->pBt;
75731 pPager = pBt->pPager;
75734 assert( sqlite3_mutex_held(pBt->mutex) );
75736 assert(pBt->autoVacuum);
75737 if( !pBt->incrVacuum ){
75747 ** is either a pointer-map page or the pending-byte page. If one
75753 nFree = get4byte(&pBt->pPage1->aData[36]);
75754 db = p->db;
75755 if( db->xAutovacPages ){
75757 for(iDb=0; ALWAYS(iDb<db->nDb); iDb++){
75758 if( db->aDb[iDb].pBt==p ) break;
75760 nVac = db->xAutovacPages(
75761 db->pAutovacPagesArg,
75762 db->aDb[iDb].zDbSName,
75765 pBt->pageSize
75781 for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
75785 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
75787 put4byte(&pBt->pPage1->aData[32], 0);
75788 put4byte(&pBt->pPage1->aData[36], 0);
75790 put4byte(&pBt->pPage1->aData[28], nFin);
75791 pBt->bDoTruncate = 1;
75792 pBt->nPage = nFin;
75808 ** This routine does the first phase of a two-phase commit. This routine
75820 ** This call is a no-op if no write-transaction is currently active on pBt.
75823 ** the name of a super-journal file that should be written into the
75824 ** individual journal file, or is NULL, indicating no super-journal file
75827 ** When this is called, the super-journal should already have been
75831 ** the write-transaction for this database file is to delete the journal.
75835 if( p->inTrans==TRANS_WRITE ){
75836 BtShared *pBt = p->pBt;
75839 if( pBt->autoVacuum ){
75846 if( pBt->bDoTruncate ){
75847 sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
75850 rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zSuperJrnl, 0);
75861 BtShared *pBt = p->pBt;
75862 sqlite3 *db = p->db;
75866 pBt->bDoTruncate = 0;
75868 if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
75870 ** handle, downgrade to a read-only transaction. The other statements
75873 p->inTrans = TRANS_READ;
75879 if( p->inTrans!=TRANS_NONE ){
75881 pBt->nTransaction--;
75882 if( 0==pBt->nTransaction ){
75883 pBt->inTransaction = TRANS_NONE;
75889 p->inTrans = TRANS_NONE;
75899 ** This routine implements the second phase of a 2-phase commit. The
75908 ** Normally, if an error occurs while the pager layer is attempting to
75909 ** finalize the underlying journal file, this function returns an error and
75911 ** is non-zero then this b-tree transaction is part of a multi-file
75913 ** (by deleting a super-journal file) and the caller will ignore this
75914 ** functions return code. So, even if an error occurs in the pager layer,
75915 ** reset the b-tree objects internal state to indicate that the write
75924 if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
75928 /* If the handle has a write-transaction open, commit the shared-btrees
75931 if( p->inTrans==TRANS_WRITE ){
75933 BtShared *pBt = p->pBt;
75934 assert( pBt->inTransaction==TRANS_WRITE );
75935 assert( pBt->nTransaction>0 );
75936 rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
75941 p->iBDataVersion--; /* Compensate for pPager->iDataVersion++; */
75942 pBt->inTransaction = TRANS_READ;
75976 ** flag is true, then only write-cursors need be tripped - read-only
75980 ** rolled back modified the database schema. In this case b-tree root
75984 ** If the writeOnly flag is true and an error is encountered while
75985 ** saving the current position of a read-only cursor, all cursors,
75986 ** including all read-cursors are tripped.
75988 ** SQLITE_OK is returned if successful, or if an error occurs while
75989 ** saving a cursor position, an SQLite error code.
75998 for(p=pBtree->pBt->pCursor; p; p=p->pNext){
75999 if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
76000 if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
76009 p->eState = CURSOR_FAULT;
76010 p->skipNext = errCode;
76020 ** Set the pBt->nPage field correctly, according to the current
76021 ** state of the database. Assume pBt->pPage1 is valid.
76024 int nPage = get4byte(&pPage1->aData[28]);
76026 if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
76027 testcase( pBt->nPage!=(u32)nPage );
76028 pBt->nPage = nPage;
76037 ** a tripped cursor will result in an error.
76044 BtShared *pBt = p->pBt;
76063 if( p->inTrans==TRANS_WRITE ){
76066 assert( TRANS_WRITE==pBt->inTransaction );
76067 rc2 = sqlite3PagerRollback(pBt->pPager);
76072 /* The rollback may have destroyed the pPage1->aData value. So
76074 ** sure pPage1->aData is set correctly. */
76080 pBt->inTransaction = TRANS_READ;
76100 ** A statement sub-transaction is implemented as an anonymous savepoint. The
76102 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
76103 ** are no active savepoints and no other statement-transactions open,
76109 BtShared *pBt = p->pBt;
76111 assert( p->inTrans==TRANS_WRITE );
76112 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
76114 assert( iStatement>p->db->nSavepoint );
76115 assert( pBt->inTransaction==TRANS_WRITE );
76117 ** an index greater than all savepoints created explicitly using
76121 rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
76133 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
76140 if( p && p->inTrans==TRANS_WRITE ){
76141 BtShared *pBt = p->pBt;
76143 assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
76149 rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
76152 if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
76153 pBt->nPage = 0;
76156 btreeSetNPage(pBt, pBt->pPage1);
76158 /* pBt->nPage might be zero if the database was corrupt when
76160 assert( CORRUPT_DB || pBt->nPage>0 );
76169 ** iTable. If a read-only cursor is requested, it is assumed that
76170 ** the caller already has at least a read-only transaction open
76171 ** on the database already. If a write-cursor is requested, then
76172 ** the caller is assumed to have an open write transaction.
76188 ** 3: The database must be writable (not on read-only media)
76190 ** 4: There must be an active transaction.
76194 ** this cursor will only be used to seek to and delete entries of an index
76199 ** operations on this cursor can be no-ops and all READ operations can
76200 ** return a null row (2-bytes: 0x01 0x00).
76203 ** root page of a b-tree. If it is not, then the cursor acquired
76212 int wrFlag, /* 1 to write. 0 read-only */
76216 BtShared *pBt = p->pBt; /* Shared b-tree handle */
76226 ** b-tree database, the connection is holding the required table locks,
76234 assert( p->inTrans>TRANS_NONE );
76235 assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
76236 assert( pBt->pPage1 && pBt->pPage1->aData );
76237 assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
76250 pCur->pgnoRoot = iTable;
76251 pCur->iPage = -1;
76252 pCur->pKeyInfo = pKeyInfo;
76253 pCur->pBtree = p;
76254 pCur->pBt = pBt;
76255 pCur->curFlags = 0;
76258 for(pX=pBt->pCursor; pX; pX=pX->pNext){
76259 if( pX->pgnoRoot==iTable ){
76260 pX->curFlags |= BTCF_Multiple;
76261 pCur->curFlags = BTCF_Multiple;
76264 pCur->eState = CURSOR_INVALID;
76265 pCur->pNext = pBt->pCursor;
76266 pBt->pCursor = pCur;
76268 pCur->curFlags |= BTCF_WriteFlag;
76269 pCur->curPagerFlags = 0;
76270 if( pBt->pTmpSpace==0 ) return allocateTempSpace(pBt);
76272 pCur->curPagerFlags = PAGER_GET_READONLY;
76279 int wrFlag, /* 1 to write. 0 read-only */
76292 int wrFlag, /* 1 to write. 0 read-only */
76296 if( p->sharable ){
76308 ** to users so they cannot do the sizeof() themselves - they must call
76325 BtShared *pBt = pBtree->pBt;
76326 if( (pBt->openFlags & BTREE_SINGLE)==0 ) return 0;
76327 if( pBt->pCursor!=pCur ) return 0;
76328 if( pCur->pNext!=0 ) return 0;
76329 if( pCur->pBtree!=pBtree ) return 0;
76340 ** of run-time by skipping the initialization of those elements.
76351 Btree *pBtree = pCur->pBtree;
76353 BtShared *pBt = pCur->pBt;
76355 assert( pBt->pCursor!=0 );
76356 if( pBt->pCursor==pCur ){
76357 pBt->pCursor = pCur->pNext;
76359 BtCursor *pPrev = pBt->pCursor;
76361 if( pPrev->pNext==pCur ){
76362 pPrev->pNext = pCur->pNext;
76365 pPrev = pPrev->pNext;
76370 sqlite3_free(pCur->aOverflow);
76371 sqlite3_free(pCur->pKey);
76372 if( (pBt->openFlags & BTREE_SINGLE) && pBt->pCursor==0 ){
76375 assert( pBtree->sharable==0 );
76380 pCur->pBtree = 0;
76395 if( a->nKey!=b->nKey ) return 0;
76396 if( a->pPayload!=b->pPayload ) return 0;
76397 if( a->nPayload!=b->nPayload ) return 0;
76398 if( a->nLocal!=b->nLocal ) return 0;
76399 if( a->nSize!=b->nSize ) return 0;
76405 btreeParseCell(pCur->pPage, pCur->ix, &info);
76406 assert( CORRUPT_DB || cellInfoEqual(&info, &pCur->info) );
76412 if( pCur->info.nSize==0 ){
76413 pCur->curFlags |= BTCF_ValidNKey;
76414 btreeParseCell(pCur->pPage,pCur->ix,&pCur->info);
76423 ** that is currently pointing to a row in a (non-empty) table.
76427 return pCur && pCur->eState==CURSOR_VALID;
76432 return pCur->eState==CURSOR_VALID;
76438 ** ordinary table btree. If the cursor points to an index btree or
76443 assert( pCur->eState==CURSOR_VALID );
76444 assert( pCur->curIntKey );
76446 return pCur->info.nKey;
76453 assert( (pCur->curFlags & BTCF_Pinned)==0 );
76454 pCur->curFlags |= BTCF_Pinned;
76457 assert( (pCur->curFlags & BTCF_Pinned)!=0 );
76458 pCur->curFlags &= ~BTCF_Pinned;
76467 assert( pCur->eState==CURSOR_VALID );
76469 return (i64)pCur->pBt->pageSize*((i64)pCur->pPage->pgno - 1) +
76470 (i64)(pCur->info.pPayload - pCur->pPage->aData);
76478 ** The caller must guarantee that the cursor is pointing to a non-NULL
76484 assert( pCur->eState==CURSOR_VALID );
76486 return pCur->info.nPayload;
76490 ** Return an upper bound on the size of any record for the table
76493 ** This is an optimization. Everything will still work if this
76504 assert( pCur->eState==CURSOR_VALID );
76505 return pCur->pBt->pageSize * (sqlite3_int64)pCur->pBt->nPage;
76509 ** Given the page number of an overflow page in the database (parameter
76511 ** linked list of overflow pages. If possible, it uses the auto-vacuum
76512 ** pointer-map data instead of reading the content of page ovfl to do so.
76514 ** If an error occurs an SQLite error code is returned. Otherwise:
76524 ** the pointer-map was used to obtain the value for *pPgnoNext), then
76537 assert( sqlite3_mutex_held(pBt->mutex) );
76542 ** autovacuum pointer-map pages. Guess that the next page in
76547 if( pBt->autoVacuum ){
76571 next = get4byte(pPage->aData);
76593 ** SQLITE_OK is returned on success, otherwise an error code.
76599 int eOp, /* 0 -> copy from page, 1 -> copy to page */
76632 ** the overflow page-list cache array (BtCursor.aOverflow).
76636 ** Once an overflow page-list cache has been allocated, it must be
76638 ** the cursor is moved to a different row. Additionally, in auto-vacuum
76639 ** mode, the following events may invalidate an overflow page-list cache.
76641 ** * An incremental vacuum,
76643 ** * Creating a table (may require moving an overflow page).
76650 int eOp /* zero to read. non-zero to write. */
76655 MemPage *pPage = pCur->pPage; /* Btree page of current entry */
76656 BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
76663 assert( pCur->eState==CURSOR_VALID );
76664 if( pCur->ix>=pPage->nCell ){
76670 aPayload = pCur->info.pPayload;
76671 assert( offset+amt <= pCur->info.nPayload );
76673 assert( aPayload > pPage->aData );
76674 if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
76675 /* Trying to read or write past the end of the data is an error. The
76677 ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
76684 if( offset<pCur->info.nLocal ){
76686 if( a+offset>pCur->info.nLocal ){
76687 a = pCur->info.nLocal - offset;
76689 rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
76692 amt -= a;
76694 offset -= pCur->info.nLocal;
76699 const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
76702 nextPage = get4byte(&aPayload[pCur->info.nLocal]);
76711 if( (pCur->curFlags & BTCF_ValidOvfl)==0 ){
76712 int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
76713 if( pCur->aOverflow==0
76714 || nOvfl*(int)sizeof(Pgno) > sqlite3MallocSize(pCur->aOverflow)
76720 aNew = (Pgno*)sqlite3Realloc(pCur->aOverflow, nOvfl*2*sizeof(Pgno));
76725 pCur->aOverflow = aNew;
76728 memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
76729 pCur->curFlags |= BTCF_ValidOvfl;
76732 assert( pCur->aOverflow[0]==nextPage
76733 || pCur->aOverflow[0]==0
76735 assert( pCur->aOverflow[0]!=0 || pCur->aOverflow[offset/ovflSize]==0 );
76737 /* If the overflow page-list cache has been allocated and the
76741 if( pCur->aOverflow[offset/ovflSize] ){
76743 nextPage = pCur->aOverflow[iIdx];
76750 /* If required, populate the overflow page-list cache. */
76751 if( nextPage > pBt->nPage ) return SQLITE_CORRUPT_BKPT;
76752 assert( pCur->aOverflow[iIdx]==0
76753 || pCur->aOverflow[iIdx]==nextPage
76755 pCur->aOverflow[iIdx] = nextPage;
76761 ** page-list cache, if any, then fall back to the getOverflowPage()
76764 assert( pCur->curFlags & BTCF_ValidOvfl );
76765 assert( pCur->pBtree->db==pBt->db );
76766 if( pCur->aOverflow[iIdx+1] ){
76767 nextPage = pCur->aOverflow[iIdx+1];
76771 offset -= ovflSize;
76778 a = ovflSize - offset;
76786 ** 3) there are no dirty pages in the page-cache
76787 ** 4) the database is file-backed, and
76792 ** output buffer, bypassing the page-cache altogether. This speeds
76797 && sqlite3PagerDirectReadOk(pBt->pPager, nextPage) /* (3,4,5) */
76798 && &pBuf[-4]>=pBufStart /* (6) */
76800 sqlite3_file *fd = sqlite3PagerFile(pBt->pPager);
76802 u8 *aWrite = &pBuf[-4];
76805 rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
76813 rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
76824 amt -= a;
76845 ** pCur can be pointing to either a table or an index b-tree.
76847 ** pCur is pointing to an index b-tree then the key section is read.
76853 ** Return SQLITE_OK on success or an error code if anything goes
76854 ** wrong. An error is returned if "offset+amt" is larger than
76859 assert( pCur->eState==CURSOR_VALID );
76860 assert( pCur->iPage>=0 && pCur->pPage );
76877 if ( pCur->eState==CURSOR_INVALID ){
76885 if( pCur->eState==CURSOR_VALID ){
76897 ** the key if index btrees (pPage->intKey==0) and is the data for
76898 ** table btrees (pPage->intKey==1). The number of bytes of available
76902 ** This routine is an optimization. It is common for the entire key
76918 assert( pCur!=0 && pCur->iPage>=0 && pCur->pPage);
76919 assert( pCur->eState==CURSOR_VALID );
76920 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
76922 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
76923 assert( pCur->info.nSize>0 );
76924 assert( pCur->info.pPayload>pCur->pPage->aData || CORRUPT_DB );
76925 assert( pCur->info.pPayload<pCur->pPage->aDataEnd ||CORRUPT_DB);
76926 amt = pCur->info.nLocal;
76927 if( amt>(int)(pCur->pPage->aDataEnd - pCur->info.pPayload) ){
76931 amt = MAX(0, (int)(pCur->pPage->aDataEnd - pCur->info.pPayload));
76934 return (void*)pCur->info.pPayload;
76941 ** b-tree page. Write the number of available bytes into *pAmt.
76961 ** This function returns SQLITE_CORRUPT if the page-header flags field of
76963 ** if an intkey page appears to be the parent of a non-intkey page, or
76964 ** vice-versa).
76969 assert( pCur->eState==CURSOR_VALID );
76970 assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
76971 assert( pCur->iPage>=0 );
76972 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
76975 pCur->info.nSize = 0;
76976 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
76977 pCur->aiIdx[pCur->iPage] = pCur->ix;
76978 pCur->apPage[pCur->iPage] = pCur->pPage;
76979 pCur->ix = 0;
76980 pCur->iPage++;
76981 rc = getAndInitPage(pCur->pBt, newPgno, &pCur->pPage, pCur->curPagerFlags);
76982 assert( pCur->pPage!=0 || rc!=SQLITE_OK );
76984 && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey)
76986 releasePage(pCur->pPage);
76990 pCur->pPage = pCur->apPage[--pCur->iPage];
76997 ** Page pParent is an internal (non-leaf) tree page. This function
76998 ** asserts that page number iChild is the left-child if the iIdx'th
77000 ** cells in pParent, that page number iChild is the right-child of
77006 assert( iIdx<=pParent->nCell );
77007 if( iIdx==pParent->nCell ){
77008 assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
77020 ** pCur->idx is set to the cell index that contains the pointer
77022 ** right-most child page then pCur->idx is set to one more than
77028 assert( pCur->eState==CURSOR_VALID );
77029 assert( pCur->iPage>0 );
77030 assert( pCur->pPage );
77032 pCur->apPage[pCur->iPage-1],
77033 pCur->aiIdx[pCur->iPage-1],
77034 pCur->pPage->pgno
77036 testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
77037 pCur->info.nSize = 0;
77038 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
77039 pCur->ix = pCur->aiIdx[pCur->iPage-1];
77040 pLeaf = pCur->pPage;
77041 pCur->pPage = pCur->apPage[--pCur->iPage];
77046 ** Move the cursor to point to the root page of its b-tree structure.
77053 ** If the b-tree structure is empty, the cursor state is set to
77059 ** page-header flags indicate that the [virtual] root-page is the expected
77060 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
77062 ** indicating a table b-tree, or if the caller did specify a KeyInfo
77063 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
77064 ** b-tree).
77074 assert( pCur->eState < CURSOR_REQUIRESEEK || pCur->iPage<0 );
77075 assert( pCur->pgnoRoot>0 || pCur->iPage<0 );
77077 if( pCur->iPage>=0 ){
77078 if( pCur->iPage ){
77079 releasePageNotNull(pCur->pPage);
77080 while( --pCur->iPage ){
77081 releasePageNotNull(pCur->apPage[pCur->iPage]);
77083 pRoot = pCur->pPage = pCur->apPage[0];
77086 }else if( pCur->pgnoRoot==0 ){
77087 pCur->eState = CURSOR_INVALID;
77090 assert( pCur->iPage==(-1) );
77091 if( pCur->eState>=CURSOR_REQUIRESEEK ){
77092 if( pCur->eState==CURSOR_FAULT ){
77093 assert( pCur->skipNext!=SQLITE_OK );
77094 return pCur->skipNext;
77098 rc = getAndInitPage(pCur->pBt, pCur->pgnoRoot, &pCur->pPage,
77099 pCur->curPagerFlags);
77101 pCur->eState = CURSOR_INVALID;
77104 pCur->iPage = 0;
77105 pCur->curIntKey = pCur->pPage->intKey;
77107 pRoot = pCur->pPage;
77108 assert( pRoot->pgno==pCur->pgnoRoot || CORRUPT_DB );
77110 /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
77111 ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
77112 ** NULL, the caller expects a table b-tree. If this is not the case,
77113 ** return an SQLITE_CORRUPT error.
77117 ** if pCur->iPage>=0). But this is not so if the database is corrupted
77118 ** in such a way that page pRoot is linked into a second b-tree table
77120 assert( pRoot->intKey==1 || pRoot->intKey==0 );
77121 if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
77122 return SQLITE_CORRUPT_PAGE(pCur->pPage);
77126 pCur->ix = 0;
77127 pCur->info.nSize = 0;
77128 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
77130 if( pRoot->nCell>0 ){
77131 pCur->eState = CURSOR_VALID;
77132 }else if( !pRoot->leaf ){
77134 if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
77135 subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
77136 pCur->eState = CURSOR_VALID;
77139 pCur->eState = CURSOR_INVALID;
77146 ** Move the cursor down to the left-most leaf entry beneath the
77149 ** The left-most leaf is the one with the smallest key - the first
77158 assert( pCur->eState==CURSOR_VALID );
77159 while( rc==SQLITE_OK && !(pPage = pCur->pPage)->leaf ){
77160 assert( pCur->ix<pPage->nCell );
77161 pgno = get4byte(findCell(pPage, pCur->ix));
77168 ** Move the cursor down to the right-most leaf entry beneath the
77171 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
77172 ** finds the right-most entry beneath the *page*.
77174 ** The right-most entry is the one with the largest key - the last
77183 assert( pCur->eState==CURSOR_VALID );
77184 while( !(pPage = pCur->pPage)->leaf ){
77185 pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
77186 pCur->ix = pPage->nCell;
77190 pCur->ix = pPage->nCell-1;
77191 assert( pCur->info.nSize==0 );
77192 assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
77204 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
77207 assert( pCur->pPage->nCell>0 );
77211 assert( pCur->pgnoRoot==0 || (pCur->pPage!=0 && pCur->pPage->nCell==0) );
77223 ** It is an internal verification routine and does not appear in production
77228 for(ii=0; ii<pCur->iPage; ii++){
77229 if( pCur->aiIdx[ii]!=pCur->apPage[ii]->nCell ) return 0;
77231 return pCur->ix==pCur->pPage->nCell-1 && pCur->pPage->leaf!=0;
77242 assert( pCur->eState==CURSOR_VALID );
77246 pCur->curFlags |= BTCF_AtLast;
77248 pCur->curFlags &= ~BTCF_AtLast;
77251 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
77259 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
77261 /* If the cursor already points to the last entry, this is a no-op. */
77262 if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
77270 /* Move the cursor so that it points to an entry in a table (a.k.a INTKEY)
77273 ** If an exact match is not found, then the cursor is always
77275 ** were present. The cursor might point to an entry that comes
77278 ** An integer is written into *pRes which is the result of
77283 ** *pRes<0 The cursor is left pointing at an entry that
77287 ** *pRes==0 The cursor is left pointing at an entry that
77290 ** *pRes>0 The cursor is left pointing at an entry that
77302 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
77304 assert( pCur->pKeyInfo==0 );
77305 assert( pCur->eState!=CURSOR_VALID || pCur->curIntKey!=0 );
77309 if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0 ){
77310 if( pCur->info.nKey==intKey ){
77314 if( pCur->info.nKey<intKey ){
77315 if( (pCur->curFlags & BTCF_AtLast)!=0 ){
77317 *pRes = -1;
77322 ** binary search. This is an optimization only. The correct answer
77324 if( pCur->info.nKey+1==intKey ){
77329 if( pCur->info.nKey==intKey ){
77340 pCur->pBtree->nSeek++; /* Performance measurement during testing */
77346 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
77347 *pRes = -1;
77352 assert( pCur->pPage );
77353 assert( pCur->pPage->isInit );
77354 assert( pCur->eState==CURSOR_VALID );
77355 assert( pCur->pPage->nCell > 0 );
77356 assert( pCur->iPage==0 || pCur->apPage[0]->intKey==pCur->curIntKey );
77357 assert( pCur->curIntKey );
77362 MemPage *pPage = pCur->pPage;
77365 /* pPage->nCell must be greater than zero. If this is the root-page
77367 ** not run. If this is not the root-page, then the moveToChild() routine
77369 ** be the right kind (index or table) of b-tree page. Otherwise
77371 assert( pPage->nCell>0 );
77372 assert( pPage->intKey );
77374 upr = pPage->nCell-1;
77376 idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
77380 if( pPage->intKeyLeaf ){
77382 if( pCell>=pPage->aDataEnd ){
77390 if( lwr>upr ){ c = -1; break; }
77392 upr = idx-1;
77396 pCur->ix = (u16)idx;
77397 if( !pPage->leaf ){
77401 pCur->curFlags |= BTCF_ValidNKey;
77402 pCur->info.nKey = nCellKey;
77403 pCur->info.nSize = 0;
77411 assert( lwr==upr+1 || !pPage->leaf );
77412 assert( pPage->isInit );
77413 if( pPage->leaf ){
77414 assert( pCur->ix<pCur->pPage->nCell );
77415 pCur->ix = (u16)idx;
77421 if( lwr>=pPage->nCell ){
77422 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
77426 pCur->ix = (u16)lwr;
77431 pCur->info.nSize = 0;
77432 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
77437 ** Compare the "idx"-th cell on the page the cursor pCur is currently
77449 ** This routine is part of an optimization. It is always safe to return
77458 MemPage *pPage = pCur->pPage;
77464 if( nCell<=pPage->max1bytePayload ){
77465 /* This branch runs if the record-size field of the cell is a
77467 ** b-tree page. */
77468 testcase( pCell+nCell+1==pPage->aDataEnd );
77471 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
77473 /* The record-size field is a 2 byte varint and the record
77474 ** fits entirely on the main b-tree page. */
77475 testcase( pCell+nCell+2==pPage->aDataEnd );
77486 ** Return true (non-zero) if pCur is current pointing to the last
77491 assert( pCur->eState==CURSOR_VALID );
77492 for(i=0; i<pCur->iPage; i++){
77493 MemPage *pPage = pCur->apPage[i];
77494 if( pCur->aiIdx[i]<pPage->nCell ) return 0;
77499 /* Move the cursor so that it points to an entry in an index table
77502 ** If an exact match is not found, then the cursor is always
77504 ** were present. The cursor might point to an entry that comes
77507 ** An integer is written into *pRes which is the result of
77512 ** *pRes<0 The cursor is left pointing at an entry that
77516 ** *pRes==0 The cursor is left pointing at an entry that
77519 ** *pRes>0 The cursor is left pointing at an entry that
77522 ** The pIdxKey->eqSeen field is set to 1 if there
77523 ** exists an entry in the table that exactly matches pIdxKey.
77534 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
77536 assert( pCur->pKeyInfo!=0 );
77539 pCur->pBtree->nSeek++; /* Performance measurement during testing */
77543 pIdxKey->errCode = 0;
77544 assert( pIdxKey->default_rc==1
77545 || pIdxKey->default_rc==0
77546 || pIdxKey->default_rc==-1
77561 if( pCur->eState==CURSOR_VALID
77562 && pCur->pPage->leaf
77566 if( pCur->ix==pCur->pPage->nCell-1
77567 && (c = indexCellCompare(pCur, pCur->ix, pIdxKey, xRecordCompare))<=0
77568 && pIdxKey->errCode==SQLITE_OK
77573 if( pCur->iPage>0
77575 && pIdxKey->errCode==SQLITE_OK
77577 pCur->curFlags &= ~(BTCF_ValidOvfl|BTCF_AtLast);
77578 if( !pCur->pPage->isInit ){
77583 pIdxKey->errCode = SQLITE_OK;
77589 assert( pCur->pgnoRoot==0 || pCur->pPage->nCell==0 );
77590 *pRes = -1;
77597 assert( pCur->pPage );
77598 assert( pCur->pPage->isInit );
77599 assert( pCur->eState==CURSOR_VALID );
77600 assert( pCur->pPage->nCell > 0 );
77601 assert( pCur->curIntKey==0 );
77606 MemPage *pPage = pCur->pPage;
77609 /* pPage->nCell must be greater than zero. If this is the root-page
77611 ** not run. If this is not the root-page, then the moveToChild() routine
77613 ** be the right kind (index or table) of b-tree page. Otherwise
77615 assert( pPage->nCell>0 );
77616 assert( pPage->intKey==0 );
77618 upr = pPage->nCell-1;
77624 /* The maximum supported page-size is 65536 bytes. This means that
77625 ** the maximum number of record bytes stored on an index B-Tree
77626 ** page is less than 16384 bytes and may be stored as a 2-byte
77629 ** stored entirely within the b-tree page by inspecting the first
77633 if( nCell<=pPage->max1bytePayload ){
77634 /* This branch runs if the record-size field of the cell is a
77636 ** b-tree page. */
77637 testcase( pCell+nCell+1==pPage->aDataEnd );
77640 && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
77642 /* The record-size field is a 2 byte varint and the record
77643 ** fits entirely on the main b-tree page. */
77644 testcase( pCell+nCell+2==pPage->aDataEnd );
77653 ** up to two varints past the end of the buffer. An extra 18
77657 u8 * const pCellBody = pCell - pPage->childPtrSize;
77659 pPage->xParseCell(pPage, pCellBody, &pCur->info);
77660 nCell = (int)pCur->info.nKey;
77665 if( nCell<2 || nCell/pCur->pBt->usableSize>pCur->pBt->nPage ){
77674 pCur->ix = (u16)idx;
77677 pCur->curFlags &= ~BTCF_ValidOvfl;
77686 (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
77687 && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
77692 upr = idx-1;
77697 pCur->ix = (u16)idx;
77698 if( pIdxKey->errCode ) rc = SQLITE_CORRUPT_BKPT;
77705 assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
77706 assert( pPage->isInit );
77707 if( pPage->leaf ){
77708 assert( pCur->ix<pCur->pPage->nCell || CORRUPT_DB );
77709 pCur->ix = (u16)idx;
77714 if( lwr>=pPage->nCell ){
77715 chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
77720 /* This block is similar to an in-lined version of:
77722 ** pCur->ix = (u16)lwr;
77726 pCur->info.nSize = 0;
77727 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
77728 if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
77731 pCur->aiIdx[pCur->iPage] = (u16)lwr;
77732 pCur->apPage[pCur->iPage] = pCur->pPage;
77733 pCur->ix = 0;
77734 pCur->iPage++;
77735 rc = getAndInitPage(pCur->pBt, chldPg, &pCur->pPage, pCur->curPagerFlags);
77737 && (pCur->pPage->nCell<1 || pCur->pPage->intKey!=pCur->curIntKey)
77739 releasePage(pCur->pPage);
77743 pCur->pPage = pCur->apPage[--pCur->iPage];
77747 ***** End of in-lined moveToChild() call */
77750 pCur->info.nSize = 0;
77751 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
77757 ** Return TRUE if the cursor is not pointing at an entry of the table.
77765 ** have been deleted? This API will need to change to return an error code
77768 return (CURSOR_VALID!=pCur->eState);
77772 ** Return an estimate for the number of rows in the table that pCur is
77781 assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
77786 if( pCur->eState!=CURSOR_VALID ) return 0;
77787 if( NEVER(pCur->pPage->leaf==0) ) return -1;
77789 n = pCur->pPage->nCell;
77790 for(i=0; i<pCur->iPage; i++){
77791 n *= pCur->apPage[i]->nCell;
77811 ** cursor corresponds to an SQL index and this routine could have been
77822 if( pCur->eState!=CURSOR_VALID ){
77823 assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
77828 if( CURSOR_INVALID==pCur->eState ){
77831 if( pCur->eState==CURSOR_SKIPNEXT ){
77832 pCur->eState = CURSOR_VALID;
77833 if( pCur->skipNext>0 ) return SQLITE_OK;
77837 pPage = pCur->pPage;
77838 idx = ++pCur->ix;
77839 if( sqlite3FaultSim(412) ) pPage->isInit = 0;
77840 if( !pPage->isInit ){
77844 if( idx>=pPage->nCell ){
77845 if( !pPage->leaf ){
77846 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
77851 if( pCur->iPage==0 ){
77852 pCur->eState = CURSOR_INVALID;
77856 pPage = pCur->pPage;
77857 }while( pCur->ix>=pPage->nCell );
77858 if( pPage->intKey ){
77864 if( pPage->leaf ){
77875 pCur->info.nSize = 0;
77876 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
77877 if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur);
77878 pPage = pCur->pPage;
77879 if( (++pCur->ix)>=pPage->nCell ){
77880 pCur->ix--;
77883 if( pPage->leaf ){
77905 ** the cursor corresponds to an SQL index and this routine could have been
77915 assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
77916 assert( pCur->info.nSize==0 );
77917 if( pCur->eState!=CURSOR_VALID ){
77922 if( CURSOR_INVALID==pCur->eState ){
77925 if( CURSOR_SKIPNEXT==pCur->eState ){
77926 pCur->eState = CURSOR_VALID;
77927 if( pCur->skipNext<0 ) return SQLITE_OK;
77931 pPage = pCur->pPage;
77932 if( sqlite3FaultSim(412) ) pPage->isInit = 0;
77933 if( !pPage->isInit ){
77936 if( !pPage->leaf ){
77937 int idx = pCur->ix;
77942 while( pCur->ix==0 ){
77943 if( pCur->iPage==0 ){
77944 pCur->eState = CURSOR_INVALID;
77949 assert( pCur->info.nSize==0 );
77950 assert( (pCur->curFlags & (BTCF_ValidOvfl))==0 );
77952 pCur->ix--;
77953 pPage = pCur->pPage;
77954 if( pPage->intKey && !pPage->leaf ){
77966 pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
77967 pCur->info.nSize = 0;
77968 if( pCur->eState!=CURSOR_VALID
77969 || pCur->ix==0
77970 || pCur->pPage->leaf==0
77974 pCur->ix--;
77987 ** an error. *ppPage is set to NULL in the event of an error.
77989 ** If the "nearby" parameter is not 0, then an effort is made to
77990 ** locate a page close to the page number "nearby". This can be used in an
77995 ** anywhere on the free-list, then it is guaranteed to be returned. If
78015 assert( sqlite3_mutex_held(pBt->mutex) );
78016 assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
78017 pPage1 = pBt->pPage1;
78019 /* EVIDENCE-OF: R-21003-45125 The 4-byte big-endian integer at offset 36
78021 n = get4byte(&pPage1->aData[36]);
78022 testcase( n==mxPage-1 );
78029 u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
78032 /* If eMode==BTALLOC_EXACT and a query of the pointer-map
78033 ** shows that the page 'nearby' is somewhere on the free-list, then
78034 ** the entire-list will be searched for that page.
78041 assert( pBt->autoVacuum );
78053 /* Decrement the free-list count by 1. Set iTrunk to the index of the
78054 ** first free-list trunk page. iPrevTrunk is initially 1.
78056 rc = sqlite3PagerWrite(pPage1->pDbPage);
78058 put4byte(&pPage1->aData[36], n-1);
78061 ** is not true. Otherwise, it runs once for each trunk-page on the
78062 ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
78068 /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
78071 iTrunk = get4byte(&pPrevTrunk->aData[0]);
78073 /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
78076 iTrunk = get4byte(&pPage1->aData[32]);
78080 rc = SQLITE_CORRUPT_PGNO(pPrevTrunk ? pPrevTrunk->pgno : 1);
78089 assert( pTrunk->aData!=0 );
78090 /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
78092 k = get4byte(&pTrunk->aData[4]);
78098 rc = sqlite3PagerWrite(pTrunk->pDbPage);
78103 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
78106 TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
78107 }else if( k>(u32)(pBt->usableSize/4 - 2) ){
78121 rc = sqlite3PagerWrite(pTrunk->pDbPage);
78127 memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
78129 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
78133 memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
78137 ** pointers to free-list leaves. The first leaf becomes a trunk
78141 Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
78151 rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
78156 memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
78157 put4byte(&pNewTrunk->aData[4], k-1);
78158 memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
78161 assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
78162 put4byte(&pPage1->aData[32], iNewTrunk);
78164 rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
78168 put4byte(&pPrevTrunk->aData[0], iNewTrunk);
78172 TRACE(("ALLOCATE: %u trunk - %u free pages left\n", *pPgno, n-1));
78178 unsigned char *aData = pTrunk->aData;
78192 dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
78194 int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
78219 *pPgno, closest+1, k, pTrunk->pgno, n-1));
78220 rc = sqlite3PagerWrite(pTrunk->pDbPage);
78222 if( closest<k-1 ){
78225 put4byte(&aData[4], k-1);
78229 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
78246 ** pager layer with the 'no-content' flag set. This prevents the pager
78248 ** current transaction has already run one or more incremental-vacuum
78251 ** not set the no-content flag. This causes the pager to load and journal
78256 ** file on disk. So the effects of disabling the no-content optimization
78260 int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
78262 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
78264 pBt->nPage++;
78265 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
78268 if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
78269 /* If *pPgno refers to a pointer-map page, allocate two new pages
78271 ** becomes a new pointer-map page, the second is used by the caller.
78274 TRACE(("ALLOCATE: %u from end of file (pointer-map page)\n", pBt->nPage));
78275 assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
78276 rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
78278 rc = sqlite3PagerWrite(pPg->pDbPage);
78282 pBt->nPage++;
78283 if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
78286 put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
78287 *pPgno = pBt->nPage;
78292 rc = sqlite3PagerWrite((*ppPage)->pDbPage);
78305 assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
78306 assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
78311 ** This function is used to add page iPage to the database file free-list.
78312 ** It is assumed that the page is not already a part of the free-list.
78323 MemPage *pTrunk = 0; /* Free-list trunk page */
78324 Pgno iTrunk = 0; /* Page number of free-list trunk page */
78325 MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
78328 u32 nFree; /* Initial number of pages on free-list */
78330 assert( sqlite3_mutex_held(pBt->mutex) );
78332 assert( !pMemPage || pMemPage->pgno==iPage );
78334 if( iPage<2 || iPage>pBt->nPage ){
78339 sqlite3PagerRef(pPage->pDbPage);
78345 rc = sqlite3PagerWrite(pPage1->pDbPage);
78347 nFree = get4byte(&pPage1->aData[36]);
78348 put4byte(&pPage1->aData[36], nFree+1);
78350 if( pBt->btsFlags & BTS_SECURE_DELETE ){
78355 || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
78359 memset(pPage->aData, 0, pPage->pBt->pageSize);
78362 /* If the database supports auto-vacuum, write an entry in the pointer-map
78370 /* Now manipulate the actual database free-list structure. There are two
78371 ** possibilities. If the free-list is currently empty, or if the first
78372 ** trunk page in the free-list is full, then this page will become a
78373 ** new free-list trunk page. Otherwise, it will become a leaf of the
78374 ** first trunk page in the current free-list. This block tests if it
78375 ** is possible to add the page as a new free-list leaf.
78380 iTrunk = get4byte(&pPage1->aData[32]);
78390 nLeaf = get4byte(&pTrunk->aData[4]);
78391 assert( pBt->usableSize>32 );
78392 if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
78396 if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
78401 ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
78404 ** usableSize/4 - 8 entries will be reported as corrupt. In order
78406 ** we will continue to restrict the number of entries to usableSize/4 - 8
78409 ** to read "usableSize/4-2" instead of "usableSize/4-8".
78411 ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
78416 rc = sqlite3PagerWrite(pTrunk->pDbPage);
78418 put4byte(&pTrunk->aData[4], nLeaf+1);
78419 put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
78420 if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
78421 sqlite3PagerDontWrite(pPage->pDbPage);
78425 TRACE(("FREE-PAGE: %u leaf on trunk page %u\n",pPage->pgno,pTrunk->pgno));
78431 ** the page being freed as a leaf page of the first trunk in the free-list.
78432 ** Possibly because the free-list is empty, or possibly because the
78433 ** first trunk in the free-list is full. Either way, the page being freed
78434 ** will become the new first trunk page in the free-list.
78439 rc = sqlite3PagerWrite(pPage->pDbPage);
78443 put4byte(pPage->aData, iTrunk);
78444 put4byte(&pPage->aData[4], 0);
78445 put4byte(&pPage1->aData[32], iPage);
78446 TRACE(("FREE-PAGE: %u new trunk page replacing %u\n", pPage->pgno, iTrunk));
78450 pPage->isInit = 0;
78458 *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
78476 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
78477 assert( pInfo->nLocal!=pInfo->nPayload );
78478 testcase( pCell + pInfo->nSize == pPage->aDataEnd );
78479 testcase( pCell + (pInfo->nSize-1) == pPage->aDataEnd );
78480 if( pCell + pInfo->nSize > pPage->aDataEnd ){
78484 ovflPgno = get4byte(pCell + pInfo->nSize - 4);
78485 pBt = pPage->pBt;
78486 assert( pBt->usableSize > 4 );
78487 ovflPageSize = pBt->usableSize - 4;
78488 nOvfl = (pInfo->nPayload - pInfo->nLocal + ovflPageSize - 1)/ovflPageSize;
78490 (CORRUPT_DB && (pInfo->nPayload + ovflPageSize)<ovflPageSize)
78492 while( nOvfl-- ){
78496 /* 0 is not a legal page number and page 1 cannot be an
78507 && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
78509 /* There is no reason any cursor should have an outstanding reference
78510 ** to an overflow page belonging to a cell that is being deleted/updated.
78512 ** must not really be an overflow page and the database must be corrupt.
78514 ** freePage2() may zero the page contents if secure-delete mode is
78525 sqlite3PagerUnref(pOvfl->pDbPage);
78540 pPage->xParseCell(pPage, pCell, &sInfo); \
78555 ** Note that pCell does not necessary need to point to the pPage->aData
78557 ** be constructed in this temporary area then copied into pPage->aData
78577 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
78581 assert( pCell<pPage->aData || pCell>=&pPage->aData[pPage->pBt->pageSize]
78582 || sqlite3PagerIswriteable(pPage->pDbPage) );
78585 nHeader = pPage->childPtrSize;
78586 if( pPage->intKey ){
78587 nPayload = pX->nData + pX->nZero;
78588 pSrc = pX->pData;
78589 nSrc = pX->nData;
78590 assert( pPage->intKeyLeaf ); /* fillInCell() only called for leaves */
78592 nHeader += putVarint(&pCell[nHeader], *(u64*)&pX->nKey);
78594 assert( pX->nKey<=0x7fffffff && pX->pKey!=0 );
78595 nSrc = nPayload = (int)pX->nKey;
78596 pSrc = pX->pKey;
78602 if( nPayload<=pPage->maxLocal ){
78616 memset(pPayload+nSrc, 0, nPayload-nSrc);
78623 mn = pPage->minLocal;
78624 n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
78625 testcase( n==pPage->maxLocal );
78626 testcase( n==pPage->maxLocal+1 );
78627 if( n > pPage->maxLocal ) n = mn;
78633 pBt = pPage->pBt;
78650 pPage->xParseCell(pPage, pCell, &info);
78651 assert( nHeader==(int)(info.pPayload - pCell) );
78652 assert( info.nKey==pX->nKey );
78665 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
78669 assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
78670 || sqlite3PagerIswriteable(pPage->pDbPage) );
78680 nPayload -= n;
78684 nSrc -= n;
78685 spaceLeft -= n;
78689 Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
78690 if( pBt->autoVacuum ){
78700 /* If the database supports auto-vacuum, and the second or subsequent
78701 ** overflow page is being allocated, add an entry to the pointer-map
78705 ** to the pointer-map. If we write nothing to this pointer-map slot,
78710 if( pBt->autoVacuum && rc==SQLITE_OK ){
78725 assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
78729 assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
78730 || sqlite3PagerIswriteable(pPage->pDbPage) );
78735 pPrior = pOvfl->aData;
78737 pPayload = &pOvfl->aData[4];
78738 spaceLeft = pBt->usableSize - 4;
78746 ** Remove the i-th cell from pPage. This routine effects pPage only.
78755 u8 *data; /* pPage->aData */
78762 assert( idx<pPage->nCell );
78764 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
78765 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
78766 assert( pPage->nFree>=0 );
78767 data = pPage->aData;
78768 ptr = &pPage->aCellIdx[2*idx];
78769 assert( pPage->pBt->usableSize > (u32)(ptr-data) );
78771 hdr = pPage->hdrOffset;
78773 testcase( pc+sz==pPage->pBt->usableSize );
78774 if( pc+sz > pPage->pBt->usableSize ){
78783 pPage->nCell--;
78784 if( pPage->nCell==0 ){
78787 put2byte(&data[hdr+5], pPage->pBt->usableSize);
78788 pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
78789 - pPage->childPtrSize - 8;
78791 memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
78792 put2byte(&data[hdr+3], pPage->nCell);
78793 pPage->nFree += 2;
78804 ** in pPage->apOvfl[] and make it point to the cell content (either
78806 ** Allocating a new entry in pPage->aCell[] implies that
78807 ** pPage->nOverflow is incremented.
78819 int i, /* New cell becomes the i-th cell of the page */
78823 Pgno iChild /* If non-zero, replace first 4 bytes with this value */
78828 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
78830 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
78831 assert( MX_CELL(pPage->pBt)<=10921 );
78832 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
78833 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
78834 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
78835 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
78836 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
78837 assert( pPage->nFree>=0 );
78839 if( pPage->nOverflow || sz+2>pPage->nFree ){
78845 j = pPage->nOverflow++;
78846 /* Comparison against ArraySize-1 since we hold back one extra slot
78849 assert( j < ArraySize(pPage->apOvfl)-1 );
78850 pPage->apOvfl[j] = pCell;
78851 pPage->aiOvfl[j] = (u16)i;
78858 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
78859 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
78861 int rc = sqlite3PagerWrite(pPage->pDbPage);
78865 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
78866 data = pPage->aData;
78867 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
78873 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
78874 assert( idx+sz <= (int)pPage->pBt->usableSize );
78875 pPage->nFree -= (u16)(2 + sz);
78876 /* In a corrupt database where an entry in the cell index section of
78881 memcpy(&data[idx+4], pCell+4, sz-4);
78883 pIns = pPage->aCellIdx + i*2;
78884 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
78886 pPage->nCell++;
78888 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
78889 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
78891 if( pPage->pBt->autoVacuum ){
78893 /* The cell may contain a pointer to an overflow page. If so, write
78916 int i, /* New cell becomes the i-th cell of the page */
78923 u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
78925 assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
78926 assert( MX_CELL(pPage->pBt)<=10921 );
78927 assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
78928 assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
78929 assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
78930 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
78931 assert( sz==pPage->xCellSize(pPage, pCell) || CORRUPT_DB );
78932 assert( pPage->nFree>=0 );
78933 assert( pPage->nOverflow==0 );
78934 if( sz+2>pPage->nFree ){
78935 j = pPage->nOverflow++;
78936 /* Comparison against ArraySize-1 since we hold back one extra slot
78939 assert( j < ArraySize(pPage->apOvfl)-1 );
78940 pPage->apOvfl[j] = pCell;
78941 pPage->aiOvfl[j] = (u16)i;
78948 assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
78949 assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
78951 int rc = sqlite3PagerWrite(pPage->pDbPage);
78955 assert( sqlite3PagerIswriteable(pPage->pDbPage) );
78956 data = pPage->aData;
78957 assert( &data[pPage->cellOffset]==pPage->aCellIdx );
78963 assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
78964 assert( idx+sz <= (int)pPage->pBt->usableSize );
78965 pPage->nFree -= (u16)(2 + sz);
78967 pIns = pPage->aCellIdx + i*2;
78968 memmove(pIns+2, pIns, 2*(pPage->nCell - i));
78970 pPage->nCell++;
78972 if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
78973 assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell || CORRUPT_DB );
78975 if( pPage->pBt->autoVacuum ){
78977 /* The cell may contain a pointer to an overflow page. If so, write
79001 ** tunable - as if you could change them and recompile and it would all work.
79016 ** used to access information such as MemPage.intKey and MemPage.pBt->pageSize
79028 ** -----------
79030 ** -----------
79033 ** --------- --------- ---------
79034 ** |Child-1| |Child-2| |Child-3|
79035 ** --------- --------- ---------
79037 ** The order of cells is in the array is for an index btree is:
79039 ** 1. All cells from Child-1 in order
79041 ** 3. All cells from Child-2 in order
79043 ** 5. All cells from Child-3 in order
79045 ** For a table-btree (with rowids) the items 2 and 4 are empty because
79048 ** For an index btree, the apEnd[] array holds pointer to the end of page
79049 ** for Child-1, the Parent, Child-2, the Parent (again), and Child-3,
79053 ** ixNx[0] = Number of cells in Child-1.
79054 ** ixNx[1] = Number of cells in Child-1 plus 1 for first divider.
79055 ** ixNx[2] = Number of cells in Child-1 and Child-2 + 1 for 1st divider.
79056 ** ixNx[3] = Number of cells in Child-1 and Child-2 + both divider cells
79059 ** For a table-btree, the concept is similar, except only apEnd[0]..apEnd[2]
79062 ** ixNx[0] = Number of cells in Child-1.
79063 ** ixNx[1] = Number of cells in Child-1 and Child-2.
79082 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
79086 MemPage *pRef = p->pRef;
79087 u16 *szCell = p->szCell;
79088 assert( idx>=0 && idx+N<=p->nCell );
79090 assert( p->apCell[idx]!=0 );
79092 szCell[idx] = pRef->xCellSize(pRef, p->apCell[idx]);
79095 szCell[idx]==pRef->xCellSize(pRef, p->apCell[idx]) );
79098 N--;
79106 assert( N>=0 && N<p->nCell );
79107 assert( p->szCell[N]==0 );
79108 p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
79109 return p->szCell[N];
79112 assert( N>=0 && N<p->nCell );
79113 if( p->szCell[N] ) return p->szCell[N];
79118 ** Array apCell[] contains pointers to nCell b-tree page cells. The
79136 const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
79137 u8 * const aData = pPg->aData; /* Pointer to data for pPg */
79138 const int usableSize = pPg->pBt->usableSize;
79143 u8 *pCellptr = pPg->aCellIdx;
79144 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
79146 int k; /* Current slot in pCArray->apEnd[] */
79147 u8 *pSrcEnd; /* Current pCArray->apEnd[k] value */
79153 memcpy(&pTmp[j], &aData[j], usableSize - j);
79155 assert( pCArray->ixNx[NB*2-1]>i );
79156 for(k=0; pCArray->ixNx[k]<=i; k++){}
79157 pSrcEnd = pCArray->apEnd[k];
79161 u8 *pCell = pCArray->apCell[i];
79162 u16 sz = pCArray->szCell[i];
79166 pCell = &pTmp[pCell - aData];
79173 pData -= sz;
79174 put2byte(pCellptr, (pData - aData));
79178 assert( sz==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
79181 if( pCArray->ixNx[k]<=i ){
79183 pSrcEnd = pCArray->apEnd[k];
79187 /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
79189 pPg->nCell = (u16)nCell;
79190 pPg->nOverflow = 0;
79193 put2byte(&aData[hdr+3], pPg->nCell);
79194 put2byte(&aData[hdr+5], pData - aData);
79200 ** The pCArray objects contains pointers to b-tree cells and the cell sizes.
79203 ** will fit), non-zero is returned. Otherwise, if the cells are added
79206 ** Argument pCellptr points to the first entry in the cell-pointer array
79208 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
79210 ** that it is safe to overwrite this part of the cell-pointer array.
79218 ** end of the space required by this page for the cell-pointer area (for
79219 ** all cells - not just those inserted by the current call). If the content
79221 ** cells in apCell[], then the cells do not fit and non-zero is returned.
79225 u8 *pBegin, /* End of cell-pointer array */
79226 u8 **ppData, /* IN/OUT: Page content-area pointer */
79227 u8 *pCellptr, /* Pointer to cell-pointer area */
79232 int i = iFirst; /* Loop counter - cell index to insert */
79233 u8 *aData = pPg->aData; /* Complete page */
79236 int k; /* Current slot in pCArray->apEnd[] */
79238 assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
79240 assert( pCArray->ixNx[NB*2-1]>i );
79241 for(k=0; pCArray->ixNx[k]<=i ; k++){}
79242 pEnd = pCArray->apEnd[k];
79246 assert( pCArray->szCell[i]!=0 );
79247 sz = pCArray->szCell[i];
79249 if( (pData - pBegin)<sz ) return 1;
79250 pData -= sz;
79253 /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
79256 assert( (pSlot+sz)<=pCArray->apCell[i]
79257 || pSlot>=(pCArray->apCell[i]+sz)
79259 if( (uptr)(pCArray->apCell[i]+sz)>(uptr)pEnd
79260 && (uptr)(pCArray->apCell[i])<(uptr)pEnd
79266 memmove(pSlot, pCArray->apCell[i], sz);
79267 put2byte(pCellptr, (pSlot - aData));
79271 if( pCArray->ixNx[k]<=i ){
79273 pEnd = pCArray->apEnd[k];
79281 ** The pCArray object contains pointers to b-tree cells and their sizes.
79284 ** that is currently stored within the body of pPg to the pPg free-list.
79285 ** The cell-pointers and other fields of the page are not updated.
79287 ** This function returns the total number of cells added to the free-list.
79295 u8 * const aData = pPg->aData;
79296 u8 * const pEnd = &aData[pPg->pBt->usableSize];
79297 u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
79306 u8 *pCell = pCArray->apCell[i];
79314 sz = pCArray->szCell[i]; assert( sz>0 );
79315 iOfst = (u16)(pCell - aData);
79329 freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
79342 freeSpace(pPg, aOfst[j], aAfter[j]-aOfst[j]);
79349 ** balanced. The current page, pPg, has pPg->nCell cells starting with
79350 ** pCArray->apCell[iOld]. After balancing, this page should hold nNew cells
79356 ** The pPg->nFree field is invalid when this function returns. It is the
79366 u8 * const aData = pPg->aData;
79367 const int hdr = pPg->hdrOffset;
79368 u8 *pBegin = &pPg->aCellIdx[nNew * 2];
79369 int nCell = pPg->nCell; /* Cells stored on pPg */
79373 int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
79377 u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
79378 memcpy(pTmp, aData, pPg->pBt->usableSize);
79384 int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
79386 memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
79387 nCell -= nShift;
79390 int nTail = pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
79392 nCell -= nTail;
79397 if( NEVER(pData>pPg->aDataEnd) ) goto editpage_fail;
79401 int nAdd = MIN(nNew,iOld-iNew);
79402 assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
79404 pCellptr = pPg->aCellIdx;
79414 for(i=0; i<pPg->nOverflow; i++){
79415 int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
79417 pCellptr = &pPg->aCellIdx[iCell * 2];
79419 memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
79432 pCellptr = &pPg->aCellIdx[nCell*2];
79435 iNew+nCell, nNew-nCell, pCArray
79442 pPg->nCell = (u16)nNew;
79443 pPg->nOverflow = 0;
79445 put2byte(&aData[hdr+3], pPg->nCell);
79446 put2byte(&aData[hdr+5], pData - aData);
79450 u8 *pCell = pCArray->apCell[i+iNew];
79451 int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
79452 if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
79453 pCell = &pTmp[pCell - aData];
79456 pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
79472 ** a new entry is being inserted on the extreme right-end of the
79476 ** Instead of trying to balance the 3 right-most leaf pages, just add
79477 ** a new page to the right-hand side and put the one new entry in
79483 ** pPage is the leaf page which is the right-most page in the tree.
79485 ** which is also the right-most entry on the page.
79494 BtShared *const pBt = pPage->pBt; /* B-Tree Database */
79499 assert( sqlite3_mutex_held(pPage->pBt->mutex) );
79500 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
79501 assert( pPage->nOverflow==1 );
79503 if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT; /* dbfuzz001.test */
79504 assert( pPage->nFree>=0 );
79505 assert( pParent->nFree>=0 );
79507 /* Allocate a new page. This page will become the right-sibling of
79516 u8 *pCell = pPage->apOvfl[0];
79517 u16 szCell = pPage->xCellSize(pPage, pCell);
79521 assert( sqlite3PagerIswriteable(pNew->pDbPage) );
79522 assert( CORRUPT_DB || pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
79528 b.apEnd[0] = pPage->aDataEnd;
79530 b.ixNx[NB*2-1] = 0x7fffffff;
79536 pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
79538 /* If this is an auto-vacuum database, update the pointer map
79540 ** cell on the page to an overflow page. If either of these
79544 ** be marked as dirty. Returning an error code will cause a
79548 ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
79549 if( szCell>pNew->minLocal ){
79555 ** consists of a 4-byte page number (the page number of pPage) and
79559 ** To find the largest key value on pPage, first find the right-most
79561 ** record-length (a variable length integer at most 32-bits in size)
79563 ** The first of the while(...) loops below skips over the record-length
79567 pCell = findCell(pPage, pPage->nCell-1);
79575 rc = insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
79576 0, pPage->pgno);
79579 /* Set the right-child pointer of pParent to point to the new page. */
79580 put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
79594 ** for setting pointer-map entries.
79602 BtShared *pBt = pPage->pBt;
79603 assert( pPage->isInit );
79605 for(j=0; j<pPage->nCell; j++){
79610 pPage->xParseCell(pPage, z, &info);
79612 Pgno ovfl = get4byte(&z[info.nSize-4]);
79614 assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
79616 if( !pPage->leaf ){
79619 assert( n==pPage->pgno && e==PTRMAP_BTREE );
79622 if( !pPage->leaf ){
79623 Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
79625 assert( n==pPage->pgno && e==PTRMAP_BTREE );
79633 ** This function is used to copy the contents of the b-tree node stored
79635 ** the pointer-map entries for each child page are updated so that the
79651 BtShared * const pBt = pFrom->pBt;
79652 u8 * const aFrom = pFrom->aData;
79653 u8 * const aTo = pTo->aData;
79654 int const iFromHdr = pFrom->hdrOffset;
79655 int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
79660 assert( pFrom->isInit );
79661 assert( pFrom->nFree>=iToHdr );
79662 assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
79664 /* Copy the b-tree node content from page pFrom to page pTo. */
79666 memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
79667 memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
79674 pTo->isInit = 0;
79682 /* If this is an auto-vacuum database, update the pointer-map entries
79683 ** for any b-tree or overflow pages that pTo now contains the pointers to.
79702 ** one or two in an effort to keep pages nearly full but not over full.
79724 ** size of a cell stored within an internal node is always less than 1/4
79725 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
79734 u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
79735 int isRoot, /* True if pParent is a root-page */
79743 int nxDiv; /* Next divider slot in pParent->aCell[] */
79748 int pageFlags; /* Value of pPage->aData[0] */
79754 u8 *pRight; /* Location in parent of right-sibling pointer */
79755 u8 *apDiv[NB-1]; /* Divider cells in pParent */
79756 int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
79758 int szNew[NB+2]; /* Combined size of cells placed on i-th page */
79766 assert( sizeof(b) - sizeof(b.ixNx) == offsetof(CellArray,ixNx) );
79767 memset(&b, 0, sizeof(b)-sizeof(b.ixNx[0]));
79768 b.ixNx[NB*2-1] = 0x7fffffff;
79769 pBt = pParent->pBt;
79770 assert( sqlite3_mutex_held(pBt->mutex) );
79771 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
79778 assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
79779 assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
79784 assert( pParent->nFree>=0 );
79787 ** that divide the siblings. An attempt is made to find NN siblings on
79797 i = pParent->nOverflow + pParent->nCell;
79805 nxDiv = i-2+bBulk;
79807 nxDiv = iParentIdx-1;
79809 i = 2-bBulk;
79812 if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
79813 pRight = &pParent->aData[pParent->hdrOffset+8];
79815 pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
79826 if( apOld[i]->nFree<0 ){
79833 nMaxCells += apOld[i]->nCell + ArraySize(pParent->apOvfl);
79834 if( (i--)==0 ) break;
79836 if( pParent->nOverflow && i+nxDiv==pParent->aiOvfl[0] ){
79837 apDiv[i] = pParent->apOvfl[0];
79839 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
79840 pParent->nOverflow = 0;
79842 apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
79844 szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
79853 ** But not if we are in secure-delete mode. In secure-delete mode,
79858 if( pBt->btsFlags & BTS_FAST_SECURE ){
79863 iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
79864 if( (iOff+szNew[i])<=(int)pBt->usableSize ){
79866 apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
79869 dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
79873 /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
79883 + pBt->pageSize; /* aSpace1 */
79885 assert( szScratch<=7*(int)pBt->pageSize );
79912 leafCorrection = b.pRef->leaf*4;
79913 leafData = b.pRef->intKeyLeaf;
79916 int limit = pOld->nCell;
79917 u8 *aData = pOld->aData;
79918 u16 maskPage = pOld->maskPage;
79919 u8 *piCell = aData + pOld->cellOffset;
79923 /* Verify that all sibling pages are of the same "type" (table-leaf,
79924 ** table-interior, index-leaf, or index-interior).
79926 if( pOld->aData[0]!=apOld[0]->aData[0] ){
79939 ** adjacent and are inserted in order. There is an assert() tagged
79948 memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
79949 if( pOld->nOverflow>0 ){
79950 if( NEVER(limit<pOld->aiOvfl[0]) ){
79954 limit = pOld->aiOvfl[0];
79960 for(k=0; k<pOld->nOverflow; k++){
79961 assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
79962 b.apCell[b.nCell] = pOld->apOvfl[k];
79966 piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
79973 assert( (b.nCell-nCellAtStart)==(pOld->nCell+pOld->nOverflow) );
79976 if( i<nOld-1 && !leafData){
79983 assert( sz<=pBt->maxLocal+23 );
79984 assert( iSpace1 <= (int)pBt->pageSize );
79988 b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
79989 if( !pOld->leaf ){
79991 assert( pOld->hdrOffset==0 || CORRUPT_DB );
79994 memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
80001 assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
80013 ** size of all cells on the i-th page and cntNew[] which is the index
80020 ** szNew[i]: Spaced used on the i-th sibling page.
80022 ** the right of the i-th sibling page.
80026 usableSpace = pBt->usableSize - 12 + leafCorrection;
80029 b.apEnd[k] = p->aDataEnd;
80031 if( k && b.ixNx[k]==b.ixNx[k-1] ){
80032 k--; /* Omit b.ixNx[] entry for child pages with no cells */
80036 b.apEnd[k] = pParent->aDataEnd;
80039 assert( p->nFree>=0 );
80040 szNew[i] = usableSpace - p->nFree;
80041 for(j=0; j<p->nOverflow; j++){
80042 szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
80053 szNew[k-1] = 0;
80054 cntNew[k-1] = b.nCell;
80056 sz = 2 + cachedCellSize(&b, cntNew[i]-1);
80057 szNew[i] -= sz;
80066 cntNew[i]--;
80080 szNew[i+1] -= sz;
80084 }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
80093 ** always nearly full, while the right-most sibling might be nearly empty.
80097 ** This adjustment is more than an optimization. The packing above might
80098 ** be so out of balance as to be illegal. For example, the right-most
80101 for(i=k-1; i>0; i--){
80103 int szLeft = szNew[i-1]; /* Size of sibling on the left */
80104 int r; /* Index of right-most cell in left sibling */
80107 r = cntNew[i-1] - 1;
80108 d = r + 1 - leafData;
80117 && (bBulk || szRight+szD+2 > szLeft-(szR+(i==k-1?0:2)))){
80121 szLeft -= szR + 2;
80122 cntNew[i-1] = r;
80123 r--;
80124 d--;
80127 szNew[i-1] = szLeft;
80128 if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
80134 /* Sanity check: For a non-corrupt database file one of the following
80141 assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
80143 apOld[0]->pgno, apOld[0]->nCell,
80144 nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
80145 nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
80151 pageFlags = apOld[0]->aData[0];
80157 rc = sqlite3PagerWrite(pNew->pDbPage);
80159 if( sqlite3PagerPageRefcount(pNew->pDbPage)!=1+(i==(iParentIdx-nxDiv))
80174 /* Set the pointer-map entry for the new sibling page. */
80176 ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
80190 ** An O(N*N) sort algorithm is used, but since N is never more than NB+2
80197 aPgno[i] = apNew[i]->pgno;
80198 assert( apNew[i]->pDbPage->flags & PGHDR_WRITEABLE );
80199 assert( apNew[i]->pDbPage->flags & PGHDR_DIRTY );
80201 for(i=0; i<nNew-1; i++){
80204 if( apNew[j]->pgno < apNew[iB]->pgno ) iB = j;
80213 Pgno pgnoA = apNew[i]->pgno;
80214 Pgno pgnoB = apNew[iB]->pgno;
80215 Pgno pgnoTemp = (PENDING_BYTE/pBt->pageSize)+1;
80216 u16 fgA = apNew[i]->pDbPage->flags;
80217 u16 fgB = apNew[iB]->pDbPage->flags;
80218 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoTemp, fgB);
80219 sqlite3PagerRekey(apNew[iB]->pDbPage, pgnoA, fgA);
80220 sqlite3PagerRekey(apNew[i]->pDbPage, pgnoB, fgB);
80221 apNew[i]->pgno = pgnoB;
80222 apNew[iB]->pgno = pgnoA;
80228 apNew[0]->pgno, szNew[0], cntNew[0],
80229 nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
80230 nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
80231 nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
80232 nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
80233 nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
80234 nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
80235 nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
80236 nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
80239 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
80241 assert( apNew[nNew-1]!=0 );
80242 put4byte(pRight, apNew[nNew-1]->pgno);
80244 /* If the sibling pages are not leaves, ensure that the right-child pointer
80245 ** of the right-most new sibling page is set to the value that was
80246 ** originally in the same field of the right-most old sibling page. */
80248 MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
80249 memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
80257 ** a) if the cell contains a reference to an overflow chain, the
80264 ** associated with the right-child of each sibling may also need to be
80271 int cntOldNext = pNew->nCell + pNew->nOverflow;
80282 cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
80290 ** was either part of sibling page iOld (possibly an overflow cell),
80296 || pNew->pgno!=aPgno[iOld]
80297 || !SQLITE_WITHIN(pCell,pOld->aData,pOld->aDataEnd)
80300 ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
80302 if( cachedCellSize(&b,i)>pNew->minLocal ){
80311 for(i=0; i<nNew-1; i++){
80324 if( !pNew->leaf ){
80325 memcpy(&pNew->aData[8], pCell, 4);
80327 /* If the tree is a leaf-data tree, and the siblings are leaves,
80329 ** cell consists of the integer key for the right-most cell of
80330 ** the sibling-page assembled above only.
80333 j--;
80334 pNew->xParseCell(pNew, b.apCell[j], &info);
80339 pCell -= 4;
80340 /* Obscure case for non-leaf-data trees: If the cell at pCell was
80347 ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
80353 sz = pParent->xCellSize(pParent, pCell);
80357 assert( sz<=pBt->maxLocal+23 );
80358 assert( iOvflSpace <= (int)pBt->pageSize );
80359 assert( b.ixNx[NB*2-1]>j );
80366 rc = insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno);
80368 assert( sqlite3PagerIswriteable(pParent->pDbPage) );
80375 ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
80377 ** the left-hand sibling apNew[iPg-1] has been updated.
80381 ** the right-hand sibling apNew[iPg+1] has been updated.
80385 ** The iPg value in the following loop starts at nNew-1 goes down
80386 ** to 0, then back up to nNew-1 again, thus making two passes over
80393 for(i=1-nNew; i<nNew; i++){
80394 int iPg = i<0 ? -i : i;
80400 || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
80407 ** only after iPg-1 has already been updated. */
80408 assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
80418 iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
80419 iNew = cntNew[iPg-1] + !leafData;
80420 nNewCell = cntNew[iPg] - iNew;
80426 apNew[iPg]->nFree = usableSpace-szNew[iPg];
80427 assert( apNew[iPg]->nOverflow==0 );
80428 assert( apNew[iPg]->nCell==nNewCell );
80438 if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
80439 /* The root page of the b-tree now contains no cells. The only sibling
80440 ** page is the right-child of the parent. Copy the contents of the
80442 ** b-tree structure by one. This is described as the "balance-shallower"
80443 ** sub-algorithm in some documentation.
80445 ** If this is an auto-vacuum database, the call to copyNodeContent()
80446 ** sets all pointer-map entries corresponding to database image pages
80455 rc = defragmentPage(apNew[0], -1);
80457 assert( apNew[0]->nFree ==
80458 (get2byteNotZero(&apNew[0]->aData[5]) - apNew[0]->cellOffset
80459 - apNew[0]->nCell*2)
80465 /* Fix the pointer map entries associated with the right-child of each
80469 u32 key = get4byte(&apNew[i]->aData[8]);
80470 ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
80474 assert( pParent->isInit );
80485 if( ISAUTOVACUUM(pBt) && rc==SQLITE_OK && apNew[0]->isInit ){
80489 ** cause an assert() statement to fail. */
80512 ** This function is called when the root page of a b-tree structure is
80517 ** page is then overwritten to make it an empty page with the right-child
80520 ** Before returning, all pointer-map entries corresponding to pages
80521 ** that the new child-page now contains pointers to are updated. The
80522 ** entry corresponding to the new right-child pointer of the root
80527 ** to call releasePage() on *ppChild exactly once. If an error occurs,
80528 ** an error code is returned and *ppChild is set to 0.
80534 BtShared *pBt = pRoot->pBt; /* The BTree */
80536 assert( pRoot->nOverflow>0 );
80537 assert( sqlite3_mutex_held(pBt->mutex) );
80539 /* Make pRoot, the root page of the b-tree, writable. Allocate a new
80540 ** page that will become the new right-child of pPage. Copy the contents
80543 rc = sqlite3PagerWrite(pRoot->pDbPage);
80545 rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
80548 ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
80556 assert( sqlite3PagerIswriteable(pChild->pDbPage) );
80557 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
80558 assert( pChild->nCell==pRoot->nCell || CORRUPT_DB );
80560 TRACE(("BALANCE: copy root %u into %u\n", pRoot->pgno, pChild->pgno));
80563 memcpy(pChild->aiOvfl, pRoot->aiOvfl,
80564 pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
80565 memcpy(pChild->apOvfl, pRoot->apOvfl,
80566 pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
80567 pChild->nOverflow = pRoot->nOverflow;
80569 /* Zero the contents of pRoot. Then install pChild as the right-child. */
80570 zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
80571 put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
80579 ** on the same B-tree as pCur.
80582 ** pointing to the same b-tree. If an insert occurs on one SQL table
80584 ** table linked to the same b-tree. If the secondary insert causes a
80590 for(pOther=pCur->pBt->pCursor; pOther; pOther=pOther->pNext){
80592 && pOther->eState==CURSOR_VALID
80593 && pOther->pPage==pCur->pPage
80595 return SQLITE_CORRUPT_PAGE(pCur->pPage);
80621 MemPage *pPage = pCur->pPage;
80623 if( NEVER(pPage->nFree<0) && btreeComputeFreeSpace(pPage) ) break;
80624 if( pPage->nOverflow==0 && pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
80630 }else if( (iPage = pCur->iPage)==0 ){
80631 if( pPage->nOverflow && (rc = anotherValidCursor(pCur))==SQLITE_OK ){
80632 /* The root page of the b-tree is overfull. In this case call the
80633 ** balance_deeper() function to create a new child for the root-page
80634 ** and copy the current contents of the root-page to it. The
80635 ** next iteration of the do-loop will balance the child page.
80639 rc = balance_deeper(pPage, &pCur->apPage[1]);
80641 pCur->iPage = 1;
80642 pCur->ix = 0;
80643 pCur->aiIdx[0] = 0;
80644 pCur->apPage[0] = pPage;
80645 pCur->pPage = pCur->apPage[1];
80646 assert( pCur->pPage->nOverflow );
80651 }else if( sqlite3PagerPageRefcount(pPage->pDbPage)>1 ){
80657 MemPage * const pParent = pCur->apPage[iPage-1];
80658 int const iIdx = pCur->aiIdx[iPage-1];
80660 rc = sqlite3PagerWrite(pParent->pDbPage);
80661 if( rc==SQLITE_OK && pParent->nFree<0 ){
80666 if( pPage->intKeyLeaf
80667 && pPage->nOverflow==1
80668 && pPage->aiOvfl[0]==pPage->nCell
80669 && pParent->pgno!=1
80670 && pParent->nCell==iIdx
80675 ** happens, the next iteration of the do-loop will balance pParent
80694 ** become overfull or underfull. The next iteration of the do-loop
80699 ** A subsequent iteration of the do-loop will deal with this by
80701 ** but it doesn't deal with overflow cells - just moves them to a
80708 u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
80710 pCur->hints&BTREE_BULKLOAD);
80726 pPage->nOverflow = 0;
80728 /* The next iteration of the do-loop balances the parent page. */
80730 pCur->iPage--;
80731 assert( pCur->iPage>=0 );
80732 pCur->pPage = pCur->apPage[pCur->iPage];
80752 int nData = pX->nData - iOffset;
80758 int rc = sqlite3PagerWrite(pPage->pDbPage);
80760 memset(pDest + i, 0, iAmt - i);
80767 iAmt-nData);
80771 if( memcmp(pDest, ((u8*)pX->pData) + iOffset, iAmt)!=0 ){
80772 int rc = sqlite3PagerWrite(pPage->pDbPage);
80778 memmove(pDest, ((u8*)pX->pData) + iOffset, iAmt);
80786 ** contained in pX. In this variant, pCur is pointing to an overflow
80793 int iOffset; /* Next byte of pX->pData to write */
80794 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
80796 MemPage *pPage = pCur->pPage; /* Page being written */
80801 assert( pCur->info.nLocal<nTotal ); /* pCur is an overflow cell */
80804 rc = btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
80805 0, pCur->info.nLocal);
80809 iOffset = pCur->info.nLocal;
80812 ovflPgno = get4byte(pCur->info.pPayload + iOffset);
80813 pBt = pPage->pBt;
80814 ovflPageSize = pBt->usableSize - 4;
80818 if( sqlite3PagerPageRefcount(pPage->pDbPage)!=1 || pPage->isInit ){
80822 ovflPgno = get4byte(pPage->aData);
80824 ovflPageSize = nTotal - iOffset;
80826 rc = btreeOverwriteContent(pPage, pPage->aData+4, pX,
80829 sqlite3PagerUnref(pPage->pDbPage);
80841 int nTotal = pX->nData + pX->nZero; /* Total bytes of to write */
80842 MemPage *pPage = pCur->pPage; /* Page being written */
80844 if( pCur->info.pPayload + pCur->info.nLocal > pPage->aDataEnd
80845 || pCur->info.pPayload < pPage->aData + pPage->cellOffset
80849 if( pCur->info.nLocal==nTotal ){
80851 return btreeOverwriteContent(pPage, pCur->info.pPayload, pX,
80852 0, pCur->info.nLocal);
80871 ** For an index btree (used for indexes and WITHOUT ROWID tables), the
80872 ** key is an arbitrary byte sequence stored in pX.pKey,nKey. The
80875 ** If the seekResult parameter is non-zero, then a successful call to
80886 ** if pX->nMem is non-zero, then pX->aMem contains pointers to the unpacked
80887 ** key values and pX->aMem can be used instead of pX->pKey to avoid having
80893 int flags, /* True if this is likely an append */
80897 int loc = seekResult; /* -1: before desired location +1: after */
80901 Btree *p = pCur->pBtree;
80906 assert( (flags & BTREE_PREFORMAT)==0 || seekResult || pCur->pKeyInfo==0 );
80910 ** In some cases, the call to btreeMoveto() below is a no-op. For
80911 ** example, when inserting data into a table with auto-generated integer
80914 ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
80919 if( pCur->curFlags & BTCF_Multiple ){
80920 rc = saveAllCursors(p->pBt, pCur->pgnoRoot, pCur);
80922 if( loc && pCur->iPage<0 ){
80928 return SQLITE_CORRUPT_PGNO(pCur->pgnoRoot);
80935 if( pCur->eState>=CURSOR_REQUIRESEEK ){
80936 testcase( pCur->eState==CURSOR_REQUIRESEEK );
80937 testcase( pCur->eState==CURSOR_FAULT );
80943 assert( (pCur->curFlags & BTCF_WriteFlag)!=0
80944 && p->pBt->inTransaction==TRANS_WRITE
80945 && (p->pBt->btsFlags & BTS_READ_ONLY)==0 );
80946 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
80949 ** expecting an index b-tree, then the caller should be inserting blob
80950 ** keys with no associated data. If the cursor was opened expecting an
80953 assert( (flags & BTREE_PREFORMAT) || (pX->pKey==0)==(pCur->pKeyInfo==0) );
80955 if( pCur->pKeyInfo==0 ){
80956 assert( pX->pKey==0 );
80957 /* If this is an insert into a table b-tree, invalidate any incrblob
80959 if( p->hasIncrblobCur ){
80960 invalidateIncrblobCursors(p, pCur->pgnoRoot, pX->nKey, 0);
80968 assert( pCur->curFlags & BTCF_ValidNKey );
80969 assert( pX->nKey==pCur->info.nKey );
80978 if( (pCur->curFlags&BTCF_ValidNKey)!=0 && pX->nKey==pCur->info.nKey ){
80981 assert( pX->nData>=0 && pX->nZero>=0 );
80982 if( pCur->info.nSize!=0
80983 && pCur->info.nPayload==(u32)pX->nData+pX->nZero
80985 /* New entry is the same size as the old. Do an overwrite */
80991 ** to an adjacent cell. Move the cursor so that it is pointing either
80992 ** to the cell to be overwritten or an adjacent cell.
80994 rc = sqlite3BtreeTableMoveto(pCur, pX->nKey,
80999 /* This is an index or a WITHOUT ROWID table */
81008 ** not pointing to an immediately adjacent cell, then move the cursor
81012 if( pX->nMem ){
81014 r.pKeyInfo = pCur->pKeyInfo;
81015 r.aMem = pX->aMem;
81016 r.nField = pX->nMem;
81021 rc = btreeMoveto(pCur, pX->pKey, pX->nKey,
81027 /* If the cursor is currently pointing to an entry to be overwritten
81033 if( pCur->info.nKey==pX->nKey ){
81035 x2.pData = pX->pKey;
81036 x2.nData = (int)pX->nKey; assert( pX->nKey<=0x7fffffff );
81042 assert( pCur->eState==CURSOR_VALID
81043 || (pCur->eState==CURSOR_INVALID && loc) || CORRUPT_DB );
81045 pPage = pCur->pPage;
81046 assert( pPage->intKey || pX->nKey>=0 || (flags & BTREE_PREFORMAT) );
81047 assert( pPage->leaf || !pPage->intKey );
81048 if( pPage->nFree<0 ){
81049 if( NEVER(pCur->eState>CURSOR_INVALID) ){
81050 /* ^^^^^--- due to the moveToRoot() call above */
81059 pCur->pgnoRoot, pX->nKey, pX->nData, pPage->pgno,
81061 assert( pPage->isInit || CORRUPT_DB );
81062 newCell = p->pBt->pTmpSpace;
81067 szNew = p->pBt->nPreformatSize;
81072 if( ISAUTOVACUUM(p->pBt) && szNew>pPage->maxLocal ){
81074 pPage->xParseCell(pPage, newCell, &info);
81076 Pgno ovfl = get4byte(&newCell[szNew-4]);
81077 ptrmapPut(p->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, &rc);
81085 assert( szNew==pPage->xCellSize(pPage, newCell) );
81086 assert( szNew <= MX_CELL_SIZE(p->pBt) );
81087 idx = pCur->ix;
81088 pCur->info.nSize = 0;
81092 if( idx>=pPage->nCell ){
81095 rc = sqlite3PagerWrite(pPage->pDbPage);
81100 if( !pPage->leaf ){
81104 testcase( pCur->curFlags & BTCF_ValidOvfl );
81107 && (!ISAUTOVACUUM(p->pBt) || szNew<pPage->minLocal)
81115 ** This optimization cannot be used on an autovacuum database if the
81117 ** necessary to add the PTRMAP_OVERFLOW1 pointer-map entry. */
81119 if( oldCell < pPage->aData+pPage->hdrOffset+10 ){
81122 if( oldCell+szNew > pPage->aDataEnd ){
81130 }else if( loc<0 && pPage->nCell>0 ){
81131 assert( pPage->leaf );
81132 idx = ++pCur->ix;
81133 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
81135 assert( pPage->leaf );
81138 assert( pPage->nOverflow==0 || rc==SQLITE_OK );
81139 assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
81141 /* If no error has occurred and pPage has an overflow cell, call balance()
81153 ** multiple records into an intkey b-tree using a single cursor (as can
81154 ** happen while processing an "INSERT INTO ... SELECT" statement), it
81156 ** the b-tree if possible. If the cursor is left pointing to the last
81157 ** entry in the table, and the next row inserted has an integer key
81161 if( pPage->nOverflow ){
81163 pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
81170 pCur->pPage->nOverflow = 0;
81171 pCur->eState = CURSOR_INVALID;
81174 if( pCur->pKeyInfo ){
81175 assert( pCur->pKey==0 );
81176 pCur->pKey = sqlite3Malloc( pX->nKey );
81177 if( pCur->pKey==0 ){
81180 memcpy(pCur->pKey, pX->pKey, pX->nKey);
81183 pCur->eState = CURSOR_REQUIRESEEK;
81184 pCur->nKey = pX->nKey;
81187 assert( pCur->iPage<0 || pCur->pPage->nOverflow==0 );
81206 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
81209 BtShared *pBt = pDest->pBt;
81210 u8 *aOut = pBt->pTmpSpace; /* Pointer to next output buffer */
81216 if( pSrc->info.nPayload<0x80 ){
81217 *(aOut++) = (u8)pSrc->info.nPayload;
81219 aOut += sqlite3PutVarint(aOut, pSrc->info.nPayload);
81221 if( pDest->pKeyInfo==0 ) aOut += putVarint(aOut, iKey);
81222 nIn = pSrc->info.nLocal;
81223 aIn = pSrc->info.pPayload;
81224 if( aIn+nIn>pSrc->pPage->aDataEnd ){
81225 return SQLITE_CORRUPT_PAGE(pSrc->pPage);
81227 nRem = pSrc->info.nPayload;
81228 if( nIn==nRem && nIn<pDest->pPage->maxLocal ){
81230 pBt->nPreformatSize = nIn + (int)(aOut - pBt->pTmpSpace);
81234 Pager *pSrcPager = pSrc->pBt->pPager;
81241 nOut = btreePayloadToLocal(pDest->pPage, pSrc->info.nPayload);
81242 pBt->nPreformatSize = (int)nOut + (int)(aOut - pBt->pTmpSpace);
81243 if( nOut<pSrc->info.nPayload ){
81245 pBt->nPreformatSize += 4;
81249 if( aIn+nIn+4>pSrc->pPage->aDataEnd ){
81250 return SQLITE_CORRUPT_PAGE(pSrc->pPage);
81252 ovflIn = get4byte(&pSrc->info.pPayload[nIn]);
81256 nRem -= nOut;
81262 nOut -= nCopy;
81263 nIn -= nCopy;
81275 nIn = pSrc->pBt->usableSize - 4;
81286 ptrmapPut(pBt, pgnoNew, PTRMAP_OVERFLOW2, pPageOut->pgno, &rc);
81291 pPgnoOut = pPageOut->aData;
81294 nOut = MIN(pBt->usableSize - 4, nRem);
81309 ** the cursor is left pointing at an arbitrary location after the delete.
81318 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
81323 Btree *p = pCur->pBtree;
81324 BtShared *pBt = p->pBt;
81334 assert( pBt->inTransaction==TRANS_WRITE );
81335 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
81336 assert( pCur->curFlags & BTCF_WriteFlag );
81337 assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
81338 assert( !hasReadConflicts(p, pCur->pgnoRoot) );
81340 if( pCur->eState!=CURSOR_VALID ){
81341 if( pCur->eState>=CURSOR_REQUIRESEEK ){
81343 assert( rc!=SQLITE_OK || CORRUPT_DB || pCur->eState==CURSOR_VALID );
81344 if( rc || pCur->eState!=CURSOR_VALID ) return rc;
81346 return SQLITE_CORRUPT_PGNO(pCur->pgnoRoot);
81349 assert( pCur->eState==CURSOR_VALID );
81351 iCellDepth = pCur->iPage;
81352 iCellIdx = pCur->ix;
81353 pPage = pCur->pPage;
81354 if( pPage->nCell<=iCellIdx ){
81358 if( pPage->nFree<0 && btreeComputeFreeSpace(pPage) ){
81361 if( pCell<&pPage->aCellIdx[pPage->nCell] ){
81367 ** will cause a b-tree rebalance, then this is done by saving the cursor
81383 if( !pPage->leaf
81384 || (pPage->nFree+pPage->xCellSize(pPage,pCell)+2) >
81385 (int)(pBt->usableSize*2/3)
81386 || pPage->nCell==1 /* See dbfuzz001.test for a test case */
81388 /* A b-tree rebalance will be required after deleting this entry.
81402 ** sub-tree headed by the child page of the cell being deleted. This makes
81404 if( !pPage->leaf ){
81412 if( pCur->curFlags & BTCF_Multiple ){
81413 rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
81417 /* If this is a delete operation to remove a row from a table b-tree,
81419 if( pCur->pKeyInfo==0 && p->hasIncrblobCur ){
81420 invalidateIncrblobCursors(p, pCur->pgnoRoot, pCur->info.nKey, 0);
81426 rc = sqlite3PagerWrite(pPage->pDbPage);
81433 ** is currently pointing to the largest entry in the sub-tree headed
81434 ** by the child-page of the cell that was just deleted from an internal
81437 if( !pPage->leaf ){
81438 MemPage *pLeaf = pCur->pPage;
81443 if( pLeaf->nFree<0 ){
81447 if( iCellDepth<pCur->iPage-1 ){
81448 n = pCur->apPage[iCellDepth+1]->pgno;
81450 n = pCur->pPage->pgno;
81452 pCell = findCell(pLeaf, pLeaf->nCell-1);
81453 if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_PAGE(pLeaf);
81454 nCell = pLeaf->xCellSize(pLeaf, pCell);
81456 pTmp = pBt->pTmpSpace;
81458 rc = sqlite3PagerWrite(pLeaf->pDbPage);
81460 rc = insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n);
81462 dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
81471 ** Otherwise, if the entry deleted was on an internal node page, then
81481 assert( pCur->pPage->nOverflow==0 );
81482 assert( pCur->pPage->nFree>=0 );
81483 if( pCur->pPage->nFree*3<=(int)pCur->pBt->usableSize*2 ){
81485 ** then balance() will always be a no-op. No need to invoke it. */
81490 if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
81491 releasePageNotNull(pCur->pPage);
81492 pCur->iPage--;
81493 while( pCur->iPage>iCellDepth ){
81494 releasePage(pCur->apPage[pCur->iPage--]);
81496 pCur->pPage = pCur->apPage[pCur->iPage];
81502 assert( (pCur->iPage==iCellDepth || CORRUPT_DB) );
81503 assert( pPage==pCur->pPage || CORRUPT_DB );
81504 assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
81505 pCur->eState = CURSOR_SKIPNEXT;
81506 if( iCellIdx>=pPage->nCell ){
81507 pCur->skipNext = -1;
81508 pCur->ix = pPage->nCell-1;
81510 pCur->skipNext = 1;
81516 pCur->eState = CURSOR_REQUIRESEEK;
81536 BtShared *pBt = p->pBt;
81540 int ptfFlags; /* Page-type flags for the root page of new table */
81543 assert( pBt->inTransaction==TRANS_WRITE );
81544 assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
81552 if( pBt->autoVacuum ){
81553 Pgno pgnoMove; /* Move a page here to make room for the root-page */
81556 /* Creating a new table may probably require moving an existing database
81558 ** out to be an overflow page, delete all overflow page-map caches
81564 ** root page of the new table should go. meta[3] is the largest root-page
81565 ** created so far, so the new root-page is (meta[3]+1).
81573 /* The new root-page may not be allocated on a pointer-map page, or the
81592 /* pgnoRoot is the page that will be used for the root-page of
81593 ** the new table (assuming an error did not occur). But we were
81602 ** case they are holding a reference to an xFetch reference
81636 rc = sqlite3PagerWrite(pRoot->pDbPage);
81645 /* Update the pointer-map and meta-data with the new root-page number. */
81656 assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
81668 assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
81675 sqlite3PagerUnref(pRoot->pDbPage);
81676 assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
81705 assert( sqlite3_mutex_held(pBt->mutex) );
81711 if( (pBt->openFlags & BTREE_SINGLE)==0
81712 && sqlite3PagerPageRefcount(pPage->pDbPage) != (1 + (pgno==1))
81717 hdr = pPage->hdrOffset;
81718 for(i=0; i<pPage->nCell; i++){
81720 if( !pPage->leaf ){
81727 if( !pPage->leaf ){
81728 rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
81730 if( pPage->intKey ) pnChange = 0;
81733 testcase( !pPage->intKey );
81734 *pnChange += pPage->nCell;
81738 }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
81739 zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
81761 BtShared *pBt = p->pBt;
81763 assert( p->inTrans==TRANS_WRITE );
81769 ** is the root of a table b-tree - if it is not, the following call is
81770 ** a no-op). */
81771 if( p->hasIncrblobCur ){
81783 ** This routine only work for pCur on an ephemeral table.
81786 return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
81812 BtShared *pBt = p->pBt;
81815 assert( p->inTrans==TRANS_WRITE );
81835 if( pBt->autoVacuum ){
81840 /* If the table being dropped is the table with the largest root-page
81849 /* The table being dropped does not have the largest root-page
81851 ** gap left by the deleted root-page.
81874 /* Set the new 'max-root-page' value in the database header. This
81876 ** be a root-page number, less one again if that is the
81879 maxRootPgno--;
81882 maxRootPgno--;
81904 ** This function may only be called if the b-tree connection already
81907 ** Read the meta-information out of a database file. Meta[0]
81910 ** is read-only, the others are read/write.
81924 BtShared *pBt = p->pBt;
81927 assert( p->inTrans>TRANS_NONE );
81929 assert( pBt->pPage1 );
81933 *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iBDataVersion;
81935 *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
81938 /* If auto-vacuum is disabled in this build and this is an auto-vacuum
81939 ** database, mark the database as read-only. */
81942 pBt->btsFlags |= BTS_READ_ONLY;
81950 ** Write meta-information back into the database. Meta[0] is
81951 ** read-only and may not be written.
81954 BtShared *pBt = p->pBt;
81959 assert( p->inTrans==TRANS_WRITE );
81960 assert( pBt->pPage1!=0 );
81961 pP1 = pBt->pPage1->aData;
81962 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
81967 assert( pBt->autoVacuum || iMeta==0 );
81969 pBt->incrVacuum = (u8)iMeta;
81978 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
81979 ** number of entries in the b-tree and write the result to *pnEntry.
81982 ** Otherwise, if an error is encountered (i.e. an IO error or database
81983 ** corruption) an SQLite error code is returned.
81995 /* Unless an error occurs, the following loop runs one iteration for each
81996 ** page in the B-Tree structure (not including overflow pages).
81998 while( rc==SQLITE_OK && !AtomicLoad(&db->u1.isInterrupted) ){
82000 MemPage *pPage; /* Current page of the b-tree */
82002 /* If this is a leaf page or the tree is not an int-key tree, then
82006 pPage = pCur->pPage;
82007 if( pPage->leaf || !pPage->intKey ){
82008 nEntry += pPage->nCell;
82014 ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
82016 ** to visit is the right-child of its parent.
82021 if( pPage->leaf ){
82023 if( pCur->iPage==0 ){
82024 /* All pages of the b-tree have been visited. Return successfully. */
82029 }while ( pCur->ix>=pCur->pPage->nCell );
82031 pCur->ix++;
82032 pPage = pCur->pPage;
82036 ** points at. This is the right-child if (iIdx==pPage->nCell).
82038 iIdx = pCur->ix;
82039 if( iIdx==pPage->nCell ){
82040 rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
82046 /* An error has occurred. Return an error code. */
82055 return p->pBt->pPager;
82060 ** Record an OOM error during integrity_check
82063 pCheck->rc = SQLITE_NOMEM;
82064 pCheck->mxErr = 0; /* Causes integrity_check processing to stop */
82065 if( pCheck->nErr==0 ) pCheck->nErr++;
82069 ** Invoke the progress handler, if appropriate. Also check for an
82073 sqlite3 *db = pCheck->db;
82074 if( AtomicLoad(&db->u1.isInterrupted) ){
82075 pCheck->rc = SQLITE_INTERRUPT;
82076 pCheck->nErr++;
82077 pCheck->mxErr = 0;
82080 if( db->xProgress ){
82081 assert( db->nProgressOps>0 );
82082 pCheck->nStep++;
82083 if( (pCheck->nStep % db->nProgressOps)==0
82084 && db->xProgress(db->pProgressArg)
82086 pCheck->rc = SQLITE_INTERRUPT;
82087 pCheck->nErr++;
82088 pCheck->mxErr = 0;
82104 if( !pCheck->mxErr ) return;
82105 pCheck->mxErr--;
82106 pCheck->nErr++;
82108 if( pCheck->errMsg.nChar ){
82109 sqlite3_str_append(&pCheck->errMsg, "\n", 1);
82111 if( pCheck->zPfx ){
82112 sqlite3_str_appendf(&pCheck->errMsg, pCheck->zPfx,
82113 pCheck->v0, pCheck->v1, pCheck->v2);
82115 sqlite3_str_vappendf(&pCheck->errMsg, zFormat, ap);
82117 if( pCheck->errMsg.accError==SQLITE_NOMEM ){
82126 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
82130 assert( pCheck->aPgRef!=0 );
82131 assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 );
82132 return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
82139 assert( pCheck->aPgRef!=0 );
82140 assert( iPg<=pCheck->nCkPage && sizeof(pCheck->aPgRef[0])==1 );
82141 pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
82147 ** reference to the page, add an error message to pCheck->zErrMsg.
82154 if( iPage>pCheck->nCkPage || iPage==0 ){
82168 ** Check that the entry in the pointer-map for page iChild maps to
82169 ** page iParent, pointer type ptrType. If not, append an error message
82182 rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
82198 ** Check the integrity of the freelist or of an overflow page list.
82209 int nErrAtStart = pCheck->nErr;
82210 while( iPage!=0 && pCheck->mxErr ){
82214 N--;
82215 if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
82223 if( pCheck->pBt->autoVacuum ){
82227 if( n>pCheck->pBt->usableSize/4-2 ){
82230 N--;
82235 if( pCheck->pBt->autoVacuum ){
82241 N -= n;
82246 /* If this database supports auto-vacuum and iPage is not the last
82247 ** page in this overflow list, check that the pointer-map entry for
82250 if( pCheck->pBt->autoVacuum && N>0 ){
82259 if( N && nErrAtStart==pCheck->nErr ){
82263 expected-N, expected);
82269 ** An implementation of a min-heap.
82279 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
82308 aHeap[0]--;
82345 int depth = -1, d2; /* Depth of a subtree */
82361 u32 *heap = 0; /* Min-heap used for checking cell coverage */
82362 u32 x, prev = 0; /* Next and previous entry on the min-heap */
82363 const char *saved_zPfx = pCheck->zPfx;
82364 int saved_v1 = pCheck->v1;
82365 int saved_v2 = pCheck->v2;
82371 if( pCheck->mxErr==0 ) goto end_of_check;
82372 pBt = pCheck->pBt;
82373 usableSize = pBt->usableSize;
82376 pCheck->zPfx = "Tree %u page %u: ";
82377 pCheck->v1 = iPage;
82381 if( rc==SQLITE_IOERR_NOMEM ) pCheck->rc = SQLITE_NOMEM;
82387 savedIsInit = pPage->isInit;
82388 pPage->isInit = 0;
82400 data = pPage->aData;
82401 hdr = pPage->hdrOffset;
82404 pCheck->zPfx = "Tree %u page %u cell %u: ";
82408 /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
82411 assert( pPage->nCell==nCell );
82412 if( pPage->leaf || pPage->intKey==0 ){
82413 pCheck->nRow += nCell;
82416 /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
82417 ** immediately follows the b-tree page header. */
82418 cellStart = hdr + 12 - 4*pPage->leaf;
82419 assert( pPage->aCellIdx==&data[cellStart] );
82420 pCellIdx = &data[cellStart + 2*(nCell-1)];
82422 if( !pPage->leaf ){
82423 /* Analyze the right-child page of internal pages */
82426 if( pBt->autoVacuum ){
82427 pCheck->zPfx = "Tree %u page %u right child: ";
82436 heap = pCheck->heap;
82440 /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
82442 for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
82446 pCheck->v2 = i;
82449 pCellIdx -= 2;
82450 if( pc<contentOffset || pc>usableSize-4 ){
82452 pc, contentOffset, usableSize-4);
82457 pPage->xParseCell(pPage, pCell, &info);
82465 if( pPage->intKey ){
82477 assert( pc + info.nSize - 4 <= usableSize );
82478 nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
82479 pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
82481 if( pBt->autoVacuum ){
82488 if( !pPage->leaf ){
82492 if( pBt->autoVacuum ){
82503 /* Populate the coverage-checking heap for leaf pages */
82504 btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
82511 pCheck->zPfx = 0;
82512 if( doCoverageCheck && pCheck->mxErr>0 ){
82513 /* For leaf pages, the min-heap has already been initialized and the
82516 if( !pPage->leaf ){
82517 heap = pCheck->heap;
82519 for(i=nCell-1; i>=0; i--){
82522 size = pPage->xCellSize(pPage, &data[pc]);
82523 btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
82527 /* Add the freeblocks to the min-heap
82529 ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
82536 assert( (u32)i<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
82539 btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
82540 /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
82541 ** big-endian integer which is the offset in the b-tree page of the next
82545 /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
82548 assert( (u32)j<=usableSize-4 ); /* Enforced by btreeComputeFreeSpace() */
82551 /* Analyze the min-heap looking for overlap between cells and/or
82554 ** Each min-heap entry is of the form: (start_address<<16)|end_address.
82555 ** There is an implied first entry the covers the page header, the cell
82559 ** The loop below pulls entries from the min-heap in order and compares
82560 ** the start_address against the previous end_address. If there is an
82565 prev = contentOffset - 1; /* Implied first min-heap entry */
82572 nFrag += (x>>16) - (prev&0xffff) - 1;
82576 nFrag += usableSize - (prev&0xffff) - 1;
82577 /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
82578 ** is stored in the fifth field of the b-tree page header.
82579 ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
82590 if( !doCoverageCheck ) pPage->isInit = savedIsInit;
82592 pCheck->zPfx = saved_zPfx;
82593 pCheck->v1 = saved_v1;
82594 pCheck->v2 = saved_v2;
82602 ** an array of pages numbers were each page number is the root page of
82605 ** A read-only or read-write transaction must be opened before calling
82609 ** allocation errors, an error message held in memory obtained from
82610 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
82614 ** root pages is incomplete. This is a "partial integrity-check". This
82615 ** happens when performing an integrity check on a single table. The
82625 Pgno *aRoot, /* An array of root pages numbers for individual trees */
82634 BtShared *pBt = p->pBt;
82635 u64 savedDbFlags = pBt->db->flags;
82652 assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
82653 VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
82658 sCheck.pPager = pBt->pPager;
82672 sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
82685 checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
82686 get4byte(&pBt->pPage1->aData[36]));
82694 if( pBt->autoVacuum ){
82698 mxInHdr = get4byte(&pBt->pPage1->aData[52]);
82705 }else if( get4byte(&pBt->pPage1->aData[64])!=0 ){
82712 testcase( pBt->db->flags & SQLITE_CellSizeCk );
82713 pBt->db->flags &= ~(u64)SQLITE_CellSizeCk;
82719 if( pBt->autoVacuum && aRoot[i]>1 && !bPartial ){
82728 pBt->db->flags = savedDbFlags;
82739 /* If the database supports auto-vacuum, make sure no tables contain
82740 ** references to pointer-map pages.
82743 (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
82747 (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
82767 assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
82775 ** an empty string if the database is in-memory or a TEMP database.
82781 assert( p->pBt->pPager!=0 );
82782 return sqlite3PagerFilename(p->pBt->pPager, 1);
82794 assert( p->pBt->pPager!=0 );
82795 return sqlite3PagerJournalname(p->pBt->pPager);
82803 assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
82804 return p ? p->inTrans : 0;
82811 ** Return SQLITE_LOCKED if this or any other connection has an open
82812 ** transaction on the shared-cache the argument Btree is connected to.
82819 BtShared *pBt = p->pBt;
82821 if( pBt->inTransaction!=TRANS_NONE ){
82824 rc = sqlite3PagerCheckpoint(pBt->pPager, p->db, eMode, pnLog, pnCkpt);
82837 assert( sqlite3_mutex_held(p->db->mutex) );
82838 return p->nBackup!=0;
82843 ** a single shared-btree. The memory is used by client code for its own
82844 ** purposes (for example, to store a high-level schema associated with
82845 ** the shared-btree). The btree layer manages reference counting issues.
82847 ** The first time this is called on a shared-btree, nBytes bytes of memory
82856 ** Just before the shared-btree is closed, the function passed as the
82862 BtShared *pBt = p->pBt;
82865 if( !pBt->pSchema && nBytes ){
82866 pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
82867 pBt->xFreeSchema = xFree;
82870 return pBt->pSchema;
82875 ** btree as the argument handle holds an exclusive lock on the
82880 assert( sqlite3_mutex_held(p->db->mutex) );
82897 assert( p->inTrans!=TRANS_NONE );
82898 if( p->sharable ){
82916 ** Argument pCsr must be a cursor opened for writing on an
82928 assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
82929 assert( pCsr->curFlags & BTCF_Incrblob );
82935 assert( pCsr->eState!=CURSOR_REQUIRESEEK );
82936 if( pCsr->eState!=CURSOR_VALID ){
82941 ** required in case any of them are holding references to an xFetch
82942 ** version of the b-tree page modified by the accessPayload call below.
82948 VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
82954 ** (c) the connection holds a write-lock on the table (if required),
82955 ** (d) there are no conflicting read-locks, and
82956 ** (e) the cursor points at a valid row of an intKey table.
82958 if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
82961 assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
82962 && pCsr->pBt->inTransaction==TRANS_WRITE );
82963 assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
82964 assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
82965 assert( pCsr->pPage->intKey );
82971 ** Mark this cursor as an incremental blob cursor.
82974 pCur->curFlags |= BTCF_Incrblob;
82975 pCur->pBtree->hasIncrblobCur = 1;
82985 BtShared *pBt = pBtree->pBt;
82993 pBt->btsFlags &= ~BTS_NO_WAL;
82994 if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
82998 u8 *aData = pBt->pPage1->aData;
83002 rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
83011 pBt->btsFlags &= ~BTS_NO_WAL;
83020 return (pCsr->hints & mask)!=0;
83024 ** Return true if the given Btree is read-only.
83027 return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
83036 ** If no transaction is active and the database is not a temp-db, clear
83037 ** the in-memory pager cache.
83040 BtShared *pBt = p->pBt;
83041 if( pBt->inTransaction==TRANS_NONE ){
83042 sqlite3PagerClearCache(pBt->pPager);
83051 return p->sharable;
83060 testcase( p->sharable );
83061 return p->pBt->nRef;
83089 Btree *pDest; /* Destination b-tree file */
83091 int bDestLocked; /* True once a write-transaction is open on pDest */
83095 Btree *pSrc; /* Source b-tree file */
83113 ** structure may be accessed via two groups of thread-safe entry points:
83127 ** backup_pagecount() are not thread-safe functions. If they are called
83135 ** Non-sharable Btrees (in-memory databases for example), do not have
83142 ** a NULL pointer and write an error message to pErrorDb.
83145 ** function. If an error occurs while doing so, return 0 and write an
83171 return pDb->aDb[i].pBt;
83180 rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),0,0);
83185 ** Check that there is no open read-transaction on the b-tree passed as the
83187 ** is an open read-transaction, return SQLITE_ERROR and leave an error
83199 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
83203 ** If an error occurs, NULL is returned and an error code and error message
83229 sqlite3_mutex_enter(pSrcDb->mutex);
83230 sqlite3_mutex_enter(pDestDb->mutex);
83239 ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
83250 p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
83251 p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
83252 p->pDestDb = pDestDb;
83253 p->pSrcDb = pSrcDb;
83254 p->iNext = 1;
83255 p->isAttached = 0;
83257 if( 0==p->pSrc || 0==p->pDest
83258 || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
83260 /* One (or both) of the named databases did not exist or an OOM
83270 p->pSrc->nBackup++;
83273 sqlite3_mutex_leave(pDestDb->mutex);
83274 sqlite3_mutex_leave(pSrcDb->mutex);
83279 ** Argument rc is an SQLite error code. Return true if this error is
83296 int bUpdate /* True for an update, false otherwise */
83298 Pager * const pDestPager = sqlite3BtreePager(p->pDest);
83299 const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
83300 int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
83306 assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
83307 assert( p->bDestLocked );
83308 assert( !isFatalError(p->rc) );
83309 assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
83317 for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
83320 if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
83338 sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
83350 ** this function is a no-op.
83352 ** Return SQLITE_OK if everything is successful, or an SQLite error
83353 ** code if an error occurs.
83370 assert( sqlite3BtreeHoldsMutex(p->pSrc) );
83371 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
83372 p->pNext = *pp;
83374 p->isAttached = 1;
83378 ** Copy nPage pages from the source b-tree to the destination.
83389 sqlite3_mutex_enter(p->pSrcDb->mutex);
83390 sqlite3BtreeEnter(p->pSrc);
83391 if( p->pDestDb ){
83392 sqlite3_mutex_enter(p->pDestDb->mutex);
83395 rc = p->rc;
83397 Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
83398 Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
83400 int nSrcPage = -1; /* Size of source db in pages */
83403 /* If the source pager is currently in a write-transaction, return
83406 if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
83412 /* If there is no open read-transaction on the source database, open
83416 if( rc==SQLITE_OK && SQLITE_TXN_NONE==sqlite3BtreeTxnState(p->pSrc) ){
83417 rc = sqlite3BtreeBeginTrans(p->pSrc, 0, 0);
83427 if( p->bDestLocked==0 && rc==SQLITE_OK && setDestPgsz(p)==SQLITE_NOMEM ){
83432 if( SQLITE_OK==rc && p->bDestLocked==0
83433 && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2,
83434 (int*)&p->iDestSchema))
83436 p->bDestLocked = 1;
83441 pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
83442 pgszDest = sqlite3BtreeGetPageSize(p->pDest);
83443 destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
83451 /* Now that there is a read-lock on the source database, query the
83454 nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
83456 for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
83457 const Pgno iSrcPg = p->iNext; /* Source page number */
83458 if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
83466 p->iNext++;
83469 p->nPagecount = nSrcPage;
83470 p->nRemaining = nSrcPage+1-p->iNext;
83471 if( p->iNext>(Pgno)nSrcPage ){
83473 }else if( !p->isAttached ){
83479 ** is to make sure that the schema-version really does change in
83485 rc = sqlite3BtreeNewDb(p->pDest);
83489 rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
83492 if( p->pDestDb ){
83493 sqlite3ResetAllSchemasOfConnection(p->pDestDb);
83496 rc = sqlite3BtreeSetVersion(p->pDest, 2);
83513 assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
83514 assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
83517 nDestTruncate = (nSrcPage+ratio-1)/ratio;
83518 if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
83519 nDestTruncate--;
83527 /* If the source page-size is smaller than the destination page-size,
83533 ** pending-byte page in the source database may need to be
83546 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
83558 if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
83602 && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
83612 ** "committing" a read-only transaction cannot fail.
83616 TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
83617 TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
83624 p->rc = rc;
83626 if( p->pDestDb ){
83627 sqlite3_mutex_leave(p->pDestDb->mutex);
83629 sqlite3BtreeLeave(p->pSrc);
83630 sqlite3_mutex_leave(p->pSrcDb->mutex);
83635 ** Release all resources associated with an sqlite3_backup* handle.
83644 pSrcDb = p->pSrcDb;
83645 sqlite3_mutex_enter(pSrcDb->mutex);
83646 sqlite3BtreeEnter(p->pSrc);
83647 if( p->pDestDb ){
83648 sqlite3_mutex_enter(p->pDestDb->mutex);
83652 if( p->pDestDb ){
83653 p->pSrc->nBackup--;
83655 if( p->isAttached ){
83656 pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
83659 pp = &(*pp)->pNext;
83662 *pp = p->pNext;
83666 sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
83669 rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
83670 if( p->pDestDb ){
83671 sqlite3Error(p->pDestDb, rc);
83674 sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
83676 sqlite3BtreeLeave(p->pSrc);
83677 if( p->pDestDb ){
83678 /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
83698 return p->nRemaining;
83712 return p->nPagecount;
83734 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
83735 if( !isFatalError(p->rc) && iPage<p->iNext ){
83741 assert( p->pDestDb );
83742 sqlite3_mutex_enter(p->pDestDb->mutex);
83744 sqlite3_mutex_leave(p->pDestDb->mutex);
83747 p->rc = rc;
83750 }while( (p = p->pNext)!=0 );
83758 ** detects that the database has been modified by an external database
83769 for(p=pBackup; p; p=p->pNext){
83770 assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
83771 p->iNext = 1;
83793 if( pFd->pMethods ){
83800 /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
83806 b.pSrcDb = pFrom->db;
83814 ** within a single call (unless an error occurs). The assert() statement
83815 ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
83816 ** or an error code. */
83822 pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
83850 ** stores a single value in the VDBE. Mem is an opaque structure visible
83860 #define ISPOWEROF2(X) (((X)&((X)-1))==0)
83873 assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
83879 assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
83882 assert( ISPOWEROF2(p->flags & (MEM_Int|MEM_Real|MEM_IntReal)) );
83884 if( p->flags & MEM_Null ){
83886 assert( (p->flags & (MEM_Int|MEM_Real|MEM_Str|MEM_Blob|MEM_Agg))==0 );
83893 if( (p->flags & (MEM_Term|MEM_Subtype))==(MEM_Term|MEM_Subtype) ){
83896 assert( ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
83897 ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
83898 ((p->flags&MEM_Static)!=0 ? 1 : 0) <= 1 );
83901 assert( (p->flags & ~(MEM_Null|MEM_Term|MEM_Subtype|MEM_FromBind
83909 assert( (p->flags & MEM_Cleared)==0 );
83913 assert( p->szMalloc==0
83914 || (p->flags==MEM_Undefined
83915 && p->szMalloc<=sqlite3DbMallocSize(p->db,p->zMalloc))
83916 || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc));
83923 ** (3) An ephemeral string or blob
83926 if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
83928 ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
83929 ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
83930 ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
83931 ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
83944 assert( p->flags & (MEM_Int|MEM_Real|MEM_IntReal) );
83946 if( p->flags & MEM_Int ){
83948 /* Work-around for GCC bug
83951 assert( (p->flags&MEM_Int)*2==sizeof(x) );
83952 memcpy(&x, (char*)&p->u, (p->flags&MEM_Int)*2);
83953 p->n = sqlite3Int64ToText(x, zBuf);
83955 p->n = sqlite3Int64ToText(p->u.i, zBuf);
83960 (p->flags & MEM_IntReal)!=0 ? (double)p->u.i : p->u.r);
83963 p->n = acc.nChar;
83976 ** If a table contains a numeric value and an index is based on the
83980 ** https://sqlite.org/src/info/343634942dd54ab (2018-01-31) for
83981 ** an example.
83995 if( (p->flags & MEM_Str)==0 ) return 1;
83996 if( p->db && p->db->mallocFailed ) return 1;
83997 if( p->flags & MEM_Term ){
83998 /* Insure that the string is properly zero-terminated. Pay particular
83999 ** attention to the case where p->n is odd */
84000 if( p->szMalloc>0 && p->z==p->zMalloc ){
84001 assert( p->enc==SQLITE_UTF8 || p->szMalloc >= ((p->n+1)&~1)+2 );
84002 assert( p->enc!=SQLITE_UTF8 || p->szMalloc >= p->n+1 );
84004 assert( p->z[p->n]==0 );
84005 assert( p->enc==SQLITE_UTF8 || p->z[(p->n+1)&~1]==0 );
84006 assert( p->enc==SQLITE_UTF8 || p->z[((p->n+1)&~1)+1]==0 );
84008 if( (p->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 ) return 1;
84011 z = p->z;
84014 if( p->enc!=SQLITE_UTF8 ){
84016 if( p->enc==SQLITE_UTF16BE ) z++;
84027 ** If pMem is an object with a valid string representation, this routine
84033 ** routine is a no-op.
84047 if( !(pMem->flags&MEM_Str) ){
84048 pMem->enc = desiredEnc;
84051 if( pMem->enc==desiredEnc ){
84054 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84064 assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
84065 assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
84071 ** Make sure pMem->z points to a writable allocation of at least n bytes.
84074 ** pMem->z into the new allocation. pMem must be either a string or
84076 ** in pMem->z is discarded.
84081 testcase( pMem->db==0 );
84085 assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
84086 testcase( bPreserve && pMem->z==0 );
84088 assert( pMem->szMalloc==0
84089 || (pMem->flags==MEM_Undefined
84090 && pMem->szMalloc<=sqlite3DbMallocSize(pMem->db,pMem->zMalloc))
84091 || pMem->szMalloc==sqlite3DbMallocSize(pMem->db,pMem->zMalloc));
84092 if( pMem->szMalloc>0 && bPreserve && pMem->z==pMem->zMalloc ){
84093 if( pMem->db ){
84094 pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
84096 pMem->zMalloc = sqlite3Realloc(pMem->z, n);
84097 if( pMem->zMalloc==0 ) sqlite3_free(pMem->z);
84098 pMem->z = pMem->zMalloc;
84102 if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
84103 pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
84105 if( pMem->zMalloc==0 ){
84107 pMem->z = 0;
84108 pMem->szMalloc = 0;
84111 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
84114 if( bPreserve && pMem->z ){
84115 assert( pMem->z!=pMem->zMalloc );
84116 memcpy(pMem->zMalloc, pMem->z, pMem->n);
84118 if( (pMem->flags&MEM_Dyn)!=0 ){
84119 assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
84120 pMem->xDel((void *)(pMem->z));
84123 pMem->z = pMem->zMalloc;
84124 pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
84129 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
84130 ** If pMem->zMalloc already meets or exceeds the requested size, this
84131 ** routine is a no-op.
84134 ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
84138 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
84143 assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
84144 if( pMem->szMalloc<szNew ){
84147 assert( (pMem->flags & MEM_Dyn)==0 );
84148 pMem->z = pMem->zMalloc;
84149 pMem->flags &= (MEM_Null|MEM_Int|MEM_Real|MEM_IntReal);
84154 ** If pMem is already a string, detect if it is a zero-terminated
84157 ** This is an optimization. Correct operation continues even if
84158 ** this routine is a no-op.
84161 if( (pMem->flags & (MEM_Str|MEM_Term|MEM_Ephem|MEM_Static))!=MEM_Str ){
84162 /* pMem must be a string, and it cannot be an ephemeral or static string */
84165 if( pMem->enc!=SQLITE_UTF8 ) return;
84166 assert( pMem->z!=0 );
84167 if( pMem->flags & MEM_Dyn ){
84168 if( pMem->xDel==sqlite3_free
84169 && sqlite3_msize(pMem->z) >= (u64)(pMem->n+1)
84171 pMem->z[pMem->n] = 0;
84172 pMem->flags |= MEM_Term;
84175 if( pMem->xDel==sqlite3RCStrUnref ){
84176 /* Blindly assume that all RCStr objects are zero-terminated */
84177 pMem->flags |= MEM_Term;
84180 }else if( pMem->szMalloc >= pMem->n+1 ){
84181 pMem->z[pMem->n] = 0;
84182 pMem->flags |= MEM_Term;
84188 ** It is already known that pMem contains an unterminated string.
84192 ** to be a double-zero byte at an even byte boundary in order to
84194 ** is an odd number of bytes.
84197 if( sqlite3VdbeMemGrow(pMem, pMem->n+3, 1) ){
84200 pMem->z[pMem->n] = 0;
84201 pMem->z[pMem->n+1] = 0;
84202 pMem->z[pMem->n+2] = 0;
84203 pMem->flags |= MEM_Term;
84215 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84217 if( (pMem->flags & (MEM_Str|MEM_Blob))!=0 ){
84219 if( pMem->szMalloc==0 || pMem->z!=pMem->zMalloc ){
84224 pMem->flags &= ~MEM_Ephem;
84226 pMem->pScopyFrom = 0;
84233 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
84240 assert( pMem->flags & MEM_Zero );
84241 assert( (pMem->flags&MEM_Blob)!=0 || MemNullNochng(pMem) );
84244 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84247 nByte = pMem->n + pMem->u.nZero;
84249 if( (pMem->flags & MEM_Blob)==0 ) return SQLITE_OK;
84255 assert( pMem->z!=0 );
84256 assert( sqlite3DbMallocSize(pMem->db,pMem->z) >= nByte );
84258 memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
84259 pMem->n += pMem->u.nZero;
84260 pMem->flags &= ~(MEM_Zero|MEM_Term);
84270 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84271 testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
84272 testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
84273 if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
84292 ** user and the latter is an internal programming error.
84298 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84299 assert( !(pMem->flags&MEM_Zero) );
84300 assert( !(pMem->flags&(MEM_Str|MEM_Blob)) );
84301 assert( pMem->flags&(MEM_Int|MEM_Real|MEM_IntReal) );
84307 pMem->enc = 0;
84311 vdbeMemRenderNum(nByte, pMem->z, pMem);
84312 assert( pMem->z!=0 );
84313 assert( pMem->n==(int)sqlite3Strlen30NN(pMem->z) );
84314 pMem->enc = SQLITE_UTF8;
84315 pMem->flags |= MEM_Str|MEM_Term;
84316 if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
84322 ** Memory cell pMem contains the context of an aggregate function.
84326 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
84334 assert( pMem->db!=0 );
84335 assert( pFunc->xFinalize!=0 );
84336 assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
84337 assert( sqlite3_mutex_held(pMem->db->mutex) );
84341 t.db = pMem->db;
84346 pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
84347 assert( (pMem->flags & MEM_Dyn)==0 );
84348 if( pMem->szMalloc>0 ) sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
84354 ** Memory cell pAccum contains the context of an aggregate function.
84358 ** SQLITE_ERROR is returned if xValue() reports an error. SQLITE_OK
84365 assert( pFunc->xValue!=0 );
84366 assert( (pAccum->flags & MEM_Null)!=0 || pFunc==pAccum->u.pDef );
84367 assert( pAccum->db!=0 );
84368 assert( sqlite3_mutex_held(pAccum->db->mutex) );
84374 ctx.enc = ENC(pAccum->db);
84375 pFunc->xValue(&ctx);
84390 assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
84392 if( p->flags&MEM_Agg ){
84393 sqlite3VdbeMemFinalize(p, p->u.pDef);
84394 assert( (p->flags & MEM_Agg)==0 );
84395 testcase( p->flags & MEM_Dyn );
84397 if( p->flags&MEM_Dyn ){
84398 assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
84399 p->xDel((void *)p->z);
84401 p->flags = MEM_Null;
84406 ** by p->xDel and memory in p->zMalloc.
84416 if( p->szMalloc ){
84417 sqlite3DbFreeNN(p->db, p->zMalloc);
84418 p->szMalloc = 0;
84420 p->z = 0;
84435 if( VdbeMemDynamic(p) || p->szMalloc ){
84445 if( p->szMalloc ) vdbeMemClear(p);
84450 ** at representing the value that *pMem describes as an integer.
84451 ** If pMem is an integer, then the value is exact. If pMem is
84452 ** a floating-point then the value returned is the integer part.
84453 ** If pMem is a string or blob, then we make an attempt to convert
84454 ** it into an integer and return that. If pMem represents an
84455 ** an SQL-NULL value, return 0.
84461 sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
84467 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84469 flags = pMem->flags;
84472 return pMem->u.i;
84474 return sqlite3RealToI64(pMem->u.r);
84475 }else if( (flags & (MEM_Str|MEM_Blob))!=0 && pMem->z!=0 ){
84484 ** double. If pMem is already a double or an integer, return its
84491 sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
84496 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84498 if( pMem->flags & MEM_Real ){
84499 return pMem->u.r;
84500 }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
84501 testcase( pMem->flags & MEM_IntReal );
84502 return (double)pMem->u.i;
84503 }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
84516 testcase( pMem->flags & MEM_IntReal );
84517 if( pMem->flags & (MEM_Int|MEM_IntReal) ) return pMem->u.i!=0;
84518 if( pMem->flags & MEM_Null ) return ifNull;
84528 assert( pMem->flags & (MEM_Real|MEM_IntReal) );
84530 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84533 if( pMem->flags & MEM_IntReal ){
84536 i64 ix = sqlite3RealToI64(pMem->u.r);
84538 /* Only mark the value as an integer if
84540 ** (1) the round-trip conversion real->int->real is a no-op, and
84548 if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
84549 pMem->u.i = ix;
84560 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84564 pMem->u.i = sqlite3VdbeIntValue(pMem);
84575 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84578 pMem->u.r = sqlite3VdbeRealValue(pMem);
84583 /* Compare a floating point value to an integer. Return true if the two
84588 ** For some versions of GCC on 32-bit machines, if you do the more obvious
84589 ** comparison of "r1==(double)i" you sometimes get an answer of false even
84590 ** though the r1 and (double)i values are bit-for-bit the same.
84596 && i >= -2251799813685248LL && i < 2251799813685248LL);
84604 if( r<-9223372036854774784.0 ) return SMALLEST_INT64;
84619 testcase( pMem->flags & MEM_Int );
84620 testcase( pMem->flags & MEM_Real );
84621 testcase( pMem->flags & MEM_IntReal );
84622 testcase( pMem->flags & MEM_Null );
84623 if( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))==0 ){
84626 assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
84627 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
84628 rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
84629 if( ((rc==0 || rc==1) && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1)
84630 || sqlite3RealSameAsInt(pMem->u.r, (ix = sqlite3RealToI64(pMem->u.r)))
84632 pMem->u.i = ix;
84638 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null))!=0 );
84639 pMem->flags &= ~(MEM_Str|MEM_Blob|MEM_Zero);
84651 if( pMem->flags & MEM_Null ) return SQLITE_OK;
84654 if( (pMem->flags & MEM_Blob)==0 ){
84656 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
84657 if( pMem->flags & MEM_Str ) MemSetTypeFlag(pMem, MEM_Blob);
84659 pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
84679 pMem->flags |= (pMem->flags&MEM_Blob)>>3;
84681 assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
84682 pMem->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal|MEM_Blob|MEM_Zero);
84683 if( encoding!=SQLITE_UTF8 ) pMem->n &= ~1;
84699 pMem->flags = flags;
84700 pMem->db = db;
84701 pMem->szMalloc = 0;
84721 pMem->flags = MEM_Null;
84735 pMem->flags = MEM_Blob|MEM_Zero;
84736 pMem->n = 0;
84738 pMem->u.nZero = n;
84739 pMem->enc = SQLITE_UTF8;
84740 pMem->z = 0;
84748 assert( pMem->z!=0 );
84749 assert( sqlite3DbMallocSize(pMem->db, pMem->z)>=nByte );
84750 memset(pMem->z, 0, nByte);
84751 pMem->n = n>0?n:0;
84752 pMem->flags = MEM_Blob;
84753 pMem->enc = SQLITE_UTF8;
84761 ** a 64-bit integer.
84765 pMem->u.i = val;
84766 pMem->flags = MEM_Int;
84777 pMem->u.i = val;
84778 pMem->flags = MEM_Int;
84789 /* A no-op destructor */
84802 assert( pMem->flags==MEM_Null );
84804 pMem->u.zPType = zPType ? zPType : "";
84805 pMem->z = pPtr;
84806 pMem->flags = MEM_Null|MEM_Dyn|MEM_Subtype|MEM_Term;
84807 pMem->eSubtype = 'p';
84808 pMem->xDel = xDestructor ? xDestructor : sqlite3NoopDestructor;
84819 pMem->u.r = val;
84820 pMem->flags = MEM_Real;
84831 return (pMem->flags&(MEM_Blob|MEM_Dyn))==(MEM_Blob|MEM_Dyn)
84832 && pMem->xDel==sqlite3RowSetDelete;
84837 ** Delete any previous value and set the value of pMem to be an
84844 sqlite3 *db = pMem->db;
84851 pMem->z = (char*)p;
84852 pMem->flags = MEM_Blob|MEM_Dyn;
84853 pMem->xDel = sqlite3RowSetDelete;
84859 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
84862 assert( p->db!=0 );
84863 if( p->flags & (MEM_Str|MEM_Blob) ){
84864 int n = p->n;
84865 if( p->flags & MEM_Zero ){
84866 n += p->u.nZero;
84868 return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
84879 ** This is used for testing and debugging only - to help ensure that shallow
84885 if( pMem->bScopy ){
84886 for(i=1, pX=pVdbe->aMem+1; i<pVdbe->nMem; i++, pX++){
84887 if( pX->pScopyFrom==pMem ){
84889 if( pVdbe->db->flags & SQLITE_VdbeTrace ){
84891 (int)(pX - pVdbe->aMem), (int)(pMem - pVdbe->aMem));
84899 mFlags = pMem->flags & pX->flags & pX->mScopyFlags;
84900 assert( (mFlags&(MEM_Int|MEM_IntReal))==0 || pMem->u.i==pX->u.i );
84903 ** undefined so that we can quickly detect the shallow-copy error */
84904 pX->flags = MEM_Undefined;
84905 pX->pScopyFrom = 0;
84908 pMem->bScopy = 0;
84910 pMem->pScopyFrom = 0;
84915 ** Make an shallow copy of pFrom into pTo. Prior contents of
84916 ** pTo are freed. The pFrom->z field is not duplicated. If
84917 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
84927 assert( pTo->db==pFrom->db );
84930 if( (pFrom->flags&MEM_Static)==0 ){
84931 pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
84933 pTo->flags |= srcType;
84947 pTo->flags &= ~MEM_Dyn;
84948 if( pTo->flags&(MEM_Str|MEM_Blob) ){
84949 if( 0==(pFrom->flags&MEM_Static) ){
84950 pTo->flags |= MEM_Ephem;
84962 ** pFrom contains an SQL NULL when this routine returns.
84965 assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
84966 assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
84967 assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
84971 pFrom->flags = MEM_Null;
84972 pFrom->szMalloc = 0;
84995 ** non-negative for blobs.
85004 i64 nByte = n; /* New value for pMem->n */
85006 u16 flags; /* New value for pMem->flags */
85009 assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
85013 /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
85019 if( pMem->db ){
85020 iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
85041 sqlite3DbFree(pMem->db, (void*)z);
85047 return sqlite3ErrorToParser(pMem->db, SQLITE_TOOBIG);
85065 memcpy(pMem->z, z, nAlloc);
85068 pMem->z = (char *)z;
85070 pMem->zMalloc = pMem->z;
85071 pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
85073 pMem->xDel = xDel;
85078 pMem->n = (int)(nByte & 0x7fffffff);
85079 pMem->flags = flags;
85080 pMem->enc = enc;
85099 ** pMem->zMalloc to hold the content from the btree, if possible. New
85100 ** pMem->zMalloc space will be allocated if necessary. The calling routine
85105 ** to read from the disk) then the pMem is left in an inconsistent state.
85114 pMem->flags = MEM_Null;
85119 rc = sqlite3BtreePayload(pCur, offset, amt, pMem->z);
85121 pMem->z[amt] = 0; /* Overrun area used when reading malformed records */
85122 pMem->flags = MEM_Blob;
85123 pMem->n = (int)amt;
85144 pMem->z = (char *)sqlite3BtreePayloadFetch(pCur, &available);
85145 assert( pMem->z!=0 );
85148 pMem->flags = MEM_Blob|MEM_Ephem;
85149 pMem->n = (int)amt;
85160 ** to a zero-terminated version of that string.
85164 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
85167 assert( (pVal->flags & (MEM_Null))==0 );
85168 if( pVal->flags & (MEM_Blob|MEM_Str) ){
85170 pVal->flags |= MEM_Str;
85171 if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
85174 if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
85175 assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
85180 sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
85183 assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
85185 assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
85186 || pVal->db->mallocFailed );
85187 if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
85189 return pVal->z;
85201 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
85202 ** If that is the case, then the result must be aligned on an even byte
85207 assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
85210 if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
85212 return pVal->z;
85214 if( pVal->flags&MEM_Null ){
85224 ** that third-party extensions can get access to it?
85228 && ALWAYS((pVal->flags & (MEM_Str|MEM_Blob))!=0)
85229 && (pVal->flags & MEM_Dyn)!=0
85230 && pVal->xDel==xFree
85244 p->flags = MEM_Null;
85245 p->db = db;
85266 ** Otherwise, if the second argument is non-zero, then this function is
85270 ** an sqlite3_value within the UnpackedRecord.a[] array.
85275 UnpackedRecord *pRec = p->ppRec[0];
85278 Index *pIdx = p->pIdx; /* Index being probed */
85281 int nCol = pIdx->nColumn; /* Number of index columns including rowid */
85286 pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
85287 if( pRec->pKeyInfo ){
85288 assert( pRec->pKeyInfo->nAllField==nCol );
85289 assert( pRec->pKeyInfo->enc==ENC(db) );
85290 pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
85292 pRec->aMem[i].flags = MEM_Null;
85293 pRec->aMem[i].db = db;
85301 p->ppRec[0] = pRec;
85304 pRec->nField = p->iVal+1;
85305 sqlite3VdbeMemSetNull(&pRec->aMem[p->iVal]);
85306 return &pRec->aMem[p->iVal];
85331 ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
85332 ** NULL and an SQLite error code returned.
85353 assert( (p->flags & EP_TokenOnly)==0 );
85355 pList = p->x.pList;
85356 if( pList ) nVal = pList->nExpr;
85358 pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
85363 if( (pFunc->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
85364 || (pFunc->funcFlags & (SQLITE_FUNC_NEEDCOLL|SQLITE_FUNC_RUNONLY))!=0
85376 rc = sqlite3Stat4ValueFromExpr(pCtx->pParse, pList->a[i].pExpr, aff,
85392 pFunc->xSFunc(&ctx, nVal, apVal);
85395 sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
85402 pCtx->pParse->nErr++;
85409 pCtx->pParse->rc = rc;
85430 ** If pCtx is NULL and an error occurs after the sqlite3_value object
85451 while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
85452 if( op==TK_REGISTER ) op = pExpr->op2;
85456 ** check ensures that an EP_TokenOnly expression is never passed down
85458 assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
85463 aff = sqlite3AffinityType(pExpr->u.zToken,0);
85464 rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
85470 /* zero-blobs only come from functions, not literal values. And
85481 ** case when the value is -9223372036854775808. Except - do not do this
85484 Expr *pLeft = pExpr->pLeft;
85485 if( (pLeft->op==TK_INTEGER || pLeft->op==TK_FLOAT) ){
85487 || pLeft->u.zToken[0]!='0' || (pLeft->u.zToken[1] & ~0x20)!='X'
85490 op = pExpr->op;
85491 negInt = -1;
85492 zNeg = "-";
85501 sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
85504 if( op==TK_INTEGER && 0==sqlite3DecOrHexToI64(pExpr->u.zToken, &iVal) ){
85507 zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
85509 sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
85514 assert( pVal && pVal->z && pVal->flags==(MEM_Str|MEM_Term) );
85515 sqlite3AtoF(pVal->z, &pVal->u.r, pVal->n, SQLITE_UTF8);
85516 pVal->flags = MEM_Real;
85518 /* This case is required by -9223372036854775808 and other strings
85526 assert( (pVal->flags & MEM_IntReal)==0 );
85527 if( pVal->flags & (MEM_Int|MEM_IntReal|MEM_Real) ){
85528 testcase( pVal->flags & MEM_Int );
85529 testcase( pVal->flags & MEM_Real );
85530 pVal->flags &= ~MEM_Str;
85536 /* This branch happens for multiple negative signs. Ex: -(-5) */
85537 if( SQLITE_OK==valueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal,pCtx)
85541 if( pVal->flags & MEM_Real ){
85542 pVal->u.r = -pVal->u.r;
85543 }else if( pVal->u.i==SMALLEST_INT64 ){
85545 pVal->u.r = -(double)SMALLEST_INT64;
85547 pVal->u.r = LARGEST_INT64;
85551 pVal->u.i = -pVal->u.i;
85564 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
85565 assert( pExpr->u.zToken[1]=='\'' );
85568 zVal = &pExpr->u.zToken[2];
85569 nVal = sqlite3Strlen30(zVal)-1;
85584 pVal->flags = MEM_Int;
85585 pVal->u.i = pExpr->u.zToken[4]==0;
85595 if( pCtx==0 || NEVER(pCtx->pParse->nErr==0) )
85632 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
85638 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
85656 sqlite3 *db = pParse->db;
85661 assert( pExpr==0 || pExpr->op!=TK_REGISTER || pExpr->op2!=TK_VARIABLE );
85667 }else if( pExpr->op==TK_VARIABLE && (db->flags & SQLITE_EnableQPSG)==0 ){
85669 int iBindVar = pExpr->iColumn;
85670 sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
85671 if( (v = pParse->pReprepare)!=0 ){
85674 rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
85676 pVal->db = pParse->db;
85683 assert( pVal==0 || pVal->db==db );
85697 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
85713 ** When this function is called, *ppRec must either point to an object
85714 ** allocated by an earlier call to this function, or must be NULL. If it
85718 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
85719 ** error if a value cannot be extracted from pExpr. If an error does
85720 ** occur, an SQLite error code is returned.
85734 if( pExpr==0 || pExpr->op!=TK_SELECT ){
85745 u8 aff = sqlite3IndexColumnAffinity(pParse->db, pIdx, iVal+i);
85763 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
85764 ** does occur, return an SQLite error code. The final value of *ppVal
85777 ** Extract the iCol-th column from the nRec-byte record in pRec. Write
85819 sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
85820 pMem->enc = ENC(db);
85825 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
85826 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
85832 int nCol = pRec->pKeyInfo->nAllField;
85833 Mem *aMem = pRec->aMem;
85838 sqlite3KeyInfoUnref(pRec->pKeyInfo);
85845 ** Change the string value of an sqlite3_value object
85858 ** Free an sqlite3_value object
85863 sqlite3DbFreeNN(((Mem*)v)->db, v);
85872 return valueToText(pVal, enc)!=0 ? pVal->n : 0;
85876 assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
85877 if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
85878 return p->n;
85880 if( (p->flags & MEM_Str)!=0 && enc!=SQLITE_UTF8 && pVal->enc!=SQLITE_UTF8 ){
85881 return p->n;
85883 if( (p->flags & MEM_Blob)!=0 ){
85884 if( p->flags & MEM_Zero ){
85885 return p->n + p->u.nZero;
85887 return p->n;
85890 if( p->flags & MEM_Null ) return 0;
85908 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
85921 sqlite3 *db = pParse->db;
85925 memset(&p->aOp, 0, sizeof(Vdbe)-offsetof(Vdbe,aOp));
85926 p->db = db;
85927 if( db->pVdbe ){
85928 db->pVdbe->ppVPrev = &p->pVNext;
85930 p->pVNext = db->pVdbe;
85931 p->ppVPrev = &db->pVdbe;
85932 db->pVdbe = p;
85933 assert( p->eVdbeState==VDBE_INIT_STATE );
85934 p->pParse = pParse;
85935 pParse->pVdbe = p;
85936 assert( pParse->aLabel==0 );
85937 assert( pParse->nLabel==0 );
85938 assert( p->nOpAlloc==0 );
85939 assert( pParse->szOpAlloc==0 );
85948 return p->pParse;
85956 sqlite3DbFree(p->db, p->zErrMsg);
85958 p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
85967 p->prepFlags = prepFlags;
85969 p->expmask = 0;
85971 assert( p->zSql==0 );
85972 p->zSql = sqlite3DbStrNDup(p->db, z, n);
85977 ** Add a new element to the Vdbe->pDblStr list.
85983 sizeof(*pStr)+n+1-sizeof(pStr->z));
85985 pStr->pNextStr = p->pDblStr;
85986 p->pDblStr = pStr;
85987 memcpy(pStr->z, z, n+1);
85995 ** zId of length nId is a double-quoted identifier. Check to see if
86000 const char *zId /* The double-quoted identifier, already dequoted */
86004 if( pVdbe->pDblStr==0 ) return 0;
86005 for(pStr=pVdbe->pDblStr; pStr; pStr=pStr->pNextStr){
86006 if( strcmp(zId, pStr->z)==0 ) return 1;
86013 ** Swap byte-code between two VDBE structures.
86025 assert( pA->db==pB->db );
86029 pTmp = pA->pVNext;
86030 pA->pVNext = pB->pVNext;
86031 pB->pVNext = pTmp;
86032 ppTmp = pA->ppVPrev;
86033 pA->ppVPrev = pB->ppVPrev;
86034 pB->ppVPrev = ppTmp;
86035 zTmp = pA->zSql;
86036 pA->zSql = pB->zSql;
86037 pB->zSql = zTmp;
86039 zTmp = pA->zNormSql;
86040 pA->zNormSql = pB->zNormSql;
86041 pB->zNormSql = zTmp;
86043 pB->expmask = pA->expmask;
86044 pB->prepFlags = pA->prepFlags;
86045 memcpy(pB->aCounter, pA->aCounter, sizeof(pB->aCounter));
86046 pB->aCounter[SQLITE_STMTSTATUS_REPREPARE]++;
86054 ** If an out-of-memory error occurs while resizing the array, return
86061 Parse *p = v->pParse;
86063 /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
86071 sqlite3_int64 nNew = (v->nOpAlloc>=512 ? 2*(sqlite3_int64)v->nOpAlloc
86072 : (sqlite3_int64)v->nOpAlloc+nOp);
86074 sqlite3_int64 nNew = (v->nOpAlloc ? 2*(sqlite3_int64)v->nOpAlloc
86080 if( nNew > p->db->aLimit[SQLITE_LIMIT_VDBE_OP] ){
86081 sqlite3OomFault(p->db);
86086 assert( nNew>=(v->nOpAlloc+nOp) );
86087 pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
86089 p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
86090 v->nOpAlloc = p->szOpAlloc/sizeof(Op);
86091 v->aOp = pNew;
86123 assert( p->nOpAlloc<=p->nOp );
86125 assert( p->nOpAlloc>p->nOp );
86134 int p4 /* The P4 operand as an integer */
86137 if( p->db->mallocFailed==0 ){
86138 VdbeOp *pOp = &p->aOp[addr];
86139 pOp->p4type = P4_INT32;
86140 pOp->p4.i = p4;
86171 i = p->nOp;
86172 assert( p->eVdbeState==VDBE_INIT_STATE );
86174 if( p->nOpAlloc<=i ){
86177 assert( p->aOp!=0 );
86178 p->nOp++;
86179 pOp = &p->aOp[i];
86181 pOp->opcode = (u8)op;
86182 pOp->p5 = 0;
86183 pOp->p1 = p1;
86184 pOp->p2 = p2;
86185 pOp->p3 = p3;
86186 pOp->p4.p = 0;
86187 pOp->p4type = P4_NOTUSED;
86192 pOp->zComment = 0;
86195 pOp->nExec = 0;
86196 pOp->nCycle = 0;
86199 if( p->db->flags & SQLITE_VdbeAddopTrace ){
86200 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
86201 test_addop_breakpoint(i, &p->aOp[i]);
86205 pOp->iSrcLine = 0;
86218 int p4 /* The P4 operand as an integer */
86223 i = p->nOp;
86224 if( p->nOpAlloc<=i ){
86227 p->nOp++;
86228 pOp = &p->aOp[i];
86230 pOp->opcode = (u8)op;
86231 pOp->p5 = 0;
86232 pOp->p1 = p1;
86233 pOp->p2 = p2;
86234 pOp->p3 = p3;
86235 pOp->p4.i = p4;
86236 pOp->p4type = P4_INT32;
86241 pOp->zComment = 0;
86244 pOp->nExec = 0;
86245 pOp->nCycle = 0;
86248 if( p->db->flags & SQLITE_VdbeAddopTrace ){
86249 sqlite3VdbePrintOp(0, i, &p->aOp[i]);
86250 test_addop_breakpoint(i, &p->aOp[i]);
86254 pOp->iSrcLine = 0;
86262 /* Generate code for an unconditional jump to instruction iDest
86281 ** in zTypes[], the register is initialized to an integer.
86283 ** If the input string does not end with "X" then an OP_ResultRow instruction
86307 ** Add an opcode that includes the p4 value as a pointer.
86324 ** Add an OP_Function or OP_PureFunc opcode.
86329 ** NC_IdxExpr means called as part of an index expression. NC_PartIdx
86342 Vdbe *v = pParse->pVdbe;
86346 pCtx = sqlite3DbMallocRawNN(pParse->db, SZ_CONTEXT(nArg));
86348 assert( pParse->db->mallocFailed );
86349 freeEphemeralFunction(pParse->db, (FuncDef*)pFunc);
86352 pCtx->pOut = 0;
86353 pCtx->pFunc = (FuncDef*)pFunc;
86354 pCtx->pVdbe = 0;
86355 pCtx->isError = 0;
86356 pCtx->argc = nArg;
86357 pCtx->iOp = sqlite3VdbeCurrentAddr(v);
86366 ** Add an opcode that includes the p4 value with a P4_INT64 or
86390 if( pParse->addrExplain==0 ) return 0;
86391 pOp = sqlite3VdbeGetOp(pParse->pVdbe, pParse->addrExplain);
86392 return pOp->p2;
86417 if( pParse->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
86425 zMsg = sqlite3VMPrintf(pParse->db, zFmt, ap);
86427 v = pParse->pVdbe;
86428 iThis = v->nOp;
86429 addr = sqlite3VdbeAddOp4(v, OP_Explain, iThis, pParse->addrExplain, 0,
86431 sqlite3ExplainBreakpoint(bPush?"PUSH":"", sqlite3VdbeGetLastOp(v)->p4.z);
86433 pParse->addrExplain = iThis;
86435 sqlite3VdbeScanStatus(v, iThis, -1, -1, 0, 0);
86445 pParse->addrExplain = sqlite3VdbeExplainParent(pParse);
86450 ** Add an OP_ParseSchema opcode. This routine is broken out from
86461 for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
86462 sqlite3MayAbort(p->pParse);
86465 /* Insert the end of a co-routine
86471 ** co-routine has its own independent set of registers, because co-routines
86472 ** might expect their registers to be preserved across an OP_Yield, and
86473 ** that could cause problems if two or more co-routines are using the same
86476 v->pParse->nTempReg = 0;
86477 v->pParse->nRangeReg = 0;
86481 ** Create a new symbolic label for an instruction that has yet to be
86483 ** label can be used as the P2 value of an operation. Later, when
86489 ** always negative and P2 values are suppose to be non-negative.
86496 ** Parse.aLabel[x] Stores the address that the x-th label resolves
86498 ** labels stores -1, but that is not required.
86506 return --pParse->nLabel;
86515 int nNewSize = 10 - p->nLabel;
86516 p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
86517 nNewSize*sizeof(p->aLabel[0]));
86518 if( p->aLabel==0 ){
86519 p->nLabelAlloc = 0;
86523 for(i=p->nLabelAlloc; i<nNewSize; i++) p->aLabel[i] = -1;
86525 if( nNewSize>=100 && (nNewSize/100)>(p->nLabelAlloc/100) ){
86528 p->nLabelAlloc = nNewSize;
86529 p->aLabel[j] = v->nOp;
86533 Parse *p = v->pParse;
86535 assert( v->eVdbeState==VDBE_INIT_STATE );
86536 assert( j<-p->nLabel );
86539 if( p->db->flags & SQLITE_VdbeAddopTrace ){
86540 printf("RESOLVE LABEL %d to %d\n", x, v->nOp);
86543 if( p->nLabelAlloc + p->nLabel < 0 ){
86546 assert( p->aLabel[j]==(-1) ); /* Labels may only be resolved once */
86547 p->aLabel[j] = v->nOp;
86563 for(i=1; ALWAYS(i<p->nOp); i++){
86564 if( ALWAYS(p->aOp[i].opcode==OP_Expire) ){
86565 p->aOp[1].opcode = OP_Noop;
86575 ** in a Vdbe main program and each of the sub-programs (triggers) it may
86586 ** sqlite3DbFree(v->db, sIter.apSub);
86595 int iSub; /* 0 = main program, 1 = first sub-program etc. */
86598 Vdbe *v = p->v;
86603 if( p->iSub<=p->nSub ){
86605 if( p->iSub==0 ){
86606 aOp = v->aOp;
86607 nOp = v->nOp;
86609 aOp = p->apSub[p->iSub-1]->aOp;
86610 nOp = p->apSub[p->iSub-1]->nOp;
86612 assert( p->iAddr<nOp );
86614 pRet = &aOp[p->iAddr];
86615 p->iAddr++;
86616 if( p->iAddr==nOp ){
86617 p->iSub++;
86618 p->iAddr = 0;
86621 if( pRet->p4type==P4_SUBPROGRAM ){
86622 i64 nByte = (1+(u64)p->nSub)*sizeof(SubProgram*);
86624 for(j=0; j<p->nSub; j++){
86625 if( p->apSub[j]==pRet->p4.pProgram ) break;
86627 if( j==p->nSub ){
86628 p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
86629 if( !p->apSub ){
86632 p->apSub[p->nSub++] = pRet->p4.pProgram;
86643 ** throw an ABORT exception (causing the statement, but not entire transaction
86645 ** sub-programs contains any of the following:
86657 ** Then check that the value of Parse.mayAbort is true if an
86660 ** part of an assert statement in the compiler. Similar to:
86662 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
86678 int opcode = pOp->opcode;
86685 && ((pOp->p1)!=SQLITE_OK && pOp->p2==OE_Abort))
86690 if( opcode==OP_CreateBtree && pOp->p3==BTREE_INTKEY ) hasCreateTable = 1;
86694 ** where a "DELETE FROM tbl" has a statement-journal but does not
86695 ** require one. This is not so bad - it is an inefficiency, not a bug. */
86696 if( opcode==OP_CreateBtree && pOp->p3==BTREE_BLOBKEY ) hasCreateIndex = 1;
86701 if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
86706 sqlite3DbFree(v->db, sIter.apSub);
86713 return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
86717 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
86721 ** Increment the nWrite counter in the VDBE if the cursor is not an
86726 || (pC->eCurType!=CURTYPE_SORTER
86727 && pC->eCurType!=CURTYPE_PSEUDO
86728 && !pC->isEphemeral)
86730 p->nWrite++;
86737 ** Assert if an Abort at this point in time might result in a corrupt
86741 assert( p->nWrite==0 || p->usesStmtJournal );
86750 ** resolve the P2 value to an actual address.
86769 Parse *pParse = p->pParse;
86770 int *aLabel = pParse->aLabel;
86772 assert( pParse->db->mallocFailed==0 ); /* tag-20230419-1 */
86773 p->readOnly = 1;
86774 p->bIsReader = 0;
86775 pOp = &p->aOp[p->nOp-1];
86776 assert( p->aOp[0].opcode==OP_Init );
86784 if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
86787 switch( pOp->opcode ){
86789 if( pOp->p2!=0 ) p->readOnly = 0;
86794 p->bIsReader = 1;
86802 p->readOnly = 0;
86803 p->bIsReader = 1;
86807 assert( pOp->p2>=0 );
86812 if( pOp->p2>nMaxVtabArgs ) nMaxVtabArgs = pOp->p2;
86817 /* The instruction immediately prior to VFilter will be an
86819 ** the code where OP_VFilter is generated at tag-20250207a. */
86820 assert( (pOp - p->aOp) >= 3 );
86821 assert( pOp[-1].opcode==OP_Integer );
86822 assert( pOp[-1].p2==pOp->p3+1 );
86823 n = pOp[-1].p1;
86830 if( pOp->p2<0 ){
86832 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
86833 ** have non-negative values for P2. */
86834 assert( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 );
86835 assert( ADDR(pOp->p2)<-pParse->nLabel );
86836 assert( aLabel!=0 ); /* True because of tag-20230419-1 */
86837 pOp->p2 = aLabel[ADDR(pOp->p2)];
86842 assert( pOp->p2>0
86843 || (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP0)!=0 );
86846 assert( pOp->p2<p->nOp
86847 || (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)==0 );
86852 ** non-jump opcodes less than SQLITE_MX_JUMP_CODE are guaranteed to
86853 ** have non-negative values for P2. */
86854 assert( (sqlite3OpcodeProperty[pOp->opcode]&OPFLG_JUMP)==0 || pOp->p2>=0);
86856 assert( pOp>p->aOp );
86857 pOp--;
86861 sqlite3DbNNFreeNN(p->db, pParse->aLabel);
86862 pParse->aLabel = 0;
86864 pParse->nLabel = 0;
86866 assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
86873 ** that will cause the program to halt with an error message.
86879 ** an OP_Return to iReturnAddr.
86881 ** A jump to an unresolved label means that the jump destination will be
86882 ** beyond the current address. That is normally a jump to an early
86887 ** is generated rather than an assert() or other error, so that ".eqp full"
86891 Vdbe *v, /* The byte-code program under construction */
86901 pParse = v->pParse;
86903 if( pParse->nErr ) return;
86905 assert( iLast<v->nOp );
86906 pOp = &v->aOp[iFirst];
86908 if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 ){
86909 int iDest = pOp->p2; /* Jump destination */
86911 if( pOp->opcode==OP_Gosub ) continue;
86912 if( pOp->p3==20230325 && pOp->opcode==OP_NotNull ){
86913 /* This is a deliberately taken illegal branch. tag-20230325-2 */
86919 if( j>=-pParse->nLabel || pParse->aLabel[j]<0 ){
86922 iDest = pParse->aLabel[j];
86926 for(; j<v->nOp; j++){
86927 VdbeOp *pX = &v->aOp[j];
86928 if( pX->opcode==OP_Return ){
86929 if( pX->p1==iRetReg ) break;
86932 if( pX->opcode==OP_Noop ) continue;
86933 if( pX->opcode==OP_Explain ) continue;
86961 assert( p->eVdbeState==VDBE_INIT_STATE );
86962 return p->nOp;
86971 ** sqlite3VdbeAddOpList() will always be non-NULL.
86975 assert( p->nOp + N <= p->nOpAlloc );
86981 ** an OP_ResultRow opcode. Fail an assert() if it does. This is used
86989 for(i=0; i<p->nOp; i++){
86990 assert( p->aOp[i].opcode!=OP_ResultRow );
87018 VdbeOp *aOp = p->aOp;
87019 assert( aOp && !p->db->mallocFailed );
87022 assert( DbMaskAllZero(p->btreeMask) );
87025 *pnOp = p->nOp;
87026 p->aOp = 0;
87034 ** Non-zero P2 arguments to jump instructions are automatically adjusted
87041 int iLineno /* Source-file line number of first opcode */
87046 assert( p->eVdbeState==VDBE_INIT_STATE );
87047 if( p->nOp + nOp > p->nOpAlloc && growOpArray(p, nOp) ){
87050 pFirst = pOut = &p->aOp[p->nOp];
87052 pOut->opcode = aOp->opcode;
87053 pOut->p1 = aOp->p1;
87054 pOut->p2 = aOp->p2;
87055 assert( aOp->p2>=0 );
87056 if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
87057 pOut->p2 += p->nOp;
87059 pOut->p3 = aOp->p3;
87060 pOut->p4type = P4_NOTUSED;
87061 pOut->p4.p = 0;
87062 pOut->p5 = 0;
87064 pOut->zComment = 0;
87067 pOut->iSrcLine = iLineno+i;
87072 if( p->db->flags & SQLITE_VdbeAddopTrace ){
87073 sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
87077 p->nOp += nOp;
87083 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
87093 if( IS_STMT_SCANSTATUS(p->db) ){
87094 i64 nByte = (1+(i64)p->nScan) * sizeof(ScanStatus);
87096 aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
87098 ScanStatus *pNew = &aNew[p->nScan++];
87100 pNew->addrExplain = addrExplain;
87101 pNew->addrLoop = addrLoop;
87102 pNew->addrVisit = addrVisit;
87103 pNew->nEst = nEst;
87104 pNew->zName = sqlite3DbStrDup(p->db, zName);
87105 p->aScan = aNew;
87123 if( IS_STMT_SCANSTATUS(p->db) ){
87126 for(ii=p->nScan-1; ii>=0; ii--){
87127 pScan = &p->aScan[ii];
87128 if( pScan->addrExplain==addrExplain ) break;
87132 if( addrEnd<0 ) addrEnd = sqlite3VdbeCurrentAddr(p)-1;
87133 for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
87134 if( pScan->aAddrRange[ii]==0 ){
87135 pScan->aAddrRange[ii] = addrStart;
87136 pScan->aAddrRange[ii+1] = addrEnd;
87155 if( IS_STMT_SCANSTATUS(p->db) ){
87158 for(ii=p->nScan-1; ii>=0; ii--){
87159 pScan = &p->aScan[ii];
87160 if( pScan->addrExplain==addrExplain ) break;
87164 if( addrLoop>0 ) pScan->addrLoop = addrLoop;
87165 if( addrVisit>0 ) pScan->addrVisit = addrVisit;
87178 sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
87182 sqlite3VdbeGetOp(p,addr)->p1 = val;
87185 assert( addr>=0 || p->db->mallocFailed );
87186 sqlite3VdbeGetOp(p,addr)->p2 = val;
87190 sqlite3VdbeGetOp(p,addr)->p3 = val;
87193 assert( p->nOp>0 || p->db->mallocFailed );
87194 if( p->nOp>0 ) p->aOp[p->nOp-1].p5 = p5;
87198 ** If the previous opcode is an OP_Column that delivers results
87205 while( pOp->opcode==OP_ReleaseReg ) pOp--;
87207 if( pOp->p3==iDest && pOp->opcode==OP_Column ){
87208 pOp->p5 |= OPFLAG_TYPEOFARG;
87217 sqlite3VdbeChangeP2(p, addr, p->nOp);
87223 ** the previous opcode (and is thus a no-op) then simply back up
87227 ** This routine is an optimization of sqlite3VdbeJumpHere() that
87228 ** strives to omit useless byte-code like this:
87234 if( addr==p->nOp-1 ){
87235 assert( p->aOp[addr].opcode==OP_Once
87236 || p->aOp[addr].opcode==OP_If
87237 || p->aOp[addr].opcode==OP_FkIfZero );
87238 assert( p->aOp[addr].p4type==0 );
87240 sqlite3VdbeGetLastOp(p)->iSrcLine = 0; /* Erase VdbeCoverage() macros */
87242 p->nOp--;
87244 sqlite3VdbeChangeP2(p, addr, p->nOp);
87255 if( (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
87264 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
87269 freeEphemeralFunction(db, p->pFunc);
87287 if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
87301 if( db->pnBytesFreed==0 ){
87309 if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
87313 if( db->pnBytesFreed==0 ) sqlite3DeleteTable(db, (Table*)p4);
87318 sqlite3DbFree(db, pSig->zAff);
87334 Op *pOp = &aOp[nOp-1];
87336 if( pOp->p4type <= P4_FREE_IF_LE ) freeP4(db, pOp->p4type, pOp->p4.p);
87338 sqlite3DbFree(db, pOp->zComment);
87341 pOp--;
87349 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
87353 p->pNext = pVdbe->pProgram;
87354 pVdbe->pProgram = p;
87361 return pVdbe->pProgram!=0;
87369 if( p->db->mallocFailed ) return 0;
87370 assert( addr>=0 && addr<p->nOp );
87371 pOp = &p->aOp[addr];
87372 freeP4(p->db, pOp->p4type, pOp->p4.p);
87373 pOp->p4type = P4_NOTUSED;
87374 pOp->p4.z = 0;
87375 pOp->opcode = OP_Noop;
87381 ** then remove it. Return true if and only if an opcode was removed.
87384 if( p->nOp>0 && p->aOp[p->nOp-1].opcode==op ){
87385 return sqlite3VdbeChangeToNoop(p, p->nOp-1);
87393 ** Generate an OP_ReleaseReg opcode to indicate that a range of
87403 if( N==0 || OptimizationDisabled(pParse->db, SQLITE_ReleaseReg) ) return;
87404 assert( pParse->pVdbe );
87406 assert( iFirst+N-1<=pParse->nMem );
87411 N--;
87413 while( N>0 && N<=32 && (mask & MASKBIT32(N-1))!=0 ){
87414 mask &= ~MASKBIT32(N-1);
87415 N--;
87419 sqlite3VdbeAddOp3(pParse->pVdbe, OP_ReleaseReg, iFirst, N, *(int*)&mask);
87420 if( bUndefine ) sqlite3VdbeChangeP5(pParse->pVdbe, 1);
87448 if( pOp->p4type ){
87449 assert( pOp->p4type > P4_FREE_IF_LE );
87450 pOp->p4type = 0;
87451 pOp->p4.p = 0;
87454 sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
87457 pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
87458 pOp->p4type = P4_DYNAMIC;
87465 db = p->db;
87466 assert( p->eVdbeState==VDBE_INIT_STATE );
87467 assert( p->aOp!=0 || db->mallocFailed );
87468 if( db->mallocFailed ){
87472 assert( p->nOp>0 );
87473 assert( addr<p->nOp );
87475 addr = p->nOp - 1;
87477 pOp = &p->aOp[addr];
87478 if( n>=0 || pOp->p4type ){
87483 /* Note: this cast is safe, because the origin data point was an int
87485 pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
87486 pOp->p4type = P4_INT32;
87489 pOp->p4.p = (void*)zP4;
87490 pOp->p4type = (signed char)n;
87497 ** to the value defined by the arguments. This is a high-speed
87508 if( p->db->mallocFailed ){
87509 freeP4(p->db, n, pP4);
87512 assert( p->nOp>0 );
87513 pOp = &p->aOp[p->nOp-1];
87514 assert( pOp->p4type==P4_NOTUSED );
87515 pOp->p4type = n;
87516 pOp->p4.p = pP4;
87525 Vdbe *v = pParse->pVdbe;
87536 ** insert a No-op and add the comment to that new instruction. This
87541 assert( p->nOp>0 || p->aOp==0 );
87542 assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->pParse->nErr>0 );
87543 if( p->nOp ){
87544 assert( p->aOp );
87545 sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
87546 p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
87573 sqlite3VdbeGetLastOp(v)->iSrcLine = iLine;
87578 ** Return the opcode for a given address. The address must be non-negative.
87585 ** after an OOM fault without having to check to see if the return from
87594 assert( p->eVdbeState==VDBE_INIT_STATE );
87595 assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
87596 if( p->db->mallocFailed ){
87599 return &p->aOp[addr];
87606 return sqlite3VdbeGetOp(p, p->nOp - 1);
87611 ** Return an integer value for one of the parameters to the opcode pOp
87615 if( c=='1' ) return pOp->p1;
87616 if( c=='2' ) return pOp->p2;
87617 if( c=='3' ) return pOp->p3;
87618 if( c=='4' ) return pOp->p4.i;
87619 return pOp->p5;
87626 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
87630 ** "PX" -> "r[X]"
87631 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
87632 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
87633 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
87636 sqlite3 *db, /* Optional - Oom error reporting only */
87648 zOpName = sqlite3OpcodeName(pOp->opcode);
87664 if( pOp->zComment && pOp->zComment[0] ){
87665 sqlite3_str_appendall(&x, pOp->zComment);
87682 sqlite3_str_appendf(&x, "%d..%d", v1, v1+v2-1);
87685 sqlite3_context *pCtx = pOp->p4.pCtx;
87686 if( pOp->p4type!=P4_FUNCCTX || pCtx->argc==1 ){
87688 }else if( pCtx->argc>1 ){
87689 sqlite3_str_appendf(&x, "%d..%d", v1, v1+pCtx->argc-1);
87692 x.nChar -= 2;
87698 if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
87707 if( !seenCom && pOp->zComment ){
87708 sqlite3_str_appendf(&x, "; %s", pOp->zComment);
87710 }else if( pOp->zComment ){
87711 sqlite3_str_appendall(&x, pOp->zComment);
87722 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
87727 switch( pExpr->op ){
87730 sqlite3_str_appendf(p, "%Q", pExpr->u.zToken);
87733 sqlite3_str_appendf(p, "%d", pExpr->u.iValue);
87739 sqlite3_str_appendf(p, "r[%d]", pExpr->iTable);
87743 if( pExpr->iColumn<0 ){
87746 sqlite3_str_appendf(p, "c%d", (int)pExpr->iColumn);
87784 displayP4Expr(p, pExpr->pLeft);
87785 if( pExpr->pRight ){
87787 displayP4Expr(p, pExpr->pRight);
87797 ** Compute a string that describes the P4 parameter for an opcode.
87805 switch( pOp->p4type ){
87808 KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
87809 assert( pKeyInfo->aSortFlags!=0 );
87810 sqlite3_str_appendf(&x, "k(%d", pKeyInfo->nKeyField);
87811 for(j=0; j<pKeyInfo->nKeyField; j++){
87812 CollSeq *pColl = pKeyInfo->aColl[j];
87813 const char *zColl = pColl ? pColl->zName : "";
87816 (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_DESC) ? "-" : "",
87817 (pKeyInfo->aSortFlags[j] & KEYINFO_ORDER_BIGNULL)? "N." : "",
87825 displayP4Expr(&x, pOp->p4.pExpr);
87831 CollSeq *pColl = pOp->p4.pColl;
87832 assert( pColl->enc<4 );
87833 sqlite3_str_appendf(&x, "%.18s-%s", pColl->zName,
87834 encnames[pColl->enc]);
87838 FuncDef *pDef = pOp->p4.pFunc;
87839 sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
87843 FuncDef *pDef = pOp->p4.pCtx->pFunc;
87844 sqlite3_str_appendf(&x, "%s(%d)", pDef->zName, pDef->nArg);
87848 sqlite3_str_appendf(&x, "%lld", *pOp->p4.pI64);
87852 sqlite3_str_appendf(&x, "%d", pOp->p4.i);
87856 sqlite3_str_appendf(&x, "%.16g", *pOp->p4.pReal);
87860 Mem *pMem = pOp->p4.pMem;
87861 if( pMem->flags & MEM_Str ){
87862 zP4 = pMem->z;
87863 }else if( pMem->flags & (MEM_Int|MEM_IntReal) ){
87864 sqlite3_str_appendf(&x, "%lld", pMem->u.i);
87865 }else if( pMem->flags & MEM_Real ){
87866 sqlite3_str_appendf(&x, "%.16g", pMem->u.r);
87867 }else if( pMem->flags & MEM_Null ){
87870 assert( pMem->flags & MEM_Blob );
87877 sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
87884 u32 *ai = pOp->p4.ai;
87885 u32 n = ai[0]; /* The first element of an INTARRAY is always the
87898 zP4 = pOp->p4.pTab->zName;
87902 SubrtnSig *pSig = pOp->p4.pSubrtnSig;
87903 sqlite3_str_appendf(&x, "subrtnsig:%d,%s", pSig->selId, pSig->zAff);
87907 zP4 = pOp->p4.z;
87919 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
87923 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
87924 ** p->btreeMask of databases that will require a lock.
87927 assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
87928 assert( i<(int)sizeof(p->btreeMask)*8 );
87929 DbMaskSet(p->btreeMask, i);
87930 if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
87931 DbMaskSet(p->lockMask, i);
87937 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
87939 ** that may be accessed by the VM passed as an argument. In doing so it also
87941 ** that the correct busy-handler callback is invoked if required.
87943 ** If SQLite is not threadsafe but does support shared-cache mode, then
87948 ** If SQLite is not threadsafe and does not support shared-cache mode, this
87949 ** function is a no-op.
87951 ** The p->btreeMask field is a bitmask of all btrees that the prepared
87952 ** statement p will ever use. Let N be the number of bits in p->btreeMask
87962 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
87963 db = p->db;
87964 aDb = db->aDb;
87965 nDb = db->nDb;
87967 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
87983 db = p->db;
87984 aDb = db->aDb;
87985 nDb = db->nDb;
87987 if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
87993 if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
88006 static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
88020 sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3,
88021 zP4 ? zP4 : "", pOp->p5,
88032 ** Initialize an array of N Mem element.
88034 ** This is a high-runner, so only those fields that really do need to
88050 p->flags = flags;
88051 p->db = db;
88052 p->szMalloc = 0;
88054 p->pScopyFrom = 0;
88055 p->bScopy = 0;
88058 }while( (--N)>0 );
88063 ** Release auxiliary memory held in an array of N Mem elements.
88073 sqlite3 *db = p->db;
88075 if( db->pnBytesFreed ){
88077 if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
88085 /* This block is really an inlined version of sqlite3VdbeMemRelease()
88091 ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
88092 ** sqlite3MemRelease() were called from here. With -O2, this jumps
88097 testcase( p->flags & MEM_Agg );
88098 testcase( p->flags & MEM_Dyn );
88099 if( p->flags&(MEM_Agg|MEM_Dyn) ){
88100 testcase( (p->flags & MEM_Dyn)!=0 && p->xDel==sqlite3VdbeFrameMemDel );
88102 p->flags = MEM_Undefined;
88103 }else if( p->szMalloc ){
88104 sqlite3DbNNFreeNN(db, p->zMalloc);
88105 p->szMalloc = 0;
88106 p->flags = MEM_Undefined;
88110 p->flags = MEM_Undefined;
88125 if( pFrame->iFrameMagic!=SQLITE_FRAME_MAGIC ) return 0;
88132 ** This is a destructor on a Mem object (which is really an sqlite3_value)
88141 pFrame->pParent = pFrame->v->pDelFrame;
88142 pFrame->v->pDelFrame = pFrame;
88162 int nSub = 0; /* Number of sub-vdbes seen so far */
88163 SubProgram **apSub = 0; /* Array of sub-vdbes */
88174 ** encountered, but p->pc will eventually catch up to nRow.
88176 nRow = p->nOp;
88178 if( pSub->flags&MEM_Blob ){
88181 nSub = pSub->n/sizeof(Vdbe*);
88182 apSub = (SubProgram **)pSub->z;
88185 nRow += apSub[i]->nOp;
88192 p->rc = SQLITE_OK;
88196 if( i<p->nOp ){
88199 aOp = p->aOp;
88204 i -= p->nOp;
88207 for(j=0; i>=apSub[j]->nOp; j++){
88208 i -= apSub[j]->nOp;
88209 assert( i<apSub[j]->nOp || j+1<nSub );
88211 aOp = apSub[j]->aOp;
88214 /* When an OP_Program opcode is encounter (the only opcode that has
88216 ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
88226 p->rc = sqlite3VdbeMemGrow(pSub, nByte, nSub!=0);
88227 if( p->rc!=SQLITE_OK ){
88231 apSub = (SubProgram **)pSub->z;
88234 pSub->n = nSub*sizeof(SubProgram*);
88235 nRow += aOp[i].p4.pProgram->nOp;
88242 if( pOp->opcode==OP_OpenRead ) break;
88243 if( pOp->opcode==OP_OpenWrite && (pOp->p5 & OPFLAG_P2ISREG)==0 ) break;
88244 if( pOp->opcode==OP_ReopenIdx ) break;
88268 VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
88270 for(i=0; i<p->nChildCsr; i++){
88271 if( apCsr[i] ) sqlite3VdbeFreeCursorNN(p->v, apCsr[i]);
88273 releaseMemArray(aMem, p->nChildMem);
88274 sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
88275 sqlite3DbFree(p->v->db, p);
88286 ** When p->explain==1, each instruction is listed. When
88287 ** p->explain==2, only OP_Explain instructions are listed and these
88288 ** are shown in a different format. p->explain==2 is used to implement
88290 ** 2018-04-24: In p->explain==2 mode, the OP_Init opcodes of triggers
88294 ** When p->explain==1, first the main program is listed, then each of
88301 sqlite3 *db = p->db; /* The database connection */
88304 Mem *pMem = &p->aMem[1]; /* First Mem of result set */
88305 int bListSubprogs = (p->explain==1 || (db->flags & SQLITE_TriggerEQP)!=0);
88309 assert( p->explain );
88310 assert( p->eVdbeState==VDBE_RUN_STATE );
88311 assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
88315 ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
88319 if( p->rc==SQLITE_NOMEM ){
88328 ** commandeer the 9th cell to use as storage for an array of pointers
88331 assert( p->nMem>9 );
88332 pSub = &p->aMem[9];
88338 rc = sqlite3VdbeNextOpcode(p, pSub, p->explain==2, &p->pc, &i, &aOp);
88342 if( AtomicLoad(&db->u1.isInterrupted) ){
88343 p->rc = SQLITE_INTERRUPT;
88345 sqlite3VdbeError(p, sqlite3ErrStr(p->rc));
88348 if( p->explain==2 ){
88349 sqlite3VdbeMemSetInt64(pMem, pOp->p1);
88350 sqlite3VdbeMemSetInt64(pMem+1, pOp->p2);
88351 sqlite3VdbeMemSetInt64(pMem+2, pOp->p3);
88352 sqlite3VdbeMemSetStr(pMem+3, zP4, -1, SQLITE_UTF8, sqlite3_free);
88353 assert( p->nResColumn==4 );
88356 sqlite3VdbeMemSetStr(pMem+1, (char*)sqlite3OpcodeName(pOp->opcode),
88357 -1, SQLITE_UTF8, SQLITE_STATIC);
88358 sqlite3VdbeMemSetInt64(pMem+2, pOp->p1);
88359 sqlite3VdbeMemSetInt64(pMem+3, pOp->p2);
88360 sqlite3VdbeMemSetInt64(pMem+4, pOp->p3);
88362 sqlite3VdbeMemSetInt64(pMem+6, pOp->p5);
88366 sqlite3VdbeMemSetStr(pMem+7, zCom, -1, SQLITE_UTF8, sqlite3_free);
88371 sqlite3VdbeMemSetStr(pMem+5, zP4, -1, SQLITE_UTF8, sqlite3_free);
88372 assert( p->nResColumn==8 );
88374 p->pResultRow = pMem;
88375 if( db->mallocFailed ){
88376 p->rc = SQLITE_NOMEM;
88379 p->rc = SQLITE_OK;
88394 if( p->zSql ){
88395 z = p->zSql;
88396 }else if( p->nOp>=1 ){
88397 const VdbeOp *pOp = &p->aOp[0];
88398 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
88399 z = pOp->p4.z;
88409 ** Print an IOTRACE message showing SQL content.
88412 int nOp = p->nOp;
88416 pOp = &p->aOp[0];
88417 if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
88420 sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
88424 if( z[i-1]!=' ' ){
88437 /* An instance of this object describes bulk memory available for use
88447 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
88466 assert( EIGHT_BYTE_ALIGNMENT(p->pSpace) );
88469 if( nByte <= p->nFree ){
88470 p->nFree -= nByte;
88471 pBuf = &p->pSpace[p->nFree];
88473 p->nNeeded += nByte;
88489 assert( p->eVdbeState==VDBE_INIT_STATE
88490 || p->eVdbeState==VDBE_READY_STATE
88491 || p->eVdbeState==VDBE_HALT_STATE );
88495 assert( p->nOp>0 );
88497 p->eVdbeState = VDBE_READY_STATE;
88500 for(i=0; i<p->nMem; i++){
88501 assert( p->aMem[i].db==p->db );
88504 p->pc = -1;
88505 p->rc = SQLITE_OK;
88506 p->errorAction = OE_Abort;
88507 p->nChange = 0;
88508 p->cacheCtr = 1;
88509 p->minWriteFileFormat = 255;
88510 p->iStatement = 0;
88511 p->nFkConstraint = 0;
88513 for(i=0; i<p->nOp; i++){
88514 p->aOp[i].nExec = 0;
88515 p->aOp[i].nCycle = 0;
88532 ** the Vdbe becomes an independent entity and the Parse object can be
88551 assert( p->nOp>0 );
88553 assert( p->eVdbeState==VDBE_INIT_STATE );
88554 assert( pParse==p->pParse );
88555 assert( pParse->db==p->db );
88556 p->pVList = pParse->pVList;
88557 pParse->pVList = 0;
88558 db = p->db;
88559 assert( db->mallocFailed==0 );
88560 nVar = pParse->nVar;
88561 nMem = pParse->nMem;
88562 nCursor = pParse->nTab;
88563 nArg = pParse->nMaxArg;
88577 n = ROUND8P(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
88578 x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
88580 x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
88585 p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
88586 if( pParse->explain ){
88588 p->explain = pParse->explain;
88589 p->nResColumn = 12 - 4*p->explain;
88591 p->expired = 0;
88599 ** This two-pass approach that reuses as much memory as possible from
88604 p->aMem = allocSpace(&x, 0, nMem*sizeof(Mem));
88605 p->aVar = allocSpace(&x, 0, nVar*sizeof(Mem));
88606 p->apArg = allocSpace(&x, 0, nArg*sizeof(Mem*));
88607 p->apCsr = allocSpace(&x, 0, nCursor*sizeof(VdbeCursor*));
88609 x.pSpace = p->pFree = sqlite3DbMallocRawNN(db, x.nNeeded);
88611 if( !db->mallocFailed ){
88612 p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
88613 p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
88614 p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
88615 p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
88619 p->napArg = nArg;
88622 if( db->mallocFailed ){
88623 p->nVar = 0;
88624 p->nCursor = 0;
88625 p->nMem = 0;
88627 p->nCursor = nCursor;
88628 p->nVar = (ynVar)nVar;
88629 initMemArray(p->aVar, nVar, db, MEM_Null);
88630 p->nMem = nMem;
88631 initMemArray(p->aMem, nMem, db, MEM_Undefined);
88632 memset(p->apCsr, 0, nCursor*sizeof(VdbeCursor*));
88645 VdbeTxtBlbCache *pCache = pCx->pCache;
88646 assert( pCx->colCache );
88647 pCx->colCache = 0;
88648 pCx->pCache = 0;
88649 if( pCache->pCValue ){
88650 sqlite3RCStrUnref(pCache->pCValue);
88651 pCache->pCValue = 0;
88653 sqlite3DbFree(p->db, pCache);
88657 if( pCx->colCache ){
88661 switch( pCx->eCurType ){
88663 sqlite3VdbeSorterClose(p->db, pCx);
88667 assert( pCx->uc.pCursor!=0 );
88668 sqlite3BtreeCloseCursor(pCx->uc.pCursor);
88673 sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
88674 const sqlite3_module *pModule = pVCur->pVtab->pModule;
88675 assert( pVCur->pVtab->nRef>0 );
88676 pVCur->pVtab->nRef--;
88677 pModule->xClose(pVCur);
88689 for(i=0; i<p->nCursor; i++){
88690 VdbeCursor *pC = p->apCsr[i];
88693 p->apCsr[i] = 0;
88700 ** is used, for example, when a trigger sub-program is halted to restore
88704 Vdbe *v = pFrame->v;
88706 v->aOp = pFrame->aOp;
88707 v->nOp = pFrame->nOp;
88708 v->aMem = pFrame->aMem;
88709 v->nMem = pFrame->nMem;
88710 v->apCsr = pFrame->apCsr;
88711 v->nCursor = pFrame->nCursor;
88712 v->db->lastRowid = pFrame->lastRowid;
88713 v->nChange = pFrame->nChange;
88714 v->db->nChange = pFrame->nDbChange;
88715 sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
88716 v->pAuxData = pFrame->pAuxData;
88717 pFrame->pAuxData = 0;
88718 return pFrame->pc;
88730 if( p->pFrame ){
88732 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
88734 p->pFrame = 0;
88735 p->nFrame = 0;
88737 assert( p->nFrame==0 );
88739 releaseMemArray(p->aMem, p->nMem);
88740 while( p->pDelFrame ){
88741 VdbeFrame *pDel = p->pDelFrame;
88742 p->pDelFrame = pDel->pParent;
88747 if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
88748 assert( p->pAuxData==0 );
88755 ** be called on an SQL statement before sqlite3_step().
88759 sqlite3 *db = p->db;
88761 if( p->nResAlloc ){
88762 releaseMemArray(p->aColName, p->nResAlloc*COLNAME_N);
88763 sqlite3DbFree(db, p->aColName);
88766 p->nResColumn = p->nResAlloc = (u16)nResColumn;
88767 p->aColName = (Mem*)sqlite3DbMallocRawNN(db, sizeof(Mem)*n );
88768 if( p->aColName==0 ) return;
88769 initMemArray(p->aColName, n, db, MEM_Null);
88791 assert( idx<p->nResAlloc );
88793 if( p->db->mallocFailed ){
88797 assert( p->aColName!=0 );
88798 pColName = &(p->aColName[idx+var*p->nResAlloc]);
88799 rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
88800 assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
88807 ** write-transaction spanning more than one database file, this routine
88808 ** takes care of the super-journal trickery.
88812 int nTrans = 0; /* Number of databases with an active write-transaction
88813 ** that are candidates for a two-phase commit using a
88814 ** super-journal */
88827 ** be done before determining whether a super-journal file is
88828 ** required, as an xSync() callback may add an attached database
88836 ** one database file has an open write transaction, a super-journal
88837 ** file is required for an atomic commit.
88839 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
88840 Btree *pBt = db->aDb[i].pBt;
88842 /* Whether or not a database might need a super-journal depends upon
88844 ** journal modes use a super-journal and which do not */
88857 if( db->aDb[i].safety_level!=PAGER_SYNCHRONOUS_OFF
88872 /* If there are any write-transactions at all, invoke the commit hook */
88873 if( needXcommit && db->xCommitCallback ){
88874 rc = db->xCommitCallback(db->pCommitArg);
88880 /* The simple case - no more than one database file (not counting the
88882 ** super-journal.
88886 ** that case we do not support atomic multi-file commits, so use the
88889 if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
88892 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
88893 Btree *pBt = db->aDb[i].pBt;
88900 ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
88904 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
88905 Btree *pBt = db->aDb[i].pBt;
88915 /* The complex case - There is a multi-file write-transaction active.
88916 ** This requires a super-journal file to ensure the transaction is
88921 sqlite3_vfs *pVfs = db->pVfs;
88922 char *zSuper = 0; /* File-name for the super-journal */
88923 char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
88930 /* Select a super-journal file name */
88948 sqlite3_snprintf(13, &zSuper[nMainFile], "-mj%06X9%02X",
88950 /* The antipenultimate character of the super-journal name must
88952 assert( zSuper[sqlite3Strlen30(zSuper)-3]=='9' );
88957 /* Open the super-journal. */
88964 sqlite3DbFree(db, zSuper-4);
88969 ** super-journal file. If an error occurs at this point close
88970 ** and delete the super-journal file. All the individual journal files
88971 ** still have 'null' as the super-journal pointer, so they will roll
88974 for(i=0; i<db->nDb; i++){
88975 Btree *pBt = db->aDb[i].pBt;
88987 sqlite3DbFree(db, zSuper-4);
88993 /* Sync the super-journal file. If the IOCAP_SEQUENTIAL device
89001 sqlite3DbFree(db, zSuper-4);
89006 ** sets the super-journal pointer in each individual journal. If
89007 ** an error occurs here, do not delete the super-journal file.
89011 ** super-journal file will be orphaned. But we cannot delete it,
89012 ** in case the super-journal file name was written into the journal
89015 for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
89016 Btree *pBt = db->aDb[i].pBt;
89024 sqlite3DbFree(db, zSuper-4);
89028 /* Delete the super-journal file. This commits the transaction. After
89033 sqlite3DbFree(db, zSuper-4);
89044 ** may be lying around. Returning an error code won't help matters.
89048 for(i=0; i<db->nDb; i++){
89049 Btree *pBt = db->aDb[i].pBt;
89067 ** currently active. An assertion fails if the two counts do not match.
89068 ** This is an internal self-check only - it is not an essential processing
89071 ** This is a no-op if NDEBUG is defined.
89079 p = db->pVdbe;
89083 if( p->readOnly==0 ) nWrite++;
89084 if( p->bIsReader ) nRead++;
89086 p = p->pVNext;
89088 assert( cnt==db->nVdbeActive );
89089 assert( nWrite==db->nVdbeWrite );
89090 assert( nRead==db->nVdbeRead );
89097 ** If the Vdbe passed as the first argument opened a statement-transaction,
89103 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
89107 sqlite3 *const db = p->db;
89110 const int iSavepoint = p->iStatement-1;
89113 assert( db->nStatement>0 );
89114 assert( p->iStatement==(db->nStatement+db->nSavepoint) );
89116 for(i=0; i<db->nDb; i++){
89118 Btree *pBt = db->aDb[i].pBt;
89131 db->nStatement--;
89132 p->iStatement = 0;
89147 db->nDeferredCons = p->nStmtDefCons;
89148 db->nDeferredImmCons = p->nStmtDefImmCons;
89153 if( p->db->nStatement && p->iStatement ){
89162 ** handle associated with the VM passed as an argument is about to be
89168 ** and write an error message to it. Then return SQLITE_ERROR.
89172 sqlite3 *db = p->db;
89173 if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
89174 || (!deferred && p->nFkConstraint>0)
89176 p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
89177 p->errorAction = OE_Abort;
89179 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ) return SQLITE_ERROR;
89195 ** Return an error code. If the commit could not complete because of
89201 sqlite3 *db = p->db;
89214 ** Then the internal cache might have been left in an inconsistent
89219 assert( p->eVdbeState==VDBE_RUN_STATE );
89220 if( db->mallocFailed ){
89221 p->rc = SQLITE_NOMEM_BKPT;
89228 if( p->bIsReader ){
89229 int mrc; /* Primary error code from p->rc */
89237 if( p->rc ){
89238 mrc = p->rc & 0xff;
89247 /* If the query was read-only and the error code is SQLITE_INTERRUPT,
89252 ** Even if the statement is read-only, it is important to perform
89254 ** occurred while writing to the journal, sub-journal or database
89255 ** file as part of an effort to free up cache space (see function
89259 if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
89260 if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
89268 db->autoCommit = 1;
89269 p->nChange = 0;
89275 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
89279 /* If the auto-commit flag is set and this is the only active writer
89286 && db->autoCommit
89287 && db->nVdbeWrite==(p->readOnly==0)
89289 if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
89292 if( NEVER(p->readOnly) ){
89297 }else if( db->flags & SQLITE_CorruptRdOnly ){
89299 db->flags &= ~SQLITE_CorruptRdOnly;
89301 /* The auto-commit flag is true, the vdbe program was successful
89302 ** or hit an 'OR FAIL' constraint and there are no deferred foreign
89307 if( rc==SQLITE_BUSY && p->readOnly ){
89312 p->rc = rc;
89314 p->nChange = 0;
89316 db->nDeferredCons = 0;
89317 db->nDeferredImmCons = 0;
89318 db->flags &= ~(u64)SQLITE_DeferFKs;
89321 }else if( p->rc==SQLITE_SCHEMA && db->nVdbeActive>1 ){
89322 p->nChange = 0;
89325 p->nChange = 0;
89327 db->nStatement = 0;
89329 if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
89331 }else if( p->errorAction==OE_Abort ){
89336 db->autoCommit = 1;
89337 p->nChange = 0;
89341 /* If eStatementOp is non-zero, then a statement transaction needs to
89343 ** do so. If this operation returns an error, and the current statement
89350 if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
89351 p->rc = rc;
89352 sqlite3DbFree(db, p->zErrMsg);
89353 p->zErrMsg = 0;
89357 db->autoCommit = 1;
89358 p->nChange = 0;
89362 /* If this was an INSERT, UPDATE or DELETE and no statement transaction
89363 ** has been rolled back, update the database connection change-counter.
89365 if( p->changeCntOn ){
89367 sqlite3VdbeSetChanges(db, p->nChange);
89371 p->nChange = 0;
89379 db->nVdbeActive--;
89380 if( !p->readOnly ) db->nVdbeWrite--;
89381 if( p->bIsReader ) db->nVdbeRead--;
89382 assert( db->nVdbeActive>=db->nVdbeRead );
89383 assert( db->nVdbeRead>=db->nVdbeWrite );
89384 assert( db->nVdbeWrite>=0 );
89385 p->eVdbeState = VDBE_HALT_STATE;
89387 if( db->mallocFailed ){
89388 p->rc = SQLITE_NOMEM_BKPT;
89391 /* If the auto-commit flag is set to true, then any locks that were held
89393 ** to invoke any required unlock-notify callbacks.
89395 if( db->autoCommit ){
89399 assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
89400 return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
89406 ** in p->rc. This routine sets that result back to SQLITE_OK.
89409 p->rc = SQLITE_OK;
89421 sqlite3 *db = p->db;
89422 int rc = p->rc;
89423 if( p->zErrMsg ){
89424 db->bBenignMalloc++;
89426 if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
89427 sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
89429 db->bBenignMalloc--;
89430 }else if( db->pErr ){
89431 sqlite3ValueSetNull(db->pErr);
89433 db->errCode = rc;
89434 db->errByteOffset = -1;
89440 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
89444 if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
89445 char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
89446 assert( v->db->init.busy==0 );
89449 sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
89451 sqlite3DbFree(v->db, zExpanded);
89476 db = p->db;
89478 /* If the VM did not run to completion or if it encountered an
89482 if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
89489 if( p->pc>=0 ){
89491 if( db->pErr || p->zErrMsg ){
89494 db->errCode = p->rc;
89503 if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
89504 if( p->aMem ){
89505 for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
89508 if( p->zErrMsg ){
89509 sqlite3DbFree(db, p->zErrMsg);
89510 p->zErrMsg = 0;
89512 p->pResultRow = 0;
89514 p->nWrite = 0;
89523 fprintf(out, "---- ");
89524 for(i=0; i<p->nOp; i++){
89525 fprintf(out, "%02x", p->aOp[i].opcode);
89528 if( p->zSql ){
89530 fprintf(out, "-- ");
89531 for(i=0; (c = p->zSql[i])!=0; i++){
89532 if( pc=='\n' ) fprintf(out, "-- ");
89538 for(i=0; i<p->nOp; i++){
89540 i64 cnt = p->aOp[i].nExec;
89541 i64 cycles = p->aOp[i].nCycle;
89548 sqlite3VdbePrintOp(out, i, &p->aOp[i]);
89554 return p->rc & db->errMask;
89558 ** Clean up and delete a VDBE after execution. Return an integer which is
89566 if( p->eVdbeState>=VDBE_READY_STATE ){
89568 assert( (rc & p->db->errMask)==rc );
89594 || (pAux->iAuxOp==iOp
89595 && pAux->iAuxArg>=0
89596 && (pAux->iAuxArg>31 || !(mask & MASKBIT32(pAux->iAuxArg))))
89598 testcase( pAux->iAuxArg==31 );
89599 if( pAux->xDeleteAux ){
89600 pAux->xDeleteAux(pAux->pAux);
89602 *pp = pAux->pNextAux;
89605 pp= &pAux->pNextAux;
89621 assert( p->db==0 || p->db==db );
89622 if( p->aColName ){
89623 releaseMemArray(p->aColName, p->nResAlloc*COLNAME_N);
89624 sqlite3DbNNFreeNN(db, p->aColName);
89626 for(pSub=p->pProgram; pSub; pSub=pNext){
89627 pNext = pSub->pNext;
89628 vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
89631 if( p->eVdbeState!=VDBE_INIT_STATE ){
89632 releaseMemArray(p->aVar, p->nVar);
89633 if( p->pVList ) sqlite3DbNNFreeNN(db, p->pVList);
89634 if( p->pFree ) sqlite3DbNNFreeNN(db, p->pFree);
89636 vdbeFreeOpArray(db, p->aOp, p->nOp);
89637 if( p->zSql ) sqlite3DbNNFreeNN(db, p->zSql);
89639 sqlite3DbFree(db, p->zNormSql);
89642 for(pThis=p->pDblStr; pThis; pThis=pNxt){
89643 pNxt = pThis->pNextStr;
89651 for(i=0; i<p->nScan; i++){
89652 sqlite3DbFree(db, p->aScan[i].zName);
89654 sqlite3DbFree(db, p->aScan);
89660 ** Delete an entire VDBE.
89666 db = p->db;
89668 assert( sqlite3_mutex_held(db->mutex) );
89670 if( db->pnBytesFreed==0 ){
89671 assert( p->ppVPrev!=0 );
89672 *p->ppVPrev = p->pVNext;
89673 if( p->pVNext ){
89674 p->pVNext->ppVPrev = p->ppVPrev;
89682 ** carried out. Seek the cursor now. If an error occurs, return
89690 assert( p->deferredMoveto );
89691 assert( p->isTable );
89692 assert( p->eCurType==CURTYPE_BTREE );
89693 rc = sqlite3BtreeTableMoveto(p->uc.pCursor, p->movetoTarget, 0, &res);
89699 p->deferredMoveto = 0;
89700 p->cacheStatus = CACHE_STALE;
89713 assert( p->eCurType==CURTYPE_BTREE );
89714 assert( p->uc.pCursor!=0 );
89715 assert( sqlite3BtreeCursorHasMoved(p->uc.pCursor) );
89716 rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
89717 p->cacheStatus = CACHE_STALE;
89718 if( isDifferentRow ) p->nullRow = 1;
89727 assert( p->eCurType==CURTYPE_BTREE || IsNullCursor(p) );
89728 if( sqlite3BtreeCursorHasMoved(p->uc.pCursor) ){
89740 ** sqlite3VdbeSerialPut() <--- in-lined into OP_MakeRecord as of 2022-04-02
89745 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
89748 ** In an SQLite index record, the serial type is stored directly before
89752 ** serial-type and data blob separately.
89757 ** -------------- --------------- ---------------
89769 ** N>=12 and even (N-12)/2 BLOB
89770 ** N>=13 and odd (N-13)/2 text
89778 ** Return the serial-type for the value stored in pMem.
89782 ** 2019-07-11: The primary user of this subroutine was the OP_MakeRecord
89783 ** opcode in the byte-code engine. But by moving this routine in-line, we
89789 int flags = pMem->flags;
89799 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
89800 i64 i = pMem->u.i;
89825 ** as an integer, then we might as well make it an 8-byte floating
89827 pMem->u.r = (double)pMem->u.i;
89828 pMem->flags &= ~MEM_IntReal;
89829 pMem->flags |= MEM_Real;
89838 assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
89839 assert( pMem->n>=0 );
89840 n = (u32)pMem->n;
89842 n += pMem->u.nZero;
89870 ** Return the length of the data corresponding to the supplied serial-type.
89874 return (serial_type-12)/2;
89877 || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
89887 ** If we are on an architecture with mixed-endian floating
89891 ** For most architectures, this is a no-op.
89893 ** (later): It is reported to me that the mixed-endian problem
89894 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
89895 ** that early versions of GCC stored the two words of a 64-bit
89902 ** Developers using SQLite on an ARM7 should compile and run their
89903 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
89907 ** (2007-08-30) Frank van Vugt has studied this problem closely
89910 ** emulation that uses only 32-bit mantissas instead of a full
89911 ** 48-bits as required by the IEEE standard. (This is the
89914 ** the necessary byte swapping is carried out using a 64-bit integer
89915 ** rather than a 64-bit float. Frank assures us that the code here
89938 ** big-endian integer. Return the equivalent native integer
89964 /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
89965 ** twos-complement integer. */
89966 pMem->u.i = *(i64*)&x;
89967 pMem->flags = MEM_Int;
89968 testcase( pMem->u.i<0 );
89970 /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
89975 ** defined that 64-bit floating point values really are mixed
89984 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
89986 memcpy(&pMem->u.r, &x, sizeof(x));
89987 pMem->flags = IsNaN(x) ? MEM_Null : MEM_Real;
89997 assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
89999 memcpy(&pMem->u.r, &x, sizeof(x));
90001 pMem->flags = MEM_Null;
90004 pMem->flags = MEM_Real;
90014 ** UPDATE no-change flag set */
90015 pMem->flags = MEM_Null|MEM_Zero;
90016 pMem->n = 0;
90017 pMem->u.nZero = 0;
90022 /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
90023 pMem->flags = MEM_Null;
90027 /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
90029 pMem->u.i = ONE_BYTE_INT(buf);
90030 pMem->flags = MEM_Int;
90031 testcase( pMem->u.i<0 );
90034 case 2: { /* 2-byte signed integer */
90035 /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
90036 ** twos-complement integer. */
90037 pMem->u.i = TWO_BYTE_INT(buf);
90038 pMem->flags = MEM_Int;
90039 testcase( pMem->u.i<0 );
90042 case 3: { /* 3-byte signed integer */
90043 /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
90044 ** twos-complement integer. */
90045 pMem->u.i = THREE_BYTE_INT(buf);
90046 pMem->flags = MEM_Int;
90047 testcase( pMem->u.i<0 );
90050 case 4: { /* 4-byte signed integer */
90051 /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
90052 ** twos-complement integer. */
90053 pMem->u.i = FOUR_BYTE_INT(buf);
90055 /* Work around a sign-extension bug in the HP compiler for HP/UX */
90056 if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
90058 pMem->flags = MEM_Int;
90059 testcase( pMem->u.i<0 );
90062 case 5: { /* 6-byte signed integer */
90063 /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
90064 ** twos-complement integer. */
90065 pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
90066 pMem->flags = MEM_Int;
90067 testcase( pMem->u.i<0 );
90070 case 6: /* 8-byte signed integer */
90079 /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
90080 /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
90081 pMem->u.i = serial_type-8;
90082 pMem->flags = MEM_Int;
90086 /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
90088 ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
90089 ** (N-13)/2 bytes in length. */
90091 pMem->z = (char *)buf;
90092 pMem->n = (serial_type-12)/2;
90093 pMem->flags = aFlag[serial_type&1];
90100 ** This routine is used to allocate sufficient space for an UnpackedRecord
90111 ** If an OOM error occurs, NULL is returned.
90119 nByte = ROUND8P(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nKeyField+1);
90120 p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
90122 p->aMem = (Mem*)&((char*)p)[ROUND8P(sizeof(UnpackedRecord))];
90123 assert( pKeyInfo->aSortFlags!=0 );
90124 p->pKeyInfo = pKeyInfo;
90125 p->nField = pKeyInfo->nKeyField + 1;
90130 ** Given the nKey-byte encoding of a record in pKey[], populate the
90145 Mem *pMem = p->aMem;
90147 p->default_rc = 0;
90156 pMem->enc = pKeyInfo->enc;
90157 pMem->db = pKeyInfo->db;
90158 /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
90159 pMem->szMalloc = 0;
90160 pMem->z = 0;
90164 if( (++u)>=p->nField ) break;
90171 sqlite3VdbeMemSetNull(pMem-1);
90173 assert( u<=pKeyInfo->nKeyField + 1 );
90174 p->nField = u;
90203 pKeyInfo = pPKey2->pKeyInfo;
90204 if( pKeyInfo->db==0 ) return 1;
90205 mem1.enc = pKeyInfo->enc;
90206 mem1.db = pKeyInfo->db;
90222 assert( pKeyInfo->nAllField>=pPKey2->nField || CORRUPT_DB );
90223 assert( pKeyInfo->aSortFlags!=0 );
90224 assert( pKeyInfo->nKeyField>0 );
90260 rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
90261 pKeyInfo->nAllField>i ? pKeyInfo->aColl[i] : 0);
90264 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
90265 && ((mem1.flags & MEM_Null) || (pPKey2->aMem[i].flags & MEM_Null))
90267 rc = -rc;
90269 if( pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC ){
90270 rc = -rc; /* Invert the result for DESC sort order. */
90275 }while( idx1<szHdr1 && i<pPKey2->nField );
90286 rc = pPKey2->default_rc;
90293 if( pKeyInfo->db->mallocFailed ) return 1;
90302 ** limit given by pKeyInfo->nAllField.
90304 ** If this constraint is not satisfied, it means that the high-speed
90328 assert( nField <= pKeyInfo->nAllField );
90338 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
90344 u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
90346 if( pMem1->enc==pColl->enc ){
90349 return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
90355 sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
90356 sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
90359 v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
90360 v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
90365 rc = pColl->xCmp(pColl->pUser, c1.n, v1, c2.n, v2);
90375 ** with MEM_Zero. Return true if it could be a zero-blob.
90392 int n1 = pB1->n;
90393 int n2 = pB2->n;
90395 /* It is possible to have a Blob value that has some non-zero content
90399 assert( (pB1->flags & MEM_Zero)==0 || n1==0 );
90400 assert( (pB2->flags & MEM_Zero)==0 || n2==0 );
90402 if( (pB1->flags|pB2->flags) & MEM_Zero ){
90403 if( pB1->flags & pB2->flags & MEM_Zero ){
90404 return pB1->u.nZero - pB2->u.nZero;
90405 }else if( pB1->flags & MEM_Zero ){
90406 if( !isAllZero(pB2->z, pB2->n) ) return -1;
90407 return pB1->u.nZero - n2;
90409 if( !isAllZero(pB1->z, pB1->n) ) return +1;
90410 return n1 - pB2->u.nZero;
90413 c = memcmp(pB1->z, pB2->z, n1>n2 ? n2 : n1);
90415 return n1 - n2;
90429 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
90440 if( r<-9223372036854775808.0 ) return +1;
90441 if( r>=9223372036854775808.0 ) return -1;
90443 if( i<y ) return -1;
90448 return (((double)i)<r) ? -1 : (((double)i)>r);
90465 f1 = pMem1->flags;
90466 f2 = pMem2->flags;
90474 return (f2&MEM_Null) - (f1&MEM_Null);
90486 if( pMem1->u.i < pMem2->u.i ) return -1;
90487 if( pMem1->u.i > pMem2->u.i ) return +1;
90491 if( pMem1->u.r < pMem2->u.r ) return -1;
90492 if( pMem1->u.r > pMem2->u.r ) return +1;
90499 return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
90501 if( pMem1->u.i < pMem2->u.i ) return -1;
90502 if( pMem1->u.i > pMem2->u.i ) return +1;
90505 return -1;
90512 return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
90514 return -1;
90528 return -1;
90531 assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
90532 assert( pMem1->enc==SQLITE_UTF8 ||
90533 pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
90539 assert( !pColl || pColl->xCmp );
90554 ** The first argument passed to this function is a serial-type that
90555 ** corresponds to an integer - all values between 1 and 9 inclusive
90556 ** except 7. The second points to a buffer containing an integer value
90591 return (serial_type - 8);
90603 ** If argument bSkip is non-zero, it is assumed that the caller has already
90607 ** fields that appear in both keys are equal, then pPKey2->default_rc is
90610 ** If database corruption is discovered, set pPKey2->errCode to
90611 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
90612 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
90613 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
90625 Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
90654 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
90659 assert( pPKey2->pKeyInfo->nAllField>=pPKey2->nField
90661 assert( pPKey2->pKeyInfo->aSortFlags!=0 );
90662 assert( pPKey2->pKeyInfo->nKeyField>0 );
90664 while( 1 /*exit-by-break*/ ){
90667 /* RHS is an integer */
90668 if( pRhs->flags & (MEM_Int|MEM_IntReal) ){
90669 testcase( pRhs->flags & MEM_Int );
90670 testcase( pRhs->flags & MEM_IntReal );
90674 rc = serial_type==10 ? -1 : +1;
90676 rc = -1;
90679 rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
90682 i64 rhs = pRhs->u.i;
90684 rc = -1;
90692 else if( pRhs->flags & MEM_Real ){
90699 rc = serial_type==10 ? -1 : +1;
90701 rc = -1;
90705 rc = -1; /* mem1 is a NaN */
90706 }else if( mem1.u.r<pRhs->u.r ){
90707 rc = -1;
90708 }else if( mem1.u.r>pRhs->u.r ){
90715 rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
90721 else if( pRhs->flags & MEM_Str ){
90725 rc = -1;
90729 mem1.n = (serial_type - 12) / 2;
90733 || (pKeyInfo = pPKey2->pKeyInfo)->nAllField<=i
90735 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
90737 }else if( pKeyInfo->aColl[i] ){
90738 mem1.enc = pKeyInfo->enc;
90739 mem1.db = pKeyInfo->db;
90743 &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
90746 int nCmp = MIN(mem1.n, pRhs->n);
90747 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
90748 if( rc==0 ) rc = mem1.n - pRhs->n;
90754 else if( pRhs->flags & MEM_Blob ){
90755 assert( (pRhs->flags & MEM_Zero)==0 || pRhs->n==0 );
90759 rc = -1;
90761 int nStr = (serial_type - 12) / 2;
90765 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
90767 }else if( pRhs->flags & MEM_Zero ){
90771 rc = nStr - pRhs->u.nZero;
90774 int nCmp = MIN(nStr, pRhs->n);
90775 rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
90776 if( rc==0 ) rc = nStr - pRhs->n;
90795 int sortFlags = pPKey2->pKeyInfo->aSortFlags[i];
90799 !=(serial_type==0 || (pRhs->flags&MEM_Null)))
90801 rc = -rc;
90810 if( i==pPKey2->nField ) break;
90816 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
90830 || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
90831 || pPKey2->pKeyInfo->db->mallocFailed
90833 pPKey2->eqSeen = 1;
90834 return pPKey2->default_rc;
90845 ** This function is an optimized version of sqlite3VdbeRecordCompare()
90846 ** that (a) the first field of pPKey2 is an integer, and (b) the
90847 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
90865 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
90868 case 1: { /* 1-byte signed integer */
90873 case 2: { /* 2-byte signed integer */
90878 case 3: { /* 3-byte signed integer */
90883 case 4: { /* 4-byte signed integer */
90889 case 5: { /* 6-byte signed integer */
90894 case 6: { /* 8-byte signed integer */
90921 assert( pPKey2->u.i == pPKey2->aMem[0].u.i );
90922 v = pPKey2->u.i;
90924 res = pPKey2->r1;
90926 res = pPKey2->r2;
90927 }else if( pPKey2->nField>1 ){
90933 ** fields. Return pPKey2->default_rc in this case. */
90934 res = pPKey2->default_rc;
90935 pPKey2->eqSeen = 1;
90943 ** This function is an optimized version of sqlite3VdbeRecordCompare()
90945 ** uses the collation sequence BINARY and (c) that the size-of-header varint
90956 assert( pPKey2->aMem[0].flags & MEM_Str );
90957 assert( pPKey2->aMem[0].n == pPKey2->n );
90958 assert( pPKey2->aMem[0].z == pPKey2->u.z );
90959 vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
90969 res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
90971 res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
90977 nStr = (serial_type-12) / 2;
90979 pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
90982 nCmp = MIN( pPKey2->n, nStr );
90983 res = memcmp(&aKey1[szHdr], pPKey2->u.z, nCmp);
90986 res = pPKey2->r2;
90988 res = pPKey2->r1;
90990 res = nStr - pPKey2->n;
90992 if( pPKey2->nField>1 ){
90995 res = pPKey2->default_rc;
90996 pPKey2->eqSeen = 1;
90999 res = pPKey2->r2;
91001 res = pPKey2->r1;
91008 || pPKey2->pKeyInfo->db->mallocFailed
91014 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
91020 ** that the size-of-header varint that occurs at the start of each record
91027 ** is an integer.
91030 ** 13 fields or less. If the first field is an integer, the maximum legal
91032 if( p->pKeyInfo->nAllField<=13 ){
91033 int flags = p->aMem[0].flags;
91034 if( p->pKeyInfo->aSortFlags[0] ){
91035 if( p->pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL ){
91038 p->r1 = 1;
91039 p->r2 = -1;
91041 p->r1 = -1;
91042 p->r2 = 1;
91045 p->u.i = p->aMem[0].u.i;
91052 && p->pKeyInfo->aColl[0]==0
91055 p->u.z = p->aMem[0].z;
91056 p->n = p->aMem[0].n;
91065 ** pCur points at an index entry created using the OP_MakeRecord opcode.
91067 ** Return SQLITE_OK if everything works, or an error code otherwise.
91081 ** than 2GiB are support - anything large must be database corruption.
91083 ** this code can safely assume that nCellKey is 32-bits
91106 /* The last field of the index should be an integer - the ROWID.
91107 ** Verify that the last entry really is an integer. */
91108 getVarint32NR((u8*)&m.z[szHdr-1], typeRowid);
91127 sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
91162 assert( pC->eCurType==CURTYPE_BTREE );
91163 pCur = pC->uc.pCursor;
91187 assert( sqlite3_mutex_held(db->mutex) );
91188 db->nChange = nChange;
91189 db->nTotalChange += nChange;
91197 v->changeCntOn = 1;
91204 ** An expired statement means that recompilation of the statement is
91206 ** programs obsolete. Removing user-defined functions or collating
91207 ** sequences, or changing an authorization function are the types of
91215 ** prepared statements. The flag is set to 1 for an immediate expiration
91216 ** and set to 2 for an advisory expiration.
91220 for(p = db->pVdbe; p; p=p->pVNext){
91221 p->expired = iCode+1;
91229 return v->db;
91236 return v->prepFlags;
91240 ** Return a pointer to an sqlite3_value structure containing the value bound
91241 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
91250 Mem *pMem = &v->aVar[iVar-1];
91251 assert( (v->db->flags & SQLITE_EnableQPSG)==0
91252 || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 );
91253 if( 0==(pMem->flags & MEM_Null) ){
91254 sqlite3_value *pRet = sqlite3ValueNew(v->db);
91267 ** to sqlite3_reoptimize() that re-preparing the statement may result
91272 assert( (v->db->flags & SQLITE_EnableQPSG)==0
91273 || (v->db->mDbFlags & DBFLAG_InternalFunc)!=0 );
91275 v->expmask |= 0x80000000;
91277 v->expmask |= ((u32)1 << (iVar-1));
91282 ** Cause a function to throw an error if it was call from OP_PureFunc
91286 ** throw an error if it is given inputs that would make it non-deterministic.
91287 ** This routine is invoked by date/time functions that use non-deterministic
91293 if( pCtx->pVdbe==0 ) return 1;
91295 pOp = pCtx->pVdbe->aOp + pCtx->iOp;
91296 if( pOp->opcode==OP_PureFunc ){
91299 if( pOp->p5 & NC_IsCheck ){
91301 }else if( pOp->p5 & NC_GenCol ){
91304 zContext = "an index";
91306 zMsg = sqlite3_mprintf("non-deterministic use of %s() in %s",
91307 pCtx->pFunc->zName, zContext);
91308 sqlite3_result_error(pCtx, zMsg, -1);
91319 ** byte-code register values correctly initialized.
91322 if( pExpr->op==TK_REGISTER ){
91323 assert( (pWalker->u.aMem[pExpr->iTable].flags & MEM_Undefined)==0 );
91331 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
91336 if( pVtab->zErrMsg ){
91337 sqlite3 *db = p->db;
91338 sqlite3DbFree(db, p->zErrMsg);
91339 p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
91340 sqlite3_free(pVtab->zErrMsg);
91341 pVtab->zErrMsg = 0;
91350 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
91361 Mem *pMem = &p->aMem[i];
91362 if( pMem->zMalloc ) sqlite3VdbeMemReleaseMalloc(pMem);
91371 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
91377 Vdbe *v, /* Vdbe pre-update hook is invoked by */
91386 sqlite3 *db = v->db;
91389 const char *zTbl = pTab->zName;
91393 if( pTab->tabFlags & TF_WithoutRowid ){
91394 nRealCol = sqlite3PrimaryKeyIndex(pTab)->nColumn;
91395 }else if( pTab->tabFlags & TF_HasVirtual ){
91396 nRealCol = pTab->nNVCol;
91398 nRealCol = pTab->nCol;
91402 assert( db->pPreUpdate==0 );
91409 iKey2 = v->aMem[iReg].u.i;
91416 assert( pCsr->eCurType==CURTYPE_BTREE );
91417 assert( pCsr->nField==nRealCol
91418 || (pCsr->nField==nRealCol+1 && op==SQLITE_DELETE && iReg==-1)
91426 preupdate.pKeyinfo->db = db;
91427 preupdate.pKeyinfo->enc = ENC(db);
91428 preupdate.pKeyinfo->nKeyField = pTab->nCol;
91429 preupdate.pKeyinfo->aSortFlags = (u8*)&fakeSortOrder;
91435 db->pPreUpdate = &preupdate;
91436 db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
91437 db->pPreUpdate = 0;
91439 vdbeFreeUnpacked(db, preupdate.pKeyinfo->nKeyField+1,preupdate.pUnpacked);
91440 vdbeFreeUnpacked(db, preupdate.pKeyinfo->nKeyField+1,preupdate.pNewUnpacked);
91444 for(i=0; i<pCsr->nField; i++){
91451 for(i=0; i<pTab->nCol; i++){
91482 ** Return TRUE (non-zero) of the statement supplied as an argument needs
91486 ** collating sequences are registered or if an authorizer function is
91491 return p==0 || p->expired;
91497 ** an error and return true if it has been finalized (or is otherwise
91501 if( p->db==0 ){
91525 assert( p->startTime>0 );
91526 assert( db->init.busy==0 );
91527 assert( p->zSql!=0 );
91528 sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
91529 iElapse = (iNow - p->startTime)*1000000;
91531 if( db->xProfile ){
91532 db->xProfile(db->pProfileArg, p->zSql, iElapse);
91535 if( db->mTrace & SQLITE_TRACE_PROFILE ){
91536 db->trace.xV2(SQLITE_TRACE_PROFILE, db->pTraceArg, p, (void*)&iElapse);
91538 p->startTime = 0;
91545 if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
91547 # define checkProfileCallback(DB,P) /*no-op*/
91552 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
91562 /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
91563 ** pointer is a harmless no-op. */
91567 sqlite3 *db = v->db;
91569 sqlite3_mutex_enter(db->mutex);
91571 assert( v->eVdbeState>=VDBE_READY_STATE );
91581 ** Terminate the current execution of an SQL statement and reset it
91594 sqlite3 *db = v->db;
91595 sqlite3_mutex_enter(db->mutex);
91599 assert( (rc & (db->errMask))==rc );
91601 sqlite3_mutex_leave(db->mutex);
91622 mutex = p->db->mutex;
91625 for(i=0; i<p->nVar; i++){
91626 sqlite3VdbeMemRelease(&p->aVar[i]);
91627 p->aVar[i].flags = MEM_Null;
91629 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
91630 if( p->expmask ){
91631 p->expired = 1;
91644 if( p->flags & (MEM_Blob|MEM_Str) ){
91646 assert( p->flags==MEM_Null && p->z==0 );
91649 p->flags |= MEM_Blob;
91650 return p->n ? p->z : 0;
91672 return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
91676 if( (p->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
91679 && p->eSubtype=='p'
91680 && strcmp(p->u.zPType, zPType)==0
91682 return (void*)p->z;
91701 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
91702 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
91775 if( pVal->flags & MEM_Null ){
91777 }else if( pVal->flags & (MEM_Real|MEM_IntReal) ){
91779 }else if( pVal->flags & MEM_Int ){
91781 }else if( pVal->flags & MEM_Str ){
91784 assert( eType == aType[pVal->flags&MEM_AffMask] );
91787 return aType[pVal->flags&MEM_AffMask];
91790 return pVal->enc;
91793 /* Return true if a parameter to xUpdate represents an unchanged column */
91795 return (pVal->flags&(MEM_Null|MEM_Zero))==(MEM_Null|MEM_Zero);
91798 /* Return true if a parameter value originated from an sqlite3_bind() */
91800 return (pVal->flags&MEM_FromBind)!=0;
91803 /* Make a copy of an sqlite3_value object
91812 pNew->flags &= ~MEM_Dyn;
91813 pNew->db = 0;
91814 if( pNew->flags&(MEM_Str|MEM_Blob) ){
91815 pNew->flags &= ~(MEM_Static|MEM_Dyn);
91816 pNew->flags |= MEM_Ephem;
91821 }else if( pNew->flags & MEM_Null ){
91823 pNew->flags &= ~(MEM_Term|MEM_Subtype);
91828 /* Destroy an sqlite3_value object previously obtained from
91837 ** The following routines are used by user-defined functions to specify
91842 ** is too big or if an OOM occurs.
91854 Mem *pOut = pCtx->pOut;
91867 sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
91908 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91924 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91935 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91936 sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
91942 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91943 pCtx->isError = SQLITE_ERROR;
91944 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
91951 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91952 pCtx->isError = SQLITE_ERROR;
91953 sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
91960 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91961 sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
91967 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91968 sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
91974 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
91975 sqlite3VdbeMemSetNull(pCtx->pOut);
91990 pOut = pCtx->pOut;
91991 assert( sqlite3_mutex_held(pOut->db->mutex) );
91993 pOut->flags = MEM_Null;
92002 if( pCtx->pFunc!=0
92003 && (pCtx->pFunc->funcFlags & SQLITE_RESULT_SUBTYPE)==0
92008 pCtx->pFunc->zName);
92009 sqlite3_result_error(pCtx, zErr, -1);
92013 pOut = pCtx->pOut;
92014 assert( sqlite3_mutex_held(pOut->db->mutex) );
92015 pOut->eSubtype = eSubtype & 0xff;
92016 pOut->flags |= MEM_Subtype;
92030 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92046 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92056 sqlite3VdbeMemZeroTerminateIfAble(pCtx->pOut);
92066 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92075 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92084 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92098 pOut = pCtx->pOut;
92099 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92101 sqlite3VdbeChangeEncoding(pOut, pCtx->enc);
92115 pOut = pCtx->pOut;
92116 assert( sqlite3_mutex_held(pOut->db->mutex) );
92117 if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
92122 sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
92125 return sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
92132 pCtx->isError = errCode ? errCode : -1;
92134 if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
92136 if( pCtx->pOut->flags & MEM_Null ){
92137 setResultStrOrError(pCtx, sqlite3ErrStr(errCode), -1, SQLITE_UTF8,
92142 /* Force an SQLITE_TOOBIG error. */
92147 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92148 pCtx->isError = SQLITE_TOOBIG;
92149 sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
92153 /* An SQLITE_NOMEM error. */
92158 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92159 sqlite3VdbeMemSetNull(pCtx->pOut);
92160 pCtx->isError = SQLITE_NOMEM_BKPT;
92161 sqlite3OomFault(pCtx->pOut->db);
92167 ** test-control.
92170 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92171 if( pCtx->pOut->flags & MEM_Int ){
92172 pCtx->pOut->flags &= ~MEM_Int;
92173 pCtx->pOut->flags |= MEM_IntReal;
92187 for(i=0; i<db->nDb; i++){
92188 Btree *pBt = db->aDb[i].pBt;
92194 if( nEntry>0 && db->xWalCallback && rc==SQLITE_OK ){
92195 rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zDbSName, nEntry);
92206 ** statement is completely executed or an error occurs.
92218 db = p->db;
92219 if( p->eVdbeState!=VDBE_RUN_STATE ){
92221 if( p->eVdbeState==VDBE_READY_STATE ){
92222 if( p->expired ){
92223 p->rc = SQLITE_SCHEMA;
92225 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
92226 /* If this statement was prepared using saved SQL and an
92227 ** error has occurred, then return the error code in p->rc to the
92240 if( db->nVdbeActive==0 ){
92241 AtomicStore(&db->u1.isInterrupted, 0);
92244 assert( db->nVdbeWrite>0 || db->autoCommit==0
92245 || ((db->nDeferredCons + db->nDeferredImmCons)==0)
92249 if( (db->mTrace & (SQLITE_TRACE_PROFILE|SQLITE_TRACE_XPROFILE))!=0
92250 && !db->init.busy && p->zSql ){
92251 sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
92253 assert( p->startTime==0 );
92257 db->nVdbeActive++;
92258 if( p->readOnly==0 ) db->nVdbeWrite++;
92259 if( p->bIsReader ) db->nVdbeRead++;
92260 p->pc = 0;
92261 p->eVdbeState = VDBE_RUN_STATE;
92264 if( ALWAYS(p->eVdbeState==VDBE_HALT_STATE) ){
92269 ** This "automatic-reset" change is not technically an incompatibility,
92270 ** since any application that receives an SQLITE_MISUSE is broken by
92275 ** returns, and those were broken by the automatic-reset change. As a
92276 ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
92282 if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
92290 assert( p->eVdbeState==VDBE_READY_STATE );
92296 p->rcApp = SQLITE_OK;
92299 if( p->explain ){
92304 db->nVdbeExec++;
92306 db->nVdbeExec--;
92310 assert( p->rc==SQLITE_OK );
92311 assert( db->mallocFailed==0 );
92312 db->errCode = SQLITE_ROW;
92319 p->pResultRow = 0;
92320 if( rc==SQLITE_DONE && db->autoCommit ){
92321 assert( p->rc==SQLITE_OK );
92322 p->rc = doWalCallbacks(db);
92323 if( p->rc!=SQLITE_OK ){
92326 }else if( rc!=SQLITE_DONE && (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ){
92327 /* If this statement was prepared using saved SQL and an
92328 ** error has occurred, then return the error code in p->rc to the
92335 db->errCode = rc;
92336 if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
92337 p->rc = SQLITE_NOMEM_BKPT;
92338 if( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 ) rc = p->rc;
92343 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0
92347 return (rc&db->errMask);
92351 ** This is the top-level implementation of sqlite3_step(). Call
92364 db = v->db;
92365 sqlite3_mutex_enter(db->mutex);
92368 int savedPc = v->pc;
92371 /* This case occurs after failing to recompile an sql statement.
92379 const char *zErr = (const char *)sqlite3_value_text(db->pErr);
92380 sqlite3DbFree(db, v->zErrMsg);
92381 if( !db->mallocFailed ){
92382 v->zErrMsg = sqlite3DbStrDup(db, zErr);
92383 v->rc = rc = sqlite3ApiExit(db, rc);
92385 v->zErrMsg = 0;
92386 v->rc = rc = SQLITE_NOMEM_BKPT;
92395 ** SQLITE_SCHEMA. tag-20220401a */
92396 v->minWriteFileFormat = 254;
92398 assert( v->expired==0 );
92400 sqlite3_mutex_leave(db->mutex);
92413 assert( p && p->pFunc );
92414 return p->pFunc->pUserData;
92421 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
92431 assert( p && p->pOut );
92433 return p->pOut->db;
92437 ** If this routine is invoked from within an xColumn method of a virtual
92438 ** table, then it returns true if and only if the the call is during an
92447 ** performance by substituting a NULL result, or some other light-weight
92456 return sqlite3_value_nochange(p->pOut);
92484 if( (pVal->flags & MEM_Dyn)==0 || pVal->xDel!=sqlite3VdbeValueListFree ){
92487 assert( (pVal->flags&(MEM_TypeMask|MEM_Term|MEM_Subtype)) ==
92489 assert( pVal->eSubtype=='p' );
92490 assert( pVal->u.zPType!=0 && strcmp(pVal->u.zPType,"ValueList")==0 );
92491 pRhs = (ValueList*)pVal->z;
92494 rc = sqlite3BtreeNext(pRhs->pCsr, 0);
92497 rc = sqlite3BtreeFirst(pRhs->pCsr, &dummy);
92498 assert( rc==SQLITE_OK || sqlite3BtreeEof(pRhs->pCsr) );
92499 if( sqlite3BtreeEof(pRhs->pCsr) ) rc = SQLITE_DONE;
92505 sz = sqlite3BtreePayloadSize(pRhs->pCsr);
92506 rc = sqlite3VdbeMemFromBtreeZeroOffset(pRhs->pCsr,(int)sz,&sMem);
92510 sqlite3_value *pOut = pRhs->pOut;
92513 pOut->enc = ENC(pOut->db);
92514 if( (pOut->flags & MEM_Ephem)!=0 && sqlite3VdbeMemMakeWriteable(pOut) ){
92551 sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
92552 assert( p->pVdbe!=0 );
92555 sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
92558 rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
92566 ** its pMem->z element.
92569 Mem *pMem = p->pMem;
92570 assert( (pMem->flags & MEM_Agg)==0 );
92573 pMem->z = 0;
92576 pMem->flags = MEM_Agg;
92577 pMem->u.pDef = p->pFunc;
92578 if( pMem->z ){
92579 memset(pMem->z, 0, nByte);
92582 return (void*)pMem->z;
92591 assert( p && p->pFunc && p->pFunc->xFinalize );
92592 assert( sqlite3_mutex_held(p->pOut->db->mutex) );
92594 if( (p->pMem->flags & MEM_Agg)==0 ){
92597 return (void*)p->pMem->z;
92603 ** the user-function defined by pCtx.
92605 ** The left-most argument is 0.
92617 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92619 if( pCtx->pVdbe==0 ) return 0;
92621 assert( pCtx->pVdbe!=0 );
92623 for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
92624 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
92625 return pAuxData->pAux;
92633 ** argument to the user-function defined by pCtx. Any previous value is
92636 ** The left-most argument is 0.
92639 ** to all functions within the current prepared statement using iArg as an
92654 pVdbe= pCtx->pVdbe;
92655 assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
92662 for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNextAux){
92663 if( pAuxData->iAuxArg==iArg && (pAuxData->iAuxOp==pCtx->iOp || iArg<0) ){
92668 pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
92670 pAuxData->iAuxOp = pCtx->iOp;
92671 pAuxData->iAuxArg = iArg;
92672 pAuxData->pNextAux = pVdbe->pAuxData;
92673 pVdbe->pAuxData = pAuxData;
92674 if( pCtx->isError==0 ) pCtx->isError = -1;
92675 }else if( pAuxData->xDeleteAux ){
92676 pAuxData->xDeleteAux(pAuxData->pAux);
92679 pAuxData->pAux = pAux;
92680 pAuxData->xDeleteAux = xDelete;
92691 ** Return the number of times the Step function of an aggregate has been
92700 assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
92701 return p->pMem->n;
92711 return pVm->nResColumn;
92720 if( pVm==0 || pVm->pResultRow==0 ) return 0;
92721 return pVm->nResColumn;
92725 ** Return a pointer to static memory containing an SQL NULL value.
92728 /* Even though the Mem structure contains an element
92730 ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
92731 ** instead of an 8-byte one. This all works fine, except that when
92733 ** that a Mem structure is located on an 8-byte boundary. To prevent
92735 ** using gcc, we force nullMem to be 8-byte aligned using the magical
92774 assert( pVm->db );
92775 sqlite3_mutex_enter(pVm->db->mutex);
92776 if( pVm->pResultRow!=0 && i<pVm->nResColumn && i>=0 ){
92777 pOut = &pVm->pResultRow[i];
92779 sqlite3Error(pVm->db, SQLITE_RANGE);
92786 ** This function is called after invoking an sqlite3_value_XXX function on a
92787 ** column value (i.e. a value returned by evaluating an SQL expression in the
92805 /* If malloc() failed during an encoding conversion within an
92812 assert( p->db!=0 );
92813 assert( sqlite3_mutex_held(p->db->mutex) );
92814 p->rc = sqlite3ApiExit(p->db, p->rc);
92815 sqlite3_mutex_leave(p->db->mutex);
92865 if( pOut->flags&MEM_Static ){
92866 pOut->flags &= ~MEM_Static;
92867 pOut->flags |= MEM_Ephem;
92912 ** Convert the N-th element of pStmt->pColName[] into a string using
92924 ** If the result is not a simple column reference (if it is an expression
92946 db = p->db;
92948 sqlite3_mutex_enter(db->mutex);
92950 if( p->explain ){
92952 n = p->explain==1 ? 8 : 4;
92955 int i = iExplainColNames16[N + 8*p->explain - 8];
92958 ret = (void*)azExplainColNames8[N + 8*p->explain - 8];
92962 n = p->nResColumn;
92964 u8 prior_mallocFailed = db->mallocFailed;
92968 ret = sqlite3_value_text16((sqlite3_value*)&p->aColName[N]);
92972 ret = sqlite3_value_text((sqlite3_value*)&p->aColName[N]);
92977 assert( db->mallocFailed==0 || db->mallocFailed==1 );
92978 if( db->mallocFailed > prior_mallocFailed ){
92984 sqlite3_mutex_leave(db->mutex);
93028 ** NULL is returned if the result column is an expression or constant or
93029 ** anything else which is not an unambiguous reference to a database column.
93042 ** NULL is returned if the result column is an expression or constant or
93043 ** anything else which is not an unambiguous reference to a database column.
93056 ** NULL is returned if the result column is an expression or constant or
93057 ** anything else which is not an unambiguous reference to a database column.
93082 ** The error code stored in database p->db is overwritten with the return
93085 ** (tag-20240917-01) If vdbeUnbind(p,(u32)(i-1)) returns SQLITE_OK,
93089 ** p->pVar!=0
93091 ** i<=p->nVar
93093 ** An assert() is normally added after vdbeUnbind() to help static analyzers
93101 sqlite3_mutex_enter(p->db->mutex);
93102 if( p->eVdbeState!=VDBE_READY_STATE ){
93103 sqlite3Error(p->db, SQLITE_MISUSE_BKPT);
93104 sqlite3_mutex_leave(p->db->mutex);
93106 "bind on a busy prepared statement: [%s]", p->zSql);
93109 if( i>=(unsigned int)p->nVar ){
93110 sqlite3Error(p->db, SQLITE_RANGE);
93111 sqlite3_mutex_leave(p->db->mutex);
93114 pVar = &p->aVar[i];
93116 pVar->flags = MEM_Null;
93117 p->db->errCode = SQLITE_OK;
93122 ** IMPLEMENTATION-OF: R-57496-20354 If the specific value bound to a host
93128 assert( (p->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || p->expmask==0 );
93129 if( p->expmask!=0 && (p->expmask & (i>=31 ? 0x80000000 : (u32)1<<i))!=0 ){
93130 p->expired = 1;
93150 rc = vdbeUnbind(p, (u32)(i-1));
93152 assert( p!=0 && p->aVar!=0 && i>0 && i<=p->nVar ); /* tag-20240917-01 */
93154 pVar = &p->aVar[i-1];
93157 rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
93160 sqlite3Error(p->db, rc);
93161 rc = sqlite3ApiExit(p->db, rc);
93164 sqlite3_mutex_leave(p->db->mutex);
93173 ** Bind a blob value to an SQL statement variable.
93200 rc = vdbeUnbind(p, (u32)(i-1));
93202 assert( p!=0 && p->aVar!=0 && i>0 && i<=p->nVar ); /* tag-20240917-01 */
93203 sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
93204 sqlite3_mutex_leave(p->db->mutex);
93214 rc = vdbeUnbind(p, (u32)(i-1));
93216 assert( p!=0 && p->aVar!=0 && i>0 && i<=p->nVar ); /* tag-20240917-01 */
93217 sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
93218 sqlite3_mutex_leave(p->db->mutex);
93225 rc = vdbeUnbind(p, (u32)(i-1));
93227 assert( p!=0 && p->aVar!=0 && i>0 && i<=p->nVar ); /* tag-20240917-01 */
93228 sqlite3_mutex_leave(p->db->mutex);
93241 rc = vdbeUnbind(p, (u32)(i-1));
93243 assert( p!=0 && p->aVar!=0 && i>0 && i<=p->nVar ); /* tag-20240917-01 */
93244 sqlite3VdbeMemSetPointer(&p->aVar[i-1], pPtr, zPTtype, xDestructor);
93245 sqlite3_mutex_leave(p->db->mutex);
93290 rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
93294 assert( pValue->flags & (MEM_Real|MEM_IntReal) );
93296 (pValue->flags & MEM_Real) ? pValue->u.r : (double)pValue->u.i
93301 if( pValue->flags & MEM_Zero ){
93302 rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
93304 rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
93309 rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
93310 pValue->enc);
93323 rc = vdbeUnbind(p, (u32)(i-1));
93325 assert( p!=0 && p->aVar!=0 && i>0 && i<=p->nVar ); /* tag-20240917-01 */
93327 sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
93329 rc = sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
93331 sqlite3_mutex_leave(p->db->mutex);
93341 sqlite3_mutex_enter(p->db->mutex);
93342 if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
93348 rc = sqlite3ApiExit(p->db, rc);
93349 sqlite3_mutex_leave(p->db->mutex);
93359 return p ? p->nVar : 0;
93366 ** The result is always UTF-8.
93371 return sqlite3VListNumToName(p->pVList, i);
93381 return sqlite3VListNameToNum(p->pVList, zName, nName);
93394 assert( pTo->db==pFrom->db );
93395 assert( pTo->nVar==pFrom->nVar );
93396 sqlite3_mutex_enter(pTo->db->mutex);
93397 for(i=0; i<pFrom->nVar; i++){
93398 sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
93400 sqlite3_mutex_leave(pTo->db->mutex);
93414 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
93420 if( pFrom->nVar!=pTo->nVar ){
93423 assert( (pTo->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pTo->expmask==0 );
93424 if( pTo->expmask ){
93425 pTo->expired = 1;
93427 assert( (pFrom->prepFlags & SQLITE_PREPARE_SAVESQL)!=0 || pFrom->expmask==0 );
93428 if( pFrom->expmask ){
93429 pFrom->expired = 1;
93442 return pStmt ? ((Vdbe*)pStmt)->db : 0;
93450 return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
93454 ** Return 1 if the statement is an EXPLAIN and return 2 if the
93455 ** statement is an EXPLAIN QUERY PLAN
93458 return pStmt ? ((Vdbe*)pStmt)->explain : 0;
93470 sqlite3_mutex_enter(v->db->mutex);
93471 if( ((int)v->explain)==eMode ){
93475 }else if( (v->prepFlags & SQLITE_PREPARE_SAVESQL)==0 ){
93477 }else if( v->eVdbeState!=VDBE_READY_STATE ){
93479 }else if( v->nMem>=10 && (eMode!=2 || v->haveEqpOps) ){
93481 v->explain = eMode;
93484 v->explain = eMode;
93486 v->haveEqpOps = eMode==2;
93488 if( v->explain ){
93489 v->nResColumn = 12 - 4*v->explain;
93491 v->nResColumn = v->nResAlloc;
93493 sqlite3_mutex_leave(v->db->mutex);
93502 return v!=0 && v->eVdbeState==VDBE_RUN_STATE;
93519 sqlite3_mutex_enter(pDb->mutex);
93521 pNext = (sqlite3_stmt*)pDb->pVdbe;
93523 pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pVNext;
93525 sqlite3_mutex_leave(pDb->mutex);
93537 || (op!=SQLITE_STMTSTATUS_MEMUSED && (op<0||op>=ArraySize(pVdbe->aCounter)))
93544 sqlite3 *db = pVdbe->db;
93545 sqlite3_mutex_enter(db->mutex);
93547 db->pnBytesFreed = (int*)&v;
93548 assert( db->lookaside.pEnd==db->lookaside.pTrueEnd );
93549 db->lookaside.pEnd = db->lookaside.pStart;
93551 db->pnBytesFreed = 0;
93552 db->lookaside.pEnd = db->lookaside.pTrueEnd;
93553 sqlite3_mutex_leave(db->mutex);
93555 v = pVdbe->aCounter[op];
93556 if( resetFlag ) pVdbe->aCounter[op] = 0;
93566 return p ? p->zSql : 0;
93575 ** The SQLITE_TRACE_SIZE_LIMIT puts an upper bound on the size of
93586 sqlite3_mutex_enter(p->db->mutex);
93588 sqlite3_mutex_leave(p->db->mutex);
93601 if( p->zNormSql==0 && ALWAYS(p->zSql!=0) ){
93602 sqlite3_mutex_enter(p->db->mutex);
93603 p->zNormSql = sqlite3Normalize(p, p->zSql);
93604 sqlite3_mutex_leave(p->db->mutex);
93606 return p->zNormSql;
93612 ** Allocate and populate an UnpackedRecord structure based on the serialized
93614 ** if successful, or a NULL pointer if an OOM error is encountered.
93625 memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nKeyField+1));
93632 ** This function is called from within a pre-update callback to retrieve
93646 p = db->pPreUpdate;
93647 /* Test that this call is being made from within an SQLITE_DELETE or
93648 ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
93649 if( !p || p->op==SQLITE_INSERT ){
93653 if( p->pPk ){
93654 iStore = sqlite3TableColumnToIndex(p->pPk, iIdx);
93656 iStore = sqlite3TableColumnToStorage(p->pTab, iIdx);
93658 if( iStore>=p->pCsr->nField || iStore<0 ){
93663 if( iIdx==p->pTab->iPKey ){
93664 *ppValue = pMem = &p->oldipk;
93665 sqlite3VdbeMemSetInt64(pMem, p->iKey1);
93669 if( p->pUnpacked==0 ){
93673 assert( p->pCsr->eCurType==CURTYPE_BTREE );
93674 nRec = sqlite3BtreePayloadSize(p->pCsr->uc.pCursor);
93677 rc = sqlite3BtreePayload(p->pCsr->uc.pCursor, 0, nRec, aRec);
93679 p->pUnpacked = vdbeUnpackRecord(p->pKeyinfo, nRec, aRec);
93680 if( !p->pUnpacked ) rc = SQLITE_NOMEM;
93686 p->aRecord = aRec;
93689 pMem = *ppValue = &p->pUnpacked->aMem[iStore];
93690 if( iStore>=p->pUnpacked->nField ){
93693 Column *pCol = &p->pTab->aCol[iIdx];
93694 if( pCol->iDflt>0 ){
93695 if( p->apDflt==0 ){
93697 assert( sizeof(sqlite3_value*)*UMXV(p->pTab->nCol) < 0x7fffffff );
93698 nByte = sizeof(sqlite3_value*)*p->pTab->nCol;
93699 p->apDflt = (sqlite3_value**)sqlite3DbMallocZero(db, nByte);
93700 if( p->apDflt==0 ) goto preupdate_old_out;
93702 if( p->apDflt[iIdx]==0 ){
93705 assert( p->pTab!=0 && IsOrdinaryTable(p->pTab) );
93706 pDflt = p->pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
93707 rc = sqlite3ValueFromExpr(db, pDflt, ENC(db), pCol->affinity, &pVal);
93711 p->apDflt[iIdx] = pVal;
93713 *ppValue = p->apDflt[iIdx];
93717 }else if( p->pTab->aCol[iIdx].affinity==SQLITE_AFF_REAL ){
93718 if( pMem->flags & (MEM_Int|MEM_IntReal) ){
93719 testcase( pMem->flags & MEM_Int );
93720 testcase( pMem->flags & MEM_IntReal );
93734 ** This function is called from within a pre-update callback to retrieve
93740 p = db!=0 ? db->pPreUpdate : 0;
93742 p = db->pPreUpdate;
93744 return (p ? p->pKeyinfo->nKeyField : 0);
93750 ** This function is designed to be called from within a pre-update callback
93754 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
93755 ** top-level trigger etc.).
93763 p = db!=0 ? db->pPreUpdate : 0;
93765 p = db->pPreUpdate;
93767 return (p ? p->v->nFrame : 0);
93773 ** This function is designed to be called from within a pre-update callback
93779 p = db!=0 ? db->pPreUpdate : 0;
93781 p = db->pPreUpdate;
93783 return (p ? p->iBlobWrite : -1);
93789 ** This function is called from within a pre-update callback to retrieve
93803 p = db->pPreUpdate;
93804 if( !p || p->op==SQLITE_DELETE ){
93808 if( p->pPk && p->op!=SQLITE_UPDATE ){
93809 iStore = sqlite3TableColumnToIndex(p->pPk, iIdx);
93811 iStore = sqlite3TableColumnToStorage(p->pTab, iIdx);
93814 if( iStore>=p->pCsr->nField || iStore<0 ){
93819 if( p->op==SQLITE_INSERT ){
93820 /* For an INSERT, memory cell p->iNewReg contains the serialized record
93822 UnpackedRecord *pUnpack = p->pNewUnpacked;
93824 Mem *pData = &p->v->aMem[p->iNewReg];
93827 pUnpack = vdbeUnpackRecord(p->pKeyinfo, pData->n, pData->z);
93832 p->pNewUnpacked = pUnpack;
93834 pMem = &pUnpack->aMem[iStore];
93835 if( iIdx==p->pTab->iPKey ){
93836 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
93837 }else if( iStore>=pUnpack->nField ){
93841 /* For an UPDATE, memory cell (p->iNewReg+1+iStore) contains the required
93846 assert( p->op==SQLITE_UPDATE );
93847 if( !p->aNew ){
93848 assert( sizeof(Mem)*UMXV(p->pCsr->nField) < 0x7fffffff );
93849 p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem)*p->pCsr->nField);
93850 if( !p->aNew ){
93855 assert( iStore>=0 && iStore<p->pCsr->nField );
93856 pMem = &p->aNew[iStore];
93857 if( pMem->flags==0 ){
93858 if( iIdx==p->pTab->iPKey ){
93859 sqlite3VdbeMemSetInt64(pMem, p->iKey2);
93861 rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iStore]);
93898 aOp = p->aOp;
93899 nOp = p->nOp;
93900 if( p->pFrame ){
93902 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
93903 aOp = pFrame->aOp;
93904 nOp = pFrame->nOp;
93924 for(idx=0; idx<p->nScan; idx++){
93925 pScan = &p->aScan[idx];
93926 if( pScan->zName ){
93927 iScan--;
93932 if( idx>=p->nScan ) return 1;
93933 assert( pScan==0 || pScan==&p->aScan[idx] );
93934 pScan = &p->aScan[idx];
93938 if( pScan->addrLoop>0 ){
93939 *(sqlite3_int64*)pOut = aOp[pScan->addrLoop].nExec;
93941 *(sqlite3_int64*)pOut = -1;
93946 if( pScan->addrVisit>0 ){
93947 *(sqlite3_int64*)pOut = aOp[pScan->addrVisit].nExec;
93949 *(sqlite3_int64*)pOut = -1;
93955 LogEst x = pScan->nEst;
93964 *(const char**)pOut = pScan->zName;
93968 if( pScan->addrExplain ){
93969 *(const char**)pOut = aOp[ pScan->addrExplain ].p4.z;
93976 if( pScan->addrExplain ){
93977 *(int*)pOut = aOp[ pScan->addrExplain ].p1;
93979 *(int*)pOut = -1;
93984 if( pScan->addrExplain ){
93985 *(int*)pOut = aOp[ pScan->addrExplain ].p2;
93987 *(int*)pOut = -1;
93993 if( pScan->aAddrRange[0]==0 ){
93994 res = -1;
93997 for(ii=0; ii<ArraySize(pScan->aAddrRange); ii+=2){
93998 int iIns = pScan->aAddrRange[ii];
93999 int iEnd = pScan->aAddrRange[ii+1];
94010 if( pOp->p1!=iEnd ) continue;
94011 if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_NCYCLE)==0 ){
94047 for(ii=0; p!=0 && ii<p->nOp; ii++){
94048 Op *pOp = &p->aOp[ii];
94049 pOp->nExec = 0;
94050 pOp->nCycle = 0;
94072 ** The Vdbe parse-tree explainer is also found here.
94080 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
94105 ** This function returns a pointer to a nul-terminated string in memory
94109 ** then the returned string holds a copy of zRawSql with "-- " prepended
94112 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
94115 ** with large (multi-megabyte) strings and blobs.
94125 ** parameter index is known, locate the value in p->aVar[]. Then render
94144 db = p->db;
94145 sqlite3StrAccumInit(&out, 0, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
94146 if( db->nVdbeExec>1 ){
94150 sqlite3_str_append(&out, "-- ", 3);
94151 assert( (zRawSql - zStart) > 0 );
94152 sqlite3_str_append(&out, zStart, (int)(zRawSql-zStart));
94154 }else if( p->nVar==0 ){
94183 assert( idx>0 && idx<=p->nVar );
94184 pVar = &p->aVar[idx-1];
94185 if( pVar->flags & MEM_Null ){
94187 }else if( pVar->flags & (MEM_Int|MEM_IntReal) ){
94188 sqlite3_str_appendf(&out, "%lld", pVar->u.i);
94189 }else if( pVar->flags & MEM_Real ){
94190 sqlite3_str_appendf(&out, "%!.15g", pVar->u.r);
94191 }else if( pVar->flags & MEM_Str ){
94198 sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
94206 nOut = pVar->n;
94210 while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
94213 sqlite3_str_appendf(&out, "'%.*q'", nOut, pVar->z);
94215 if( nOut<pVar->n ){
94216 sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
94222 }else if( pVar->flags & MEM_Zero ){
94223 sqlite3_str_appendf(&out, "zeroblob(%d)", pVar->u.nZero);
94226 assert( pVar->flags & MEM_Blob );
94228 nOut = pVar->n;
94233 sqlite3_str_appendf(&out, "%02x", pVar->z[i]&0xff);
94237 if( nOut<pVar->n ){
94238 sqlite3_str_appendf(&out, "/*+%d bytes*/", pVar->n-nOut);
94276 ** High-resolution hardware timer used for debugging and testing only.
94295 ** This file contains inline asm code for retrieving "high-performance"
94302 ** The following routine only works on Pentium-class (or newer) processors.
94304 ** processor and returns that value. This can be used for high-res
94402 ** field of the sqlite3 structure is set in order to simulate an interrupt.
94405 ** in an ordinary build.
94425 ** use this information to make sure that the zero-blob functionality
94432 if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
94433 sqlite3_max_blobsize = p->n;
94443 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
94445 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
94495 ** feature is used for test suite validation only and does not appear an
94501 ** M: 2 - two-way branch (I=0: fall-thru 1: jump )
94502 ** 3 - two-way + NULL (I=0: fall-thru 1: jump 2: NULL )
94503 ** 4 - OP_Jump (I=0: jump p1 1: jump p2 2: jump p3)
94505 ** In other words, if M is 2, then I is either 0 (for fall-through) or
94506 ** 1 (for when the branch is taken). If M is 3, the I is 0 for an
94507 ** ordinary fall-through, I is 1 if the branch was taken, and I is 2
94510 ** When M is 4, that means that an OP_Jump is being run. I is 0, 1, or 2
94518 ** always taken, the flags should be 0x05 since the fall-through and
94520 ** flags should be 0x06 since only the fall-through approach is allowed.
94522 ** Bit 0x08 of the flags indicates an OP_Jump opcode that is only
94523 ** interested in equal or not-equal. In other words, I==0 and I==2
94528 ** should be no-ops except for special builds used to measure test coverage.
94533 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
94537 assert( M<=4 ); /* 2: two-way branch, 3: three-way branch, 4: OP_Jump */
94549 ** iSrcLine - the line number of the VdbeCoverage() macro, with
94551 ** I - Mask of bits 0x07 indicating which cases are are
94553 ** fall-thru, 0x02 means taken, 0x04 means NULL. Any
94558 ** M - Type of jump. Same as M argument above
94572 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
94578 ** This routine converts an ephemeral string into a dynamically allocated
94580 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
94583 if( ((P)->flags&MEM_Ephem)!=0 \
94587 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
94614 ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
94615 ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
94617 Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
94625 assert( iCur>=0 && iCur<p->nCursor );
94626 if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
94627 sqlite3VdbeFreeCursorNN(p, p->apCsr[iCur]);
94628 p->apCsr[iCur] = 0;
94633 ** in pMem->zMalloc. But for the special case of the aMem[] entries used
94634 ** to hold cursors, it is faster to in-line the logic. */
94635 assert( pMem->flags==MEM_Undefined );
94636 assert( (pMem->flags & MEM_Dyn)==0 );
94637 assert( pMem->szMalloc==0 || pMem->z==pMem->zMalloc );
94638 if( pMem->szMalloc<nByte ){
94639 if( pMem->szMalloc>0 ){
94640 sqlite3DbFreeNN(pMem->db, pMem->zMalloc);
94642 pMem->z = pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, nByte);
94643 if( pMem->zMalloc==0 ){
94644 pMem->szMalloc = 0;
94647 pMem->szMalloc = (int)nByte;
94650 p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->zMalloc;
94652 pCx->eCurType = eCurType;
94653 pCx->nField = nField;
94654 pCx->aOffset = &pCx->aType[nField];
94657 pCx->uc.pCursor = (BtCursor*)&pMem->z[SZ_VDBECURSOR(nField)];
94658 sqlite3BtreeCursorZero(pCx->uc.pCursor);
94664 ** The string in pRec is known to look like an integer and to have a
94666 ** integer value if the string is in range to be an integer. Otherwise,
94676 return 0==sqlite3Atoi64(pRec->z, piValue, pRec->n, pRec->enc);
94686 ** an integer representation. Strings that look like floating point
94692 ** if there is an exact integer representation of the quantity.
94696 u8 enc = pRec->enc;
94698 assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real|MEM_IntReal))==MEM_Str );
94699 rc = sqlite3AtoF(pRec->z, &rValue, pRec->n, enc);
94701 if( rc==1 && alsoAnInt(pRec, rValue, &pRec->u.i) ){
94702 pRec->flags |= MEM_Int;
94704 pRec->u.r = rValue;
94705 pRec->flags |= MEM_Real;
94708 /* TEXT->NUMERIC is many->one. Hence, it is important to invalidate the
94711 ** numeric value. Ticket [343634942dd54ab57b7024] 2018-01-31. */
94712 pRec->flags &= ~MEM_Str;
94721 ** Try to convert pRec to an integer representation or a
94722 ** floating-point representation if an integer representation
94725 ** an integer representation is more space efficient on disk.
94736 ** No-op. pRec is unchanged.
94746 if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
94747 if( (pRec->flags & (MEM_Real|MEM_IntReal))==0 ){
94748 if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
94754 /* Only attempt the conversion to TEXT if there is an integer or real
94759 if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
94760 if( (pRec->flags&(MEM_Real|MEM_Int|MEM_IntReal)) ){
94761 testcase( pRec->flags & MEM_Int );
94762 testcase( pRec->flags & MEM_Real );
94763 testcase( pRec->flags & MEM_IntReal );
94767 pRec->flags &= ~(MEM_Real|MEM_Int|MEM_IntReal);
94802 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
94808 assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal))==0 );
94809 assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
94811 pMem->u.i = 0;
94814 rc = sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc);
94816 if( rc==0 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)<=1 ){
94817 pMem->u.i = ix;
94822 }else if( rc==1 && sqlite3Atoi64(pMem->z, &ix, pMem->n, pMem->enc)==0 ){
94823 pMem->u.i = ix;
94833 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
94834 ** But it does set pMem->u.r and pMem->u.i appropriately.
94837 assert( (pMem->flags & MEM_Null)==0
94838 || pMem->db==0 || pMem->db->mallocFailed );
94839 if( pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null) ){
94840 testcase( pMem->flags & MEM_Int );
94841 testcase( pMem->flags & MEM_Real );
94842 testcase( pMem->flags & MEM_IntReal );
94843 return pMem->flags & (MEM_Int|MEM_Real|MEM_IntReal|MEM_Null);
94845 assert( pMem->flags & (MEM_Str|MEM_Blob) );
94846 testcase( pMem->flags & MEM_Str );
94847 testcase( pMem->flags & MEM_Blob );
94858 int f = pMem->flags;
94876 for(i=0; i<25 && i<pMem->n; i++){
94877 sqlite3_str_appendf(pStr, "%02X", ((int)pMem->z[i] & 0xFF));
94880 for(i=0; i<25 && i<pMem->n; i++){
94881 char z = pMem->z[i];
94886 sqlite3_str_appendf(pStr, "+%dz",pMem->u.nZero);
94903 sqlite3_str_appendf(pStr, " %c%d[", c, pMem->n);
94904 for(j=0; j<25 && j<pMem->n; j++){
94905 c = pMem->z[j];
94908 sqlite3_str_appendf(pStr, "]%s", encnames[pMem->enc]);
94910 sqlite3_str_appendf(pStr, "(0-term)");
94921 if( p->flags & MEM_Undefined ){
94923 }else if( p->flags & MEM_Null ){
94924 printf(p->flags & MEM_Zero ? " NULL-nochng" : " NULL");
94925 }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
94926 printf(" si:%lld", p->u.i);
94927 }else if( (p->flags & (MEM_IntReal))!=0 ){
94928 printf(" ir:%lld", p->u.i);
94929 }else if( p->flags & MEM_Int ){
94930 printf(" i:%lld", p->u.i);
94932 }else if( p->flags & MEM_Real ){
94933 printf(" r:%.17g", p->u.r);
94944 if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
94949 if( p->pScopyFrom ){
94950 assert( p->pScopyFrom->bScopy );
94951 printf(" <== R[%d]", (int)(p->pScopyFrom - &p[-iReg]));
94970 for(i=1; i<v->nMem; i++) registerTrace(i, v->aMem+i);
94976 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
94983 ** This function is only called from within an assert() expression. It
94985 ** the number of non-transaction savepoints currently in the
94995 for(p=db->pSavepoint; p; p=p->pNext) n++;
94996 assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
95002 ** Return the register of pOp->p2 after first preparing it to be
95003 ** overwritten with an integer value.
95007 pOut->flags = MEM_Int;
95012 assert( pOp->p2>0 );
95013 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
95014 pOut = &p->aMem[pOp->p2];
95016 if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
95019 pOut->flags = MEM_Int;
95025 ** Compute a bloom filter hash using pOp->p4.i registers from aMem[] beginning
95026 ** with pOp->p3. Return the hash.
95032 assert( pOp->p4type==P4_INT32 );
95033 for(i=pOp->p3, mx=i+pOp->p4.i; i<mx; i++){
95035 if( p->flags & (MEM_Int|MEM_IntReal) ){
95036 h += p->u.i;
95037 }else if( p->flags & MEM_Real ){
95039 }else if( p->flags & (MEM_Str|MEM_Blob) ){
95043 h += 4093 + (p->flags & (MEM_Str|MEM_Blob));
95060 int t, /* The serial-type code for the column value */
95067 sqlite3 *db = pDest->db;
95068 int encoding = pDest->enc;
95070 assert( pC->eCurType==CURTYPE_BTREE );
95071 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) return SQLITE_TOOBIG;
95072 if( len > 4000 && pC->pKeyInfo==0 ){
95074 ** an RCStr (reference counted string) so that if they are reloaded,
95079 ** Only do this on table-btrees so that writes to index-btrees do not
95085 if( pC->colCache==0 ){
95086 pC->pCache = sqlite3DbMallocZero(db, sizeof(VdbeTxtBlbCache) );
95087 if( pC->pCache==0 ) return SQLITE_NOMEM;
95088 pC->colCache = 1;
95090 pCache = pC->pCache;
95091 if( pCache->pCValue==0
95092 || pCache->iCol!=iCol
95093 || pCache->cacheStatus!=cacheStatus
95094 || pCache->colCacheCtr!=colCacheCtr
95095 || pCache->iOffset!=sqlite3BtreeOffset(pC->uc.pCursor)
95097 if( pCache->pCValue ) sqlite3RCStrUnref(pCache->pCValue);
95098 pBuf = pCache->pCValue = sqlite3RCStrNew( len+3 );
95100 rc = sqlite3BtreePayload(pC->uc.pCursor, iOffset, len, pBuf);
95105 pCache->iCol = iCol;
95106 pCache->cacheStatus = cacheStatus;
95107 pCache->colCacheCtr = colCacheCtr;
95108 pCache->iOffset = sqlite3BtreeOffset(pC->uc.pCursor);
95110 pBuf = pCache->pCValue;
95117 pDest->flags |= MEM_Term;
95123 rc = sqlite3VdbeMemFromBtree(pC->uc.pCursor, iOffset, len, pDest);
95125 sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
95127 pDest->z[len] = 0;
95128 pDest->flags |= MEM_Term;
95131 pDest->flags &= ~MEM_Ephem;
95147 return azTypes[sqlite3_value_type(pMem)-1];
95157 Op *aOp = p->aOp; /* Copy of p->aOp */
95165 sqlite3 *db = p->db; /* The database */
95166 u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
95173 Mem *aMem = p->aMem; /* Copy of p->aMem */
95185 assert( p->eVdbeState==VDBE_RUN_STATE ); /* sqlite3_step() verifies this */
95186 if( DbMaskNonZero(p->lockMask) ){
95190 if( db->xProgress ){
95191 u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
95192 assert( 0 < db->nProgressOps );
95193 nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
95198 if( p->rc==SQLITE_NOMEM ){
95203 assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
95204 testcase( p->rc!=SQLITE_OK );
95205 p->rc = SQLITE_OK;
95206 assert( p->bIsReader || p->readOnly!=0 );
95207 p->iCurrentTime = 0;
95208 assert( p->explain==0 );
95209 db->busyHandler.nBusy = 0;
95210 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
95214 if( p->pc==0
95215 && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
95220 if( p->db->flags & SQLITE_VdbeListing ){
95222 for(i=0; i<p->nOp; i++){
95226 if( p->db->flags & SQLITE_VdbeEQP ){
95227 for(i=0; i<p->nOp; i++){
95235 if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
95239 for(pOp=&aOp[p->pc]; 1; pOp++){
95240 /* Errors are detected by individual opcodes, with an immediate
95244 assert( pOp>=aOp && pOp<&aOp[p->nOp]);
95248 pOp->nExec++;
95249 pnCycle = &pOp->nCycle;
95250 if( sqlite3NProfileCnt==0 ) *pnCycle -= sqlite3Hwtime();
95253 pOp->nExec++;
95254 pnCycle = &pOp->nCycle;
95255 *pnCycle -= sqlite3Hwtime();
95262 if( db->flags & SQLITE_VdbeTrace ){
95263 sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
95264 test_trace_breakpoint((int)(pOp - aOp),pOp,p);
95269 /* Check to see if we need to simulate an interrupt. This only happens
95274 sqlite3_interrupt_count--;
95284 u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
95286 assert( pOp->p1>0 );
95287 assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
95288 assert( memIsValid(&aMem[pOp->p1]) );
95289 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
95290 REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
95293 assert( pOp->p2>0 );
95294 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
95295 assert( memIsValid(&aMem[pOp->p2]) );
95296 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
95297 REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
95300 assert( pOp->p3>0 );
95301 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
95302 assert( memIsValid(&aMem[pOp->p3]) );
95303 assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
95304 REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
95307 assert( pOp->p2>0 );
95308 assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
95309 memAboutToChange(p, &aMem[pOp->p2]);
95312 assert( pOp->p3>0 );
95313 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
95314 memAboutToChange(p, &aMem[pOp->p3]);
95322 switch( pOp->opcode ){
95329 ** the switch statement will break with convention and be flush-left. Another
95337 ** opcode and the opcodes.c file is filled with an array of strings where
95361 ** An unconditional jump to address P2.
95367 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
95374 /* In debugging mode, when the p5 flags is set on an OP_Goto, that
95377 if( pOp->p5 ){
95378 assert( pOp->p2 < (int)(pOp - aOp) );
95379 assert( pOp->p2 > 1 );
95380 pOp = &aOp[pOp->p2 - 2];
95387 pOp = &aOp[pOp->p2 - 1];
95398 ** faster according to "valgrind --tool=cachegrind" */
95400 if( AtomicLoad(&db->u1.isInterrupted) ) goto abort_due_to_interrupt;
95405 ** If the progress callback returns non-zero, exit the virtual machine with
95408 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
95409 assert( db->nProgressOps!=0 );
95410 nProgressLimit += db->nProgressOps;
95411 if( db->xProgress(db->pProgressArg) ){
95428 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
95429 pIn1 = &aMem[pOp->p1];
95432 pIn1->flags = MEM_Int;
95433 pIn1->u.i = (int)(pOp-aOp);
95434 REGISTER_TRACE(pOp->p1, pIn1);
95443 ** If P3 is 1, then the jump is only taken if register P1 holds an integer
95445 ** OP_Return becomes a no-op. If P3 is 0, then register P1 must hold an
95446 ** integer or else an assert() is raised. P3 should be set to 1 when
95452 ** P2 is not used by the byte-code engine. However, if P2 is positive
95457 ** value is a byte-code indentation hint. See tag-20220407a in
95461 pIn1 = &aMem[pOp->p1];
95462 if( pIn1->flags & MEM_Int ){
95463 if( pOp->p3 ){ VdbeBranchTaken(1, 2); }
95464 pOp = &aOp[pIn1->u.i];
95465 }else if( ALWAYS(pOp->p3) ){
95483 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
95484 assert( pOp->p2>=0 && pOp->p2<p->nOp );
95485 assert( pOp->p3>=0 && pOp->p3<p->nOp );
95486 pOut = &aMem[pOp->p1];
95488 pOut->u.i = pOp->p3 - 1;
95489 pOut->flags = MEM_Int;
95490 if( pOp->p2==0 ) break;
95495 assert( pOp->p2>0 ); /* There are never any jumps to instruction 0 */
95496 assert( pOp->p2<p->nOp ); /* Jumps must be in range */
95497 pOp = &aOp[pOp->p2 - 1];
95513 pIn1 = &aMem[pOp->p1];
95514 assert( pIn1->flags==MEM_Int );
95515 assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
95516 pCaller = &aOp[pIn1->u.i];
95517 assert( pCaller->opcode==OP_Yield );
95518 assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
95519 pIn1->u.i = (int)(pOp - p->aOp) - 1;
95520 pOp = &aOp[pCaller->p2 - 1];
95539 pIn1 = &aMem[pOp->p1];
95541 pIn1->flags = MEM_Int;
95542 pcDest = (int)pIn1->u.i;
95543 pIn1->u.i = (int)(pOp - aOp);
95544 REGISTER_TRACE(pOp->p1, pIn1);
95554 ** value in register P3 is not NULL, then this routine is a no-op.
95558 pIn3 = &aMem[pOp->p3];
95560 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
95562 if( (pIn3->flags & MEM_Null)==0 ) break;
95581 ** text of an error message.
95597 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
95606 if( pOp->p2==OE_Abort ){ sqlite3VdbeAssertAbortable(p); }
95608 assert( pOp->p4type==P4_NOTUSED
95609 || pOp->p4type==P4_STATIC
95610 || pOp->p4type==P4_DYNAMIC );
95613 ** something is wrong with the code generator. Raise an assertion in order
95615 assert( pOp->p1!=SQLITE_INTERNAL );
95617 if( p->pFrame && pOp->p1==SQLITE_OK ){
95618 /* Halt the sub-program. Return control to the parent frame. */
95619 pFrame = p->pFrame;
95620 p->pFrame = pFrame->pParent;
95621 p->nFrame--;
95622 sqlite3VdbeSetChanges(db, p->nChange);
95624 if( pOp->p2==OE_Ignore ){
95625 /* Instruction pcx is the OP_Program that invoked the sub-program
95627 ** instruction is set to OE_Ignore, then the sub-program is throwing
95628 ** an IGNORE exception. In this case jump to the address specified
95630 pcx = p->aOp[pcx].p2-1;
95632 aOp = p->aOp;
95633 aMem = p->aMem;
95637 p->rc = pOp->p1;
95638 p->errorAction = (u8)pOp->p2;
95639 assert( pOp->p5<=4 );
95640 if( p->rc ){
95641 if( pOp->p3>0 && pOp->p4type==P4_NOTUSED ){
95643 assert( pOp->p3<=(p->nMem + 1 - p->nCursor) );
95644 zErr = sqlite3ValueText(&aMem[pOp->p3], SQLITE_UTF8);
95646 }else if( pOp->p5 ){
95649 testcase( pOp->p5==1 );
95650 testcase( pOp->p5==2 );
95651 testcase( pOp->p5==3 );
95652 testcase( pOp->p5==4 );
95653 sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
95654 if( pOp->p4.z ){
95655 p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
95658 sqlite3VdbeError(p, "%s", pOp->p4.z);
95660 pcx = (int)(pOp - aOp);
95661 sqlite3_log(pOp->p1, "abort at %d: %s; [%s]", pcx, p->zErrMsg, p->zSql);
95666 p->rc = SQLITE_BUSY;
95668 assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
95669 assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
95670 rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
95678 ** The 32-bit integer value P1 is written into register P2.
95682 pOut->u.i = pOp->p1;
95689 ** P4 is a pointer to a 64-bit integer value.
95694 assert( pOp->p4.pI64!=0 );
95695 pOut->u.i = *pOp->p4.pI64;
95703 ** P4 is a pointer to a 64-bit floating point value.
95708 pOut->flags = MEM_Real;
95709 assert( !sqlite3IsNaN(*pOp->p4.pReal) );
95710 pOut->u.r = *pOp->p4.pReal;
95718 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
95724 assert( pOp->p4.z!=0 );
95726 pOp->p1 = sqlite3Strlen30(pOp->p4.z);
95730 rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
95734 assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
95736 pOut->szMalloc = 0;
95737 pOut->flags |= MEM_Static;
95738 if( pOp->p4type==P4_DYNAMIC ){
95739 sqlite3DbFree(db, pOp->p4.z);
95741 pOp->p4type = P4_DYNAMIC;
95742 pOp->p4.z = pOut->z;
95743 pOp->p1 = pOut->n;
95746 if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
95749 pOp->opcode = OP_String;
95768 assert( pOp->p4.z!=0 );
95770 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
95771 pOut->z = pOp->p4.z;
95772 pOut->n = pOp->p1;
95773 pOut->enc = encoding;
95776 if( pOp->p3>0 ){
95777 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
95778 pIn3 = &aMem[pOp->p3];
95779 assert( pIn3->flags & MEM_Int );
95780 if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
95789 ** Mark the beginning of a subroutine that can be entered in-line
95791 ** be terminated by an OP_Return instruction that has a P1 operand that
95793 ** If the subroutine is entered in-line, then the OP_Return will simply
95799 ** a no-op that simply falls through to the next instruction (assuming that
95801 ** entered in-line, then the OP_Return will cause in-line execution to
95816 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
95825 cnt = pOp->p3-pOp->p2;
95826 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
95827 pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
95828 pOut->n = 0;
95830 pOut->uTemp = 0;
95836 pOut->flags = nullFlag;
95837 pOut->n = 0;
95838 cnt--;
95852 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
95853 pOut = &aMem[pOp->p1];
95854 pOut->flags = (pOut->flags&~(MEM_Undefined|MEM_AffMask))|MEM_Null;
95863 ** a zero-filled blob that is P1 bytes long in P2.
95866 assert( pOp->p1 <= SQLITE_MAX_LENGTH );
95868 if( pOp->p4.z==0 ){
95869 sqlite3VdbeMemSetZeroBlob(pOut, pOp->p1);
95872 sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
95874 pOut->enc = encoding;
95887 assert( pOp->p1>0 && pOp->p1<=p->nVar );
95888 pVar = &p->aVar[pOp->p1 - 1];
95892 pOut = &aMem[pOp->p2];
95895 pOut->flags &= ~(MEM_Dyn|MEM_Ephem);
95896 pOut->flags |= MEM_Static|MEM_FromBind;
95904 ** Move the P3 values in register P1..P1+P3-1 over into
95905 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
95906 ** left holding a NULL. It is an error for register ranges
95907 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
95915 n = pOp->p3;
95916 p1 = pOp->p1;
95917 p2 = pOp->p2;
95924 assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
95925 assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
95930 pIn1->pScopyFrom = 0;
95932 for(i=1; i<p->nMem; i++){
95944 }while( --n );
95964 n = pOp->p3;
95965 pIn1 = &aMem[pOp->p1];
95966 pOut = &aMem[pOp->p2];
95972 if( (pOut->flags & MEM_Subtype)!=0 && (pOp->p5 & 0x0002)!=0 ){
95973 pOut->flags &= ~MEM_Subtype;
95976 pOut->pScopyFrom = 0;
95978 REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
95979 if( (n--)==0 ) break;
96000 pIn1 = &aMem[pOp->p1];
96001 pOut = &aMem[pOp->p2];
96005 pOut->pScopyFrom = pIn1;
96006 pOut->mScopyFlags = pIn1->flags;
96007 pIn1->bScopy = 1;
96017 ** This is an optimized version of SCopy that works only for integer
96021 pIn1 = &aMem[pOp->p1];
96022 assert( (pIn1->flags & MEM_Int)!=0 );
96023 pOut = &aMem[pOp->p2];
96024 sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
96030 ** Halt with an SQLITE_CONSTRAINT error if there are any unresolved
96032 ** constraint violations, this is a no-op.
96049 ** The registers P1 through P1+P2-1 contain a single row of
96051 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
96052 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
96056 assert( p->nResColumn==pOp->p2 );
96057 assert( pOp->p1>0 || CORRUPT_DB );
96058 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
96060 p->cacheCtr = (p->cacheCtr + 2)|1;
96061 p->pResultRow = &aMem[pOp->p1];
96064 Mem *pMem = p->pResultRow;
96066 for(i=0; i<pOp->p2; i++){
96068 REGISTER_TRACE(pOp->p1+i, &pMem[i]);
96078 if( db->mallocFailed ) goto no_mem;
96079 if( db->mTrace & SQLITE_TRACE_ROW ){
96080 db->trace.xV2(SQLITE_TRACE_ROW, db->pTraceArg, p, 0);
96082 p->pc = (int)(pOp - aOp) + 1;
96105 pIn1 = &aMem[pOp->p1];
96106 pIn2 = &aMem[pOp->p2];
96107 pOut = &aMem[pOp->p3];
96110 flags1 = pIn1->flags;
96112 testcase( pIn2->flags & MEM_Null );
96113 if( (flags1 | pIn2->flags) & MEM_Null ){
96119 flags1 = pIn1->flags & ~MEM_Str;
96122 flags1 = pIn1->flags & ~MEM_Str;
96124 flags2 = pIn2->flags;
96127 flags2 = pIn2->flags & ~MEM_Str;
96130 flags2 = pIn2->flags & ~MEM_Str;
96132 nByte = pIn1->n + pIn2->n;
96133 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
96141 memcpy(pOut->z, pIn2->z, pIn2->n);
96142 assert( (pIn2->flags & MEM_Dyn) == (flags2 & MEM_Dyn) );
96143 pIn2->flags = flags2;
96145 memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
96146 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
96147 pIn1->flags = flags1;
96149 pOut->z[nByte]=0;
96150 pOut->z[nByte+1] = 0;
96151 pOut->flags |= MEM_Term;
96152 pOut->n = (int)nByte;
96153 pOut->enc = encoding;
96174 ** Synopsis: r[P3]=r[P2]-r[P1]
96208 pIn1 = &aMem[pOp->p1];
96209 type1 = pIn1->flags;
96210 pIn2 = &aMem[pOp->p2];
96211 type2 = pIn2->flags;
96212 pOut = &aMem[pOp->p3];
96215 iA = pIn1->u.i;
96216 iB = pIn2->u.i;
96217 switch( pOp->opcode ){
96223 if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
96229 if( iA==-1 ) iA = 1;
96234 pOut->u.i = iB;
96245 switch( pOp->opcode ){
96247 case OP_Subtract: rB -= rA; break;
96259 if( iA==-1 ) iA = 1;
96265 pOut->u.i = rB;
96271 pOut->u.r = rB;
96286 ** be returned. This is used by the built-in min(), max() and nullif()
96295 ** publicly. Only built-in functions have access to this feature.
96298 assert( pOp->p4type==P4_COLLSEQ );
96299 if( pOp->p1 ){
96300 sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
96308 ** Take the bit-wise AND of the values in register P1 and P2 and
96315 ** Take the bit-wise OR of the values in register P1 and P2 and
96344 pIn1 = &aMem[pOp->p1];
96345 pIn2 = &aMem[pOp->p2];
96346 pOut = &aMem[pOp->p3];
96347 if( (pIn1->flags | pIn2->flags) & MEM_Null ){
96353 op = pOp->opcode;
96364 op = 2*OP_ShiftLeft + 1 - op;
96365 iB = iB>(-64) ? -iB : 64;
96369 iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
96376 /* Sign-extend on a right shift of a negative number */
96377 if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
96382 pOut->u.i = iA;
96391 ** The result is always an integer.
96393 ** To force any register to be an integer, just add 0.
96396 pIn1 = &aMem[pOp->p1];
96399 *(u64*)&pIn1->u.i += (u64)pOp->p2;
96405 ** Force the value in register P1 to be an integer. If the value
96406 ** in P1 is not an integer and cannot be converted into an integer
96408 ** raise an SQLITE_MISMATCH exception.
96411 pIn1 = &aMem[pOp->p1];
96412 if( (pIn1->flags & MEM_Int)==0 ){
96414 if( (pIn1->flags & MEM_Int)==0 ){
96416 if( pOp->p2==0 ){
96432 ** If register P1 holds an integer convert it to a real value.
96440 pIn1 = &aMem[pOp->p1];
96441 if( pIn1->flags & (MEM_Int|MEM_IntReal) ){
96442 testcase( pIn1->flags & MEM_Int );
96443 testcase( pIn1->flags & MEM_IntReal );
96445 REGISTER_TRACE(pOp->p1, pIn1);
96468 assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
96469 testcase( pOp->p2==SQLITE_AFF_TEXT );
96470 testcase( pOp->p2==SQLITE_AFF_BLOB );
96471 testcase( pOp->p2==SQLITE_AFF_NUMERIC );
96472 testcase( pOp->p2==SQLITE_AFF_INTEGER );
96473 testcase( pOp->p2==SQLITE_AFF_REAL );
96474 pIn1 = &aMem[pOp->p1];
96478 rc = sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
96481 REGISTER_TRACE(pOp->p1, pIn1);
96492 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
96493 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
96536 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
96537 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
96586 u16 flags1; /* Copy of initial value of pIn1->flags */
96587 u16 flags3; /* Copy of initial value of pIn3->flags */
96589 pIn1 = &aMem[pOp->p1];
96590 pIn3 = &aMem[pOp->p3];
96591 flags1 = pIn1->flags;
96592 flags3 = pIn3->flags;
96595 if( pIn3->u.i > pIn1->u.i ){
96596 if( sqlite3aGTb[pOp->opcode] ){
96597 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
96602 }else if( pIn3->u.i < pIn1->u.i ){
96603 if( sqlite3aLTb[pOp->opcode] ){
96604 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
96607 iCompare = -1;
96610 if( sqlite3aEQb[pOp->opcode] ){
96611 VdbeBranchTaken(1, (pOp->p5 & SQLITE_NULLEQ)?2:3);
96617 VdbeBranchTaken(0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
96622 if( pOp->p5 & SQLITE_NULLEQ ){
96628 assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 || CORRUPT_DB );
96629 testcase( (pOp->p5 & SQLITE_JUMPIFNULL)!=0 );
96635 res = ((flags3 & MEM_Null) ? -1 : +1); /* Operands are not equal */
96643 if( pOp->p5 & SQLITE_JUMPIFNULL ){
96651 /* Neither operand is NULL and we couldn't do the special high-speed
96652 ** integer comparison case. So do a general-case comparison. */
96653 affinity = pOp->p5 & SQLITE_AFF_MASK;
96658 assert( flags3==pIn3->flags || CORRUPT_DB );
96659 flags3 = pIn3->flags;
96667 pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
96669 testcase( pIn1->flags & MEM_Int );
96670 testcase( pIn1->flags & MEM_Real );
96671 testcase( pIn1->flags & MEM_IntReal );
96673 testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
96674 flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
96678 pIn3->flags &= ~(MEM_Int|MEM_Real|MEM_IntReal);
96680 testcase( pIn3->flags & MEM_Int );
96681 testcase( pIn3->flags & MEM_Real );
96682 testcase( pIn3->flags & MEM_IntReal );
96684 testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
96685 flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
96688 assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
96689 res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
96701 res2 = sqlite3aLTb[pOp->opcode];
96703 res2 = sqlite3aEQb[pOp->opcode];
96705 res2 = sqlite3aGTb[pOp->opcode];
96711 assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
96712 pIn3->flags = flags3;
96713 assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
96714 pIn1->flags = flags1;
96716 VdbeBranchTaken(res2!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
96725 ** This opcode must follow an OP_Lt or OP_Gt comparison operator. There
96730 ** If the result of an OP_Eq comparison on the same two operands as
96732 ** the result of an OP_Eq comparison on the two previous operands
96738 /* Verify the preconditions of this opcode - that it follows an OP_Lt or
96741 for(iAddr = (int)(pOp - aOp) - 1; ALWAYS(iAddr>=0); iAddr--){
96760 ** an OP_Compare that has the OPFLAG_PERMUTE bit set in P5.
96766 assert( pOp->p4type==P4_INTARRAY );
96767 assert( pOp->p4.ai );
96774 ** Synopsis: r[P1@P3] <-> r[P2@P3]
96776 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
96777 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
96793 ** This opcode must be immediately followed by an OP_Jump opcode.
96806 if( (pOp->p5 & OPFLAG_PERMUTE)==0 ){
96810 assert( pOp[-1].opcode==OP_Permutation );
96811 assert( pOp[-1].p4type==P4_INTARRAY );
96812 aPermute = pOp[-1].p4.ai + 1;
96815 n = pOp->p3;
96816 pKeyInfo = pOp->p4.pKeyInfo;
96819 p1 = pOp->p1;
96820 p2 = pOp->p2;
96825 assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
96826 assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
96828 assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
96829 assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
96838 assert( i<pKeyInfo->nKeyField );
96839 pColl = pKeyInfo->aColl[i];
96840 bRev = (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_DESC);
96844 if( (pKeyInfo->aSortFlags[i] & KEYINFO_ORDER_BIGNULL)
96847 iCompare = -iCompare;
96849 if( bRev ) iCompare = -iCompare;
96863 ** This opcode must immediately follow an OP_Compare opcode.
96866 assert( pOp>aOp && pOp[-1].opcode==OP_Compare );
96869 VdbeBranchTaken(0,4); pOp = &aOp[pOp->p1 - 1];
96871 VdbeBranchTaken(1,4); pOp = &aOp[pOp->p2 - 1];
96873 VdbeBranchTaken(2,4); pOp = &aOp[pOp->p3 - 1];
96903 v1 = sqlite3VdbeBooleanValue(&aMem[pOp->p1], 2);
96904 v2 = sqlite3VdbeBooleanValue(&aMem[pOp->p2], 2);
96905 if( pOp->opcode==OP_And ){
96912 pOut = &aMem[pOp->p3];
96916 pOut->u.i = v1;
96943 assert( pOp->p4type==P4_INT32 );
96944 assert( pOp->p4.i==0 || pOp->p4.i==1 );
96945 assert( pOp->p3==0 || pOp->p3==1 );
96946 sqlite3VdbeMemSetInt64(&aMem[pOp->p2],
96947 sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3) ^ pOp->p4.i);
96959 pIn1 = &aMem[pOp->p1];
96960 pOut = &aMem[pOp->p2];
96961 if( (pIn1->flags & MEM_Null)==0 ){
96972 ** Interpret the content of register P1 as an integer. Store the
96973 ** ones-complement of the P1 value into register P2. If P1 holds
96977 pIn1 = &aMem[pOp->p1];
96978 pOut = &aMem[pOp->p2];
96980 if( (pIn1->flags & MEM_Null)==0 ){
96981 pOut->flags = MEM_Int;
96982 pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
96990 ** encountered on each invocation of the byte-code program. Jump to P2
96993 ** Top-level programs determine first invocation by comparing the P1
97001 ** because the self-altering code trick does not work for recursive
97007 ** be the register that holds that Bloom filter. See tag-202407032019
97012 assert( p->aOp[0].opcode==OP_Init );
97013 if( p->pFrame ){
97014 iAddr = (int)(pOp - p->aOp);
97015 if( (p->pFrame->aOnce[iAddr/8] & (1<<(iAddr & 7)))!=0 ){
97019 p->pFrame->aOnce[iAddr/8] |= 1<<(iAddr & 7);
97021 if( p->aOp[0].p1==pOp->p1 ){
97027 pOp->p1 = p->aOp[0].p1;
97034 ** is considered true if it is numeric and non-zero. If the value
97035 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
97039 c = sqlite3VdbeBooleanValue(&aMem[pOp->p1], pOp->p3);
97049 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
97053 c = !sqlite3VdbeBooleanValue(&aMem[pOp->p1], !pOp->p3);
97065 pIn1 = &aMem[pOp->p1];
97066 VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
97067 if( (pIn1->flags & MEM_Null)!=0 ){
97086 ** If P1 is -1, then P3 is a register number and the datatype is taken
97109 assert( pOp->p1>=(-1) && pOp->p1<p->nCursor );
97110 assert( pOp->p1>=0 || (pOp->p3>=0 && pOp->p3<=(p->nMem+1 - p->nCursor)) );
97111 if( pOp->p1>=0 ){
97112 pC = p->apCsr[pOp->p1];
97114 assert( pOp->p3>=0 );
97115 if( pOp->p3<pC->nHdrParsed ){
97116 serialType = pC->aType[pOp->p3];
97143 typeMask = 1 << (pOp->p4.i - 1);
97151 assert( memIsValid(&aMem[pOp->p3]) );
97152 typeMask = 1 << (sqlite3_value_type((sqlite3_value*)&aMem[pOp->p3])-1);
97159 VdbeBranchTaken( (typeMask & pOp->p5)!=0, 2);
97160 if( typeMask & pOp->p5 ){
97174 if( (aMem[pOp->p1].flags & MEM_Null)!=0
97175 || (aMem[pOp->p3].flags & MEM_Null)!=0
97177 sqlite3VdbeMemSetNull(aMem + pOp->p2);
97179 sqlite3VdbeMemSetInt64(aMem + pOp->p2, 0);
97190 pIn1 = &aMem[pOp->p1];
97191 VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
97192 if( (pIn1->flags & MEM_Null)==0 ){
97206 ** If P1 is not an open cursor, then this opcode is a no-op.
97210 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
97211 pC = p->apCsr[pOp->p1];
97212 if( pC && pC->nullRow ){
97213 sqlite3VdbeMemSetNull(aMem + pOp->p3);
97233 ** -DSQLITE_ENABLE_OFFSET_SQL_FUNC option.
97237 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
97238 pC = p->apCsr[pOp->p1];
97239 pOut = &p->aMem[pOp->p3];
97240 if( pC==0 || pC->eCurType!=CURTYPE_BTREE ){
97243 if( pC->deferredMoveto ){
97247 if( sqlite3BtreeEof(pC->uc.pCursor) ){
97250 sqlite3VdbeMemSetInt64(pOut, sqlite3BtreeOffset(pC->uc.pCursor));
97262 ** information about the format of the data.) Extract the P2-th column
97282 BtCursor *pCrsr; /* The B-Tree cursor corresponding to pC */
97283 u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
97291 u64 offset64; /* 64-bit offset */
97295 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
97296 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
97297 pC = p->apCsr[pOp->p1];
97298 p2 = (u32)pOp->p2;
97302 assert( p2<(u32)pC->nField
97303 || (pC->eCurType==CURTYPE_PSEUDO && pC->seekResult==0) );
97304 aOffset = pC->aOffset;
97305 assert( aOffset==pC->aType+pC->nField );
97306 assert( pC->eCurType!=CURTYPE_VTAB );
97307 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
97308 assert( pC->eCurType!=CURTYPE_SORTER );
97310 if( pC->cacheStatus!=p->cacheCtr ){ /*OPTIMIZATION-IF-FALSE*/
97311 if( pC->nullRow ){
97312 if( pC->eCurType==CURTYPE_PSEUDO && pC->seekResult>0 ){
97313 /* For the special case of as pseudo-cursor, the seekResult field
97315 pReg = &aMem[pC->seekResult];
97316 assert( pReg->flags & MEM_Blob );
97318 pC->payloadSize = pC->szRow = pReg->n;
97319 pC->aRow = (u8*)pReg->z;
97321 pDest = &aMem[pOp->p3];
97327 pCrsr = pC->uc.pCursor;
97328 if( pC->deferredMoveto ){
97330 assert( !pC->isEphemeral );
97331 if( pC->ub.aAltMap && (iMap = pC->ub.aAltMap[1+p2])>0 ){
97332 pC = pC->pAltCursor;
97333 p2 = iMap - 1;
97343 assert( pC->eCurType==CURTYPE_BTREE );
97346 pC->payloadSize = sqlite3BtreePayloadSize(pCrsr);
97347 pC->aRow = sqlite3BtreePayloadFetch(pCrsr, &pC->szRow);
97348 assert( pC->szRow<=pC->payloadSize );
97349 assert( pC->szRow<=65536 ); /* Maximum page size is 64KiB */
97351 pC->cacheStatus = p->cacheCtr;
97352 if( (aOffset[0] = pC->aRow[0])<0x80 ){
97353 pC->iHdrOffset = 1;
97355 pC->iHdrOffset = sqlite3GetVarint32(pC->aRow, aOffset);
97357 pC->nHdrParsed = 0;
97359 if( pC->szRow<aOffset[0] ){ /*OPTIMIZATION-IF-FALSE*/
97360 /* pC->aRow does not have to hold the entire row, but it does at least
97361 ** need to cover the header of the record. If pC->aRow does not contain
97364 pC->aRow = 0;
97365 pC->szRow = 0;
97367 /* Make sure a corrupt database has not given us an oversize header.
97368 ** Do this now to avoid an oversize memory allocation.
97373 ** 3-byte type for each of the maximum of 32768 columns plus three
97376 if( aOffset[0] > 98307 || aOffset[0] > pC->payloadSize ){
97380 /* This is an optimization. By skipping over the first few tests
97381 ** (ex: pC->nHdrParsed<=p2) in the next section, we achieve a
97393 zData = pC->aRow;
97394 assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
97398 }else if( sqlite3BtreeCursorHasMoved(pC->uc.pCursor) ){
97405 ** parsed and valid information is in aOffset[] and pC->aType[].
97407 if( pC->nHdrParsed<=p2 ){
97409 ** to extract additional fields up through the p2+1-th field
97411 if( pC->iHdrOffset<aOffset[0] ){
97413 if( pC->aRow==0 ){
97415 rc = sqlite3VdbeMemFromBtreeZeroOffset(pC->uc.pCursor,aOffset[0],&sMem);
97419 zData = pC->aRow;
97422 /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
97424 i = pC->nHdrParsed;
97426 zHdr = zData + pC->iHdrOffset;
97430 if( (pC->aType[i] = t = zHdr[0])<0x80 ){
97435 pC->aType[i] = t;
97446 if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
97447 || (offset64 > pC->payloadSize)
97453 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
97458 pC->nHdrParsed = i;
97459 pC->iHdrOffset = (u32)(zHdr - zData);
97460 if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
97469 if( pC->nHdrParsed<=p2 ){
97470 pDest = &aMem[pOp->p3];
97472 if( pOp->p4type==P4_MEM ){
97473 sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
97480 t = pC->aType[p2];
97483 /* Extract the content for the p2+1-th column. Control can only
97484 ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
97487 assert( p2<pC->nHdrParsed );
97489 pDest = &aMem[pOp->p3];
97495 assert( t==pC->aType[p2] );
97496 if( pC->szRow>=aOffset[p2+1] ){
97498 ** page - where the content is not on an overflow page */
97499 zData = pC->aRow + aOffset[p2];
97504 ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
97508 pDest->n = len = (t-12)/2;
97509 pDest->enc = encoding;
97510 if( pDest->szMalloc < len+2 ){
97511 if( len>db->aLimit[SQLITE_LIMIT_LENGTH] ) goto too_big;
97512 pDest->flags = MEM_Null;
97515 pDest->z = pDest->zMalloc;
97517 memcpy(pDest->z, zData, len);
97518 pDest->z[len] = 0;
97519 pDest->z[len+1] = 0;
97520 pDest->flags = aFlag[t&1];
97524 pDest->enc = encoding;
97525 assert( pDest->db==db );
97527 if( ((p5 = (pOp->p5 & OPFLAG_BYTELENARG))!=0
97550 p->cacheCtr, colCacheCtr, pDest);
97561 REGISTER_TRACE(pOp->p3, pDest);
97566 pOp = &aOp[aOp[0].p3-1];
97579 ** cannot be coerced into the correct type, then raise an error.
97586 ** is zero. When P3 is non-zero, no type checking occurs for
97593 ** <li> P2 should be the number of non-virtual columns in the
97598 ** If any precondition is false, an assertion fault occurs.
97605 assert( pOp->p4type==P4_TABLE );
97606 pTab = pOp->p4.pTab;
97607 assert( pTab->tabFlags & TF_Strict );
97608 assert( pTab->nNVCol==pOp->p2 );
97609 aCol = pTab->aCol;
97610 pIn1 = &aMem[pOp->p1];
97611 for(i=0; i<pTab->nCol; i++){
97614 if( pOp->p3 ){ pIn1++; continue; }
97616 assert( pIn1 < &aMem[pOp->p1+pOp->p2] );
97618 if( (pIn1->flags & MEM_Null)==0 ){
97621 if( (pIn1->flags & MEM_Blob)==0 ) goto vdbe_type_error;
97626 if( (pIn1->flags & MEM_Int)==0 ) goto vdbe_type_error;
97630 if( (pIn1->flags & MEM_Str)==0 ) goto vdbe_type_error;
97634 testcase( (pIn1->flags & (MEM_Real|MEM_IntReal))==MEM_Real );
97635 assert( (pIn1->flags & MEM_IntReal)==0 );
97636 if( pIn1->flags & MEM_Int ){
97637 /* When applying REAL affinity, if the result is still an MEM_Int
97639 ** so that we keep the high-resolution integer value but know that
97641 testcase( pIn1->u.i==140737488355328LL );
97642 testcase( pIn1->u.i==140737488355327LL );
97643 testcase( pIn1->u.i==-140737488355328LL );
97644 testcase( pIn1->u.i==-140737488355329LL );
97645 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL){
97646 pIn1->flags |= MEM_IntReal;
97647 pIn1->flags &= ~MEM_Int;
97649 pIn1->u.r = (double)pIn1->u.i;
97650 pIn1->flags |= MEM_Real;
97651 pIn1->flags &= ~MEM_Int;
97653 }else if( (pIn1->flags & (MEM_Real|MEM_IntReal))==0 ){
97664 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
97667 assert( pIn1 == &aMem[pOp->p1+pOp->p2] );
97672 vdbeMemTypeName(pIn1), sqlite3StdType[aCol[i].eCType-1],
97673 pTab->zName, aCol[i].zCnName);
97683 ** P4 is a string that is P2 characters long. The N-th character of the
97684 ** string indicates the column affinity that should be used for the N-th
97690 zAffinity = pOp->p4.z;
97692 assert( pOp->p2>0 );
97693 assert( zAffinity[pOp->p2]==0 );
97694 pIn1 = &aMem[pOp->p1];
97695 while( 1 /*exit-by-break*/ ){
97696 assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
97699 if( zAffinity[0]==SQLITE_AFF_REAL && (pIn1->flags & MEM_Int)!=0 ){
97700 /* When applying REAL affinity, if the result is still an MEM_Int
97702 ** so that we keep the high-resolution integer value but know that
97704 testcase( pIn1->u.i==140737488355328LL );
97705 testcase( pIn1->u.i==140737488355327LL );
97706 testcase( pIn1->u.i==-140737488355328LL );
97707 testcase( pIn1->u.i==-140737488355329LL );
97708 if( pIn1->u.i<=140737488355327LL && pIn1->u.i>=-140737488355328LL ){
97709 pIn1->flags |= MEM_IntReal;
97710 pIn1->flags &= ~MEM_Int;
97712 pIn1->u.r = (double)pIn1->u.i;
97713 pIn1->flags |= MEM_Real;
97714 pIn1->flags &= ~(MEM_Int|MEM_Str);
97717 REGISTER_TRACE((int)(pIn1-aMem), pIn1);
97730 ** in an index. The OP_Column opcode can decode the record later.
97732 ** P4 may be a string that is P2 characters long. The N-th character of the
97733 ** string indicates the column affinity that should be used for the N-th
97742 ** compile-time option is enabled:
97745 ** of the right-most table that can be null-trimmed.
97749 ** accept no-change records with serial_type 10. This value is
97750 ** only used inside an assert() and does not affect the end result.
97771 ** ------------------------------------------------------------------------
97772 ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
97773 ** ------------------------------------------------------------------------
97780 ** hdr-size field is also a varint which is the offset from the beginning
97786 nField = pOp->p1;
97787 zAffinity = pOp->p4.z;
97788 assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
97790 nField = pOp->p2;
97791 pLast = &pData0[nField-1];
97794 assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
97795 pOut = &aMem[pOp->p3];
97805 if( zAffinity[0]==SQLITE_AFF_REAL && (pRec->flags & MEM_Int) ){
97806 pRec->flags |= MEM_IntReal;
97807 pRec->flags &= ~(MEM_Int);
97809 REGISTER_TRACE((int)(pRec-aMem), pRec);
97819 ** have a non-NULL default value. Also, the record must be left with
97821 ** index of the right-most column with a non-NULL default value */
97822 if( pOp->p5 ){
97823 while( (pLast->flags & MEM_Null)!=0 && nField>pOp->p5 ){
97824 pLast--;
97825 nField--;
97832 ** the Mem.uTemp field of each term should hold the serial-type that will
97836 ** --------------- ---------------
97838 ** 1 1-byte signed integer
97839 ** 2 2-byte signed integer
97840 ** 3 3-byte signed integer
97841 ** 4 4-byte signed integer
97842 ** 5 6-byte signed integer
97843 ** 6 8-byte signed integer
97859 if( pRec->flags & MEM_Null ){
97860 if( pRec->flags & MEM_Zero ){
97863 ** computing an unchanging column value in an UPDATE statement.
97864 ** Give such values a special internal-use-only serial-type of 10
97868 assert( pOp->p5==OPFLAG_NOCHNG_MAGIC || CORRUPT_DB );
97870 pRec->uTemp = 10;
97872 pRec->uTemp = 0;
97875 }else if( pRec->flags & (MEM_Int|MEM_IntReal) ){
97877 i64 i = pRec->u.i;
97879 testcase( pRec->flags & MEM_Int );
97880 testcase( pRec->flags & MEM_IntReal );
97893 if( (i&1)==i && p->minWriteFileFormat>=4 ){
97894 pRec->uTemp = 8+(u32)uu;
97897 pRec->uTemp = 1;
97901 pRec->uTemp = 2;
97904 pRec->uTemp = 3;
97907 pRec->uTemp = 4;
97910 pRec->uTemp = 5;
97913 if( pRec->flags & MEM_IntReal ){
97915 ** as an integer, then we might as well make it an 8-byte floating
97917 pRec->u.r = (double)pRec->u.i;
97918 pRec->flags &= ~MEM_IntReal;
97919 pRec->flags |= MEM_Real;
97920 pRec->uTemp = 7;
97922 pRec->uTemp = 6;
97925 }else if( pRec->flags & MEM_Real ){
97928 pRec->uTemp = 7;
97930 assert( db->mallocFailed || pRec->flags&(MEM_Str|MEM_Blob) );
97931 assert( pRec->n>=0 );
97932 len = (u32)pRec->n;
97933 serial_type = (len*2) + 12 + ((pRec->flags & MEM_Str)!=0);
97934 if( pRec->flags & MEM_Zero ){
97935 serial_type += pRec->u.nZero*2;
97938 len += pRec->u.nZero;
97940 nZero += pRec->u.nZero;
97945 pRec->uTemp = serial_type;
97948 pRec--;
97951 /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
97969 ** the new record. The output register (pOp->p3) is not allowed to
97973 if( nByte+nZero<=pOut->szMalloc ){
97976 pOut->z = pOut->zMalloc;
97980 if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
97987 pOut->n = (int)nByte;
97988 pOut->flags = MEM_Blob;
97990 pOut->u.nZero = nZero;
97991 pOut->flags |= MEM_Zero;
97994 zHdr = (u8 *)pOut->z;
98005 while( 1 /*exit-by-break*/ ){
98006 serial_type = pRec->uTemp;
98007 /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
98009 ** EVIDENCE-OF: R-64536-51728 The values for each column in the record
98018 assert( sizeof(v)==sizeof(pRec->u.r) );
98019 memcpy(&v, &pRec->u.r, sizeof(v));
98022 v = pRec->u.i;
98045 if( serial_type>=14 && pRec->n>0 ){
98046 assert( pRec->z!=0 );
98047 memcpy(zPayload, pRec->z, pRec->n);
98048 zPayload += pRec->n;
98052 if( pRec->n ){
98053 assert( pRec->z!=0 );
98054 assert( pRec->z!=(const char*)sqlite3CtypeMap );
98055 memcpy(zPayload, pRec->z, pRec->n);
98056 zPayload += pRec->n;
98062 assert( nHdr==(int)(zHdr - (u8*)pOut->z) );
98063 assert( nByte==(int)(zPayload - (u8*)pOut->z) );
98065 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
98066 REGISTER_TRACE(pOp->p3, pOut);
98073 ** Store the number of entries (an integer value) in the table or index
98076 ** If P3==0, then an exact count is obtained, which involves visiting
98077 ** every btree page of the table. But if P3 is non-zero, an estimate
98084 assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
98085 pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
98087 if( pOp->p3 ){
98095 pOut->u.i = nEntry;
98103 ** To release (commit) an existing savepoint set P1==1 (SAVEPOINT_RELEASE).
98104 ** To rollback an existing savepoint set P1==2 (SAVEPOINT_ROLLBACK).
98116 p1 = pOp->p1;
98117 zName = pOp->p4.z;
98122 assert( db->pSavepoint==0 || db->autoCommit==0 );
98124 assert( db->pSavepoint || db->isTransactionSavepoint==0 );
98126 assert( p->bIsReader );
98129 if( db->nVdbeWrite>0 ){
98133 sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
98142 ** that the db->aVTrans[] array is empty. */
98143 assert( db->autoCommit==0 || db->nVTrans==0 );
98145 db->nStatement+db->nSavepoint);
98152 pNew->zName = (char *)&pNew[1];
98153 memcpy(pNew->zName, zName, nName+1);
98157 if( db->autoCommit ){
98158 db->autoCommit = 0;
98159 db->isTransactionSavepoint = 1;
98161 db->nSavepoint++;
98165 pNew->pNext = db->pSavepoint;
98166 db->pSavepoint = pNew;
98167 pNew->nDeferredCons = db->nDeferredCons;
98168 pNew->nDeferredImmCons = db->nDeferredImmCons;
98175 /* Find the named savepoint. If there is no such savepoint, then an
98176 ** an error is returned to the user. */
98178 pSavepoint = db->pSavepoint;
98179 pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
98180 pSavepoint = pSavepoint->pNext
98187 }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
98191 sqlite3VdbeError(p, "cannot release savepoint - "
98200 int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
98205 db->autoCommit = 1;
98207 p->pc = (int)(pOp - aOp);
98208 db->autoCommit = 0;
98209 p->rc = rc = SQLITE_BUSY;
98212 rc = p->rc;
98214 db->autoCommit = 0;
98216 db->isTransactionSavepoint = 0;
98220 iSavepoint = db->nSavepoint - iSavepoint - 1;
98222 isSchemaChange = (db->mDbFlags & DBFLAG_SchemaChange)!=0;
98223 for(ii=0; ii<db->nDb; ii++){
98224 rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
98233 for(ii=0; ii<db->nDb; ii++){
98234 rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
98242 db->mDbFlags |= DBFLAG_SchemaChange;
98249 while( db->pSavepoint!=pSavepoint ){
98250 pTmp = db->pSavepoint;
98251 db->pSavepoint = pTmp->pNext;
98253 db->nSavepoint--;
98261 assert( pSavepoint==db->pSavepoint );
98262 db->pSavepoint = pSavepoint->pNext;
98265 db->nSavepoint--;
98269 db->nDeferredCons = pSavepoint->nDeferredCons;
98270 db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
98280 if( p->eVdbeState==VDBE_HALT_STATE ){
98289 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
98300 desiredAutoCommit = pOp->p1;
98301 iRollback = pOp->p2;
98304 assert( db->nVdbeActive>0 ); /* At least this one VM is active */
98305 assert( p->bIsReader );
98307 if( desiredAutoCommit!=db->autoCommit ){
98311 db->autoCommit = 1;
98312 }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
98314 ** return an error indicating that the other VMs must complete first.
98316 sqlite3VdbeError(p, "cannot commit transaction - "
98323 db->autoCommit = (u8)desiredAutoCommit;
98326 p->pc = (int)(pOp - aOp);
98327 db->autoCommit = (u8)(1-desiredAutoCommit);
98328 p->rc = rc = SQLITE_BUSY;
98332 if( p->rc==SQLITE_OK ){
98341 (iRollback)?"cannot rollback - no transaction is active":
98342 "cannot commit - no transaction is active"));
98354 ** If P2 is non-zero, then a write-transaction is started, or if a
98355 ** read-transaction is already active, it is upgraded to a write-transaction.
98356 ** If P2 is zero, then a read-transaction is started. If P2 is 2 or more
98357 ** then an exclusive transaction is started.
98364 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
98366 ** throw an ABORT exception), a statement transaction may also be opened.
98370 ** VDBE to be rolled back after an error without having to roll back the
98381 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
98390 assert( p->bIsReader );
98391 assert( p->readOnly==0 || pOp->p2==0 );
98392 assert( pOp->p2>=0 && pOp->p2<=2 );
98393 assert( pOp->p1>=0 && pOp->p1<db->nDb );
98394 assert( DbMaskTest(p->btreeMask, pOp->p1) );
98396 if( pOp->p2 && (db->flags & (SQLITE_QueryOnly|SQLITE_CorruptRdOnly))!=0 ){
98397 if( db->flags & SQLITE_QueryOnly ){
98407 pDb = &db->aDb[pOp->p1];
98408 pBt = pDb->pBt;
98411 rc = sqlite3BtreeBeginTrans(pBt, pOp->p2, &iMeta);
98416 p->pc = (int)(pOp - aOp);
98417 p->rc = rc;
98423 if( p->usesStmtJournal
98424 && pOp->p2
98425 && (db->autoCommit==0 || db->nVdbeRead>1)
98428 if( p->iStatement==0 ){
98429 assert( db->nStatement>=0 && db->nSavepoint>=0 );
98430 db->nStatement++;
98431 p->iStatement = db->nSavepoint + db->nStatement;
98434 rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
98436 rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
98442 p->nStmtDefCons = db->nDeferredCons;
98443 p->nStmtDefImmCons = db->nDeferredImmCons;
98446 assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
98448 && pOp->p5
98449 && (iMeta!=pOp->p3 || pDb->pSchema->iGeneration!=pOp->p4.i)
98452 ** IMPLEMENTATION-OF: R-03189-51135 As each SQL statement runs, the schema
98456 sqlite3DbFree(db, p->zErrMsg);
98457 p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
98458 /* If the schema-cookie from the database file matches the cookie
98459 ** stored with the in-memory representation of the schema, do
98462 ** If virtual-tables are in use, this is not just an optimization.
98463 ** Often, v-tables store their data in other SQLite tables, which
98464 ** are queried from within xNext() and other v-table methods using
98465 ** prepared queries. If such a query is out-of-date, we do not want to
98467 ** v-table would have to be ready for the sqlite3_vtab structure itself
98469 ** a v-table method.
98471 if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
98472 sqlite3ResetOneSchema(db, pOp->p1);
98474 p->expired = 1;
98480 p->changeCntOn = 0;
98494 ** There must be a read-lock on the database (either a transaction
98495 ** must be started or there must be an open cursor) before
98503 assert( p->bIsReader );
98504 iDb = pOp->p1;
98505 iCookie = pOp->p3;
98506 assert( pOp->p3<SQLITE_N_BTREE_META );
98507 assert( iDb>=0 && iDb<db->nDb );
98508 assert( db->aDb[iDb].pBt!=0 );
98509 assert( DbMaskTest(p->btreeMask, iDb) );
98511 sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
98513 pOut->u.i = iMeta;
98528 ** schema version is set to P3-P5. The "PRAGMA schema_version=N" statement
98536 assert( pOp->p2<SQLITE_N_BTREE_META );
98537 assert( pOp->p1>=0 && pOp->p1<db->nDb );
98538 assert( DbMaskTest(p->btreeMask, pOp->p1) );
98539 assert( p->readOnly==0 );
98540 pDb = &db->aDb[pOp->p1];
98541 assert( pDb->pBt!=0 );
98542 assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
98544 rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
98545 if( pOp->p2==BTREE_SCHEMA_VERSION ){
98547 *(u32*)&pDb->pSchema->schema_cookie = *(u32*)&pOp->p3 - pOp->p5;
98548 db->mDbFlags |= DBFLAG_SchemaChange;
98549 sqlite3FkClearTriggerCache(db, pOp->p1);
98550 }else if( pOp->p2==BTREE_FILE_FORMAT ){
98552 pDb->pSchema->file_format = pOp->p3;
98554 if( pOp->p1==1 ){
98558 p->expired = 0;
98567 ** Open a read-only cursor for the database table whose root page is
98571 ** database. Give the new cursor an identifier of P1. The P1
98573 ** It is an error for P1 to be negative.
98582 ** The P4 value may be either an integer (P4_INT32) or a pointer to
98584 ** object, then table being opened must be an [index b-tree] where the
98586 ** sequence of that index b-tree. Otherwise, if P4 is an integer
98587 ** value, then the table being opened must be a [table b-tree] with a
98597 ** b-tree and if it is this opcode becomes a no-op. In other words,
98619 ** OPFLAG_P2ISREG bit is set in P5 - see below).
98621 ** The P4 value may be either an integer (P4_INT32) or a pointer to
98623 ** object, then table being opened must be an [index b-tree] where the
98625 ** sequence of that index b-tree. Otherwise, if P4 is an integer
98626 ** value, then the table being opened must be a [table b-tree] with a
98635 ** and subsequently delete entries in an index btree. This is a
98658 assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
98659 assert( pOp->p4type==P4_KEYINFO );
98660 pCur = p->apCsr[pOp->p1];
98661 if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
98662 assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
98663 assert( pCur->eCurType==CURTYPE_BTREE );
98664 sqlite3BtreeClearCursor(pCur->uc.pCursor);
98672 assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
98673 assert( p->bIsReader );
98674 assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
98675 || p->readOnly==0 );
98677 if( p->expired==1 ){
98684 p2 = (u32)pOp->p2;
98685 iDb = pOp->p3;
98686 assert( iDb>=0 && iDb<db->nDb );
98687 assert( DbMaskTest(p->btreeMask, iDb) );
98688 pDb = &db->aDb[iDb];
98689 pX = pDb->pBt;
98691 if( pOp->opcode==OP_OpenWrite ){
98693 wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
98695 if( pDb->pSchema->file_format < p->minWriteFileFormat ){
98696 p->minWriteFileFormat = pDb->pSchema->file_format;
98698 if( pOp->p5 & OPFLAG_P2ISREG ){
98700 assert( p2<=(u32)(p->nMem+1 - p->nCursor) );
98703 assert( (pIn2->flags & MEM_Int)!=0 );
98705 p2 = (int)pIn2->u.i;
98714 assert( (pOp->p5 & OPFLAG_P2ISREG)==0 );
98716 if( pOp->p4type==P4_KEYINFO ){
98717 pKeyInfo = pOp->p4.pKeyInfo;
98718 assert( pKeyInfo->enc==ENC(db) );
98719 assert( pKeyInfo->db==db );
98720 nField = pKeyInfo->nAllField;
98721 }else if( pOp->p4type==P4_INT32 ){
98722 nField = pOp->p4.i;
98724 assert( pOp->p1>=0 );
98727 pCur = allocateCursor(p, pOp->p1, nField, CURTYPE_BTREE);
98729 pCur->iDb = iDb;
98730 pCur->nullRow = 1;
98731 pCur->isOrdered = 1;
98732 pCur->pgnoRoot = p2;
98734 pCur->wrFlag = wrFlag;
98736 rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
98737 pCur->pKeyInfo = pKeyInfo;
98739 ** SQLite used to check if the root-page flags were sane at this point
98742 pCur->isTable = pOp->p4type!=P4_KEYINFO;
98747 testcase( pOp->p5 & OPFLAG_BULKCSR );
98748 testcase( pOp->p2 & OPFLAG_SEEKEQ );
98749 sqlite3BtreeCursorHintFlags(pCur->uc.pCursor,
98750 (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
98761 ** Duplicate ephemeral cursors are used for self-joins of materialized views.
98767 pOrig = p->apCsr[pOp->p2];
98769 assert( pOrig->isEphemeral ); /* Only ephemeral cursors can be duplicated */
98771 pCx = allocateCursor(p, pOp->p1, pOrig->nField, CURTYPE_BTREE);
98773 pCx->nullRow = 1;
98774 pCx->isEphemeral = 1;
98775 pCx->pKeyInfo = pOrig->pKeyInfo;
98776 pCx->isTable = pOrig->isTable;
98777 pCx->pgnoRoot = pOrig->pgnoRoot;
98778 pCx->isOrdered = pOrig->isOrdered;
98779 pCx->ub.pBtx = pOrig->ub.pBtx;
98780 pCx->noReuse = 1;
98781 pOrig->noReuse = 1;
98782 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
98783 pCx->pKeyInfo, pCx->uc.pCursor);
98785 ** opened for a database. Since there is already an open cursor when this
98797 ** the main database is read-only. The ephemeral
98800 ** If the cursor P1 is already opened on an ephemeral table, the table
98814 ** can be used as zero-length data for OP_Insert. This is an optimization
98815 ** that avoids an extra OP_Blob opcode to initialize that register.
98836 assert( pOp->p1>=0 );
98837 assert( pOp->p2>=0 );
98838 if( pOp->p3>0 ){
98841 assert( pOp->p2==0 ); /* Only used when number of columns is zero */
98842 assert( pOp->opcode==OP_OpenEphemeral );
98843 assert( aMem[pOp->p3].flags & MEM_Null );
98844 aMem[pOp->p3].n = 0;
98845 aMem[pOp->p3].z = "";
98847 pCx = p->apCsr[pOp->p1];
98848 if( pCx && !pCx->noReuse && ALWAYS(pOp->p2<=pCx->nField) ){
98852 assert( pCx->isEphemeral );
98853 pCx->seqCount = 0;
98854 pCx->cacheStatus = CACHE_STALE;
98855 rc = sqlite3BtreeClearTable(pCx->ub.pBtx, pCx->pgnoRoot, 0);
98857 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_BTREE);
98859 pCx->isEphemeral = 1;
98860 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->ub.pBtx,
98861 BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5,
98864 rc = sqlite3BtreeBeginTrans(pCx->ub.pBtx, 1, 0);
98869 ** automatically created table with root-page 1 (an BLOB_INTKEY table).
98871 if( (pCx->pKeyInfo = pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
98872 assert( pOp->p4type==P4_KEYINFO );
98873 rc = sqlite3BtreeCreateTable(pCx->ub.pBtx, &pCx->pgnoRoot,
98874 BTREE_BLOBKEY | pOp->p5);
98876 assert( pCx->pgnoRoot==SCHEMA_ROOT+1 );
98877 assert( pKeyInfo->db==db );
98878 assert( pKeyInfo->enc==ENC(db) );
98879 rc = sqlite3BtreeCursor(pCx->ub.pBtx, pCx->pgnoRoot, BTREE_WRCSR,
98880 pKeyInfo, pCx->uc.pCursor);
98882 pCx->isTable = 0;
98884 pCx->pgnoRoot = SCHEMA_ROOT;
98885 rc = sqlite3BtreeCursor(pCx->ub.pBtx, SCHEMA_ROOT, BTREE_WRCSR,
98886 0, pCx->uc.pCursor);
98887 pCx->isTable = 1;
98890 pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
98891 assert( p->apCsr[pOp->p1]==pCx );
98893 assert( !sqlite3BtreeClosesWithCursor(pCx->ub.pBtx, pCx->uc.pCursor) );
98894 sqlite3BtreeClose(pCx->ub.pBtx);
98895 p->apCsr[pOp->p1] = 0; /* Not required; helps with static analysis */
98897 assert( sqlite3BtreeClosesWithCursor(pCx->ub.pBtx, pCx->uc.pCursor) );
98902 pCx->nullRow = 1;
98910 ** tables using an external merge-sort algorithm.
98912 ** If argument P3 is non-zero, then it indicates that the sorter may
98919 assert( pOp->p1>=0 );
98920 assert( pOp->p2>=0 );
98921 pCx = allocateCursor(p, pOp->p1, pOp->p2, CURTYPE_SORTER);
98923 pCx->pKeyInfo = pOp->p4.pKeyInfo;
98924 assert( pCx->pKeyInfo->db==db );
98925 assert( pCx->pKeyInfo->enc==ENC(db) );
98926 rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
98940 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98941 pC = p->apCsr[pOp->p1];
98943 if( (pC->seqCount++)==0 ){
98954 ** register P2. In other words, cursor P1 becomes an alias for the
98957 ** A pseudo-table created by this opcode is used to hold a single
98960 ** is the only cursor opcode that works with a pseudo-table.
98963 ** the pseudo-table. If P2 is 0 or negative then the pseudo-cursor
98969 assert( pOp->p1>=0 );
98970 assert( pOp->p3>=0 );
98971 pCx = allocateCursor(p, pOp->p1, pOp->p3, CURTYPE_PSEUDO);
98973 pCx->nullRow = 1;
98974 pCx->seekResult = pOp->p2;
98975 pCx->isTable = 1;
98976 /* Give this pseudo-cursor a fake BtCursor pointer so that pCx
98978 ** for pCx->eCurType==CURTYPE_BTREE inside of sqlite3VdbeCursorMoveto()
98980 pCx->uc.pCursor = sqlite3BtreeFakeValidCursor();
98981 assert( pOp->p5==0 );
98988 ** currently open, this instruction is a no-op.
98991 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
98992 sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
98993 p->apCsr[pOp->p1] = 0;
99002 ** table or index for cursor P1 are used. P4 is a 64-bit integer
99005 ** by the cursor. The high-order bit is set if any column after
99010 pC = p->apCsr[pOp->p1];
99011 assert( pC->eCurType==CURTYPE_BTREE );
99012 pC->maskUsed = *(u64*)pOp->p4.pI64;
99020 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
99022 ** to an SQL index, then P3 is the first in an array of P4 registers
99023 ** that are used as an unpacked index key.
99032 ** this opcode must be followed by an IdxLE opcode with the same arguments.
99036 ** is an equality search.
99047 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
99049 ** to an SQL index, then P3 is the first in an array of P4 registers
99050 ** that are used as an unpacked index key.
99065 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
99067 ** to an SQL index, then P3 is the first in an array of P4 registers
99068 ** that are used as an unpacked index key.
99083 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
99085 ** to an SQL index, then P3 is the first in an array of P4 registers
99086 ** that are used as an unpacked index key.
99099 ** this opcode must be followed by an IdxLE opcode with the same arguments.
99103 ** is an equality search.
99119 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99120 assert( pOp->p2!=0 );
99121 pC = p->apCsr[pOp->p1];
99123 assert( pC->eCurType==CURTYPE_BTREE );
99127 assert( pC->isOrdered );
99128 assert( pC->uc.pCursor!=0 );
99129 oc = pOp->opcode;
99131 pC->nullRow = 0;
99133 pC->seekOp = pOp->opcode;
99136 pC->deferredMoveto = 0;
99137 pC->cacheStatus = CACHE_STALE;
99138 if( pC->isTable ){
99141 assert( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ)==0
99145 ** blob, or NULL. But it needs to be an integer before we can do
99147 pIn3 = &aMem[pOp->p3];
99148 flags3 = pIn3->flags;
99153 newType = pIn3->flags; /* Record the type after applying numeric affinity */
99154 pIn3->flags = flags3; /* But convert the type back to its original */
99156 /* If the P3 value could not be converted into an integer without
99165 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
99170 c = sqlite3IntFloatCompare(iKey, pIn3->u.r);
99176 ** (x > 4.9) -> (x >= 5)
99177 ** (x <= 4.9) -> (x < 5)
99180 assert( OP_SeekGE==(OP_SeekGT-1) );
99181 assert( OP_SeekLT==(OP_SeekLE-1) );
99183 if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
99195 rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)iKey, 0, &res);
99196 pC->movetoTarget = iKey; /* Used by OP_Delete */
99203 ** immediately followed by an OP_IdxGT or OP_IdxLT opcode, respectively,
99206 if( sqlite3BtreeCursorHasHint(pC->uc.pCursor, BTREE_SEEK_EQ) ){
99208 assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
99210 assert( pOp->opcode==OP_SeekGE || pOp[1].opcode==OP_IdxLT );
99211 assert( pOp->opcode==OP_SeekLE || pOp[1].opcode==OP_IdxGT );
99218 nField = pOp->p4.i;
99219 assert( pOp->p4type==P4_INT32 );
99221 r.pKeyInfo = pC->pKeyInfo;
99226 ** r.default_rc = -1;
99231 r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
99232 assert( oc!=OP_SeekGT || r.default_rc==-1 );
99233 assert( oc!=OP_SeekLE || r.default_rc==-1 );
99237 r.aMem = &aMem[pOp->p3];
99243 if( i>0 ) REGISTER_TRACE(pOp->p3+i, &r.aMem[i]);
99248 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &res);
99263 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
99279 rc = sqlite3BtreePrevious(pC->uc.pCursor, 0);
99292 res = sqlite3BtreeEof(pC->uc.pCursor);
99296 assert( pOp->p2>0 );
99309 ** Synopsis: Scan-ahead up to P1 rows
99321 ** This opcode helps to optimize IN operators on a multi-column index
99324 ** of the b-tree instead. A correct answer is obtained if this opcode
99325 ** is omitted or is a no-op.
99327 ** The SeekGE.P3 and SeekGE.P4 operands identify an unpacked key which
99332 ** then this opcode is a no-op and control passes through into the OP_SeekGE.
99344 ** This.P5 is true (non-zero) then a jump is made to This.P2. The P5==0
99384 /* If pOp->p5 is clear, then pOp->p2 points to the first instruction past the
99387 assert( pOp->p2>=(int)(pOp-aOp)+2 );
99389 if( pOp->p5==0 ){
99391 assert( pOp[1].p1==aOp[pOp->p2-1].p1 );
99392 assert( pOp[1].p2==aOp[pOp->p2-1].p2 );
99393 assert( pOp[1].p3==aOp[pOp->p2-1].p3 );
99394 assert( aOp[pOp->p2-1].opcode==OP_IdxGT
99395 || aOp[pOp->p2-1].opcode==OP_IdxGE );
99396 testcase( aOp[pOp->p2-1].opcode==OP_IdxGE );
99399 assert( pOp->p2==(int)(pOp-aOp)+2 );
99400 assert( aOp[pOp->p2-1].opcode==OP_SeekGE );
99404 assert( pOp->p1>0 );
99405 pC = p->apCsr[pOp[1].p1];
99407 assert( pC->eCurType==CURTYPE_BTREE );
99408 assert( !pC->isTable );
99409 if( !sqlite3BtreeCursorIsValidNN(pC->uc.pCursor) ){
99411 if( db->flags&SQLITE_VdbeTrace ){
99412 printf("... cursor not valid - fall through\n");
99417 nStep = pOp->p1;
99419 r.pKeyInfo = pC->pKeyInfo;
99436 if( res>0 && pOp->p5==0 ){
99440 if( db->flags&SQLITE_VdbeTrace ){
99441 printf("... %d steps and then skip\n", pOp->p1 - nStep);
99451 if( db->flags&SQLITE_VdbeTrace ){
99452 printf("... %d steps and then success\n", pOp->p1 - nStep);
99461 if( db->flags&SQLITE_VdbeTrace ){
99462 printf("... fall through after %d steps\n", pOp->p1);
99468 nStep--;
99469 pC->cacheStatus = CACHE_STALE;
99470 rc = sqlite3BtreeNext(pC->uc.pCursor, 0);
99491 ** The seekHit integer represents the maximum of terms in an index for which
99493 ** than the total number of equality terms in an index lookup, then the
99495 ** early, thus saving work. This is part of the IN-early-out optimization.
99497 ** P1 must be a valid b-tree cursor.
99501 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99502 pC = p->apCsr[pOp->p1];
99504 assert( pOp->p3>=pOp->p2 );
99505 if( pC->seekHit<pOp->p2 ){
99507 if( db->flags&SQLITE_VdbeTrace ){
99508 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p2);
99511 pC->seekHit = pOp->p2;
99512 }else if( pC->seekHit>pOp->p3 ){
99514 if( db->flags&SQLITE_VdbeTrace ){
99515 printf("seekHit changes from %d to %d\n", pC->seekHit, pOp->p3);
99518 pC->seekHit = pOp->p3;
99532 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99533 pCur = p->apCsr[pOp->p1];
99534 VdbeBranchTaken(pCur==0 || pCur->nullRow, 2);
99535 if( pCur==0 || pCur->nullRow ){
99545 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
99548 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
99562 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
99565 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
99567 ** does contain an entry whose prefix matches the P3/P4 record then control
99580 ** Register P3 is the first of P4 registers that form an unpacked
99581 ** record. Cursor P1 is an index btree. P2 is a jump destination.
99585 ** This opcode is an optimization attempt only. If this opcode always
99596 ** This opcode is used in IN clause processing for a multi-column key.
99597 ** If an IN clause is attached to an element of the key other than the
99598 ** left-most element, and if there are no matches on the most recent
99612 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
99615 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
99617 ** record are not-NULL then a check is done to determine if any row in the
99633 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99634 pC = p->apCsr[pOp->p1];
99637 if( db->flags&SQLITE_VdbeTrace ){
99638 printf("seekHit is %d\n", pC->seekHit);
99641 if( pC->seekHit>=pOp->p4.i ) break;
99655 if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
99658 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99659 assert( pOp->p4type==P4_INT32 );
99660 pC = p->apCsr[pOp->p1];
99663 pC->seekOp = pOp->opcode;
99665 r.aMem = &aMem[pOp->p3];
99666 assert( pC->eCurType==CURTYPE_BTREE );
99667 assert( pC->uc.pCursor!=0 );
99668 assert( pC->isTable==0 );
99669 r.nField = (u16)pOp->p4.i;
99671 /* Key values in an array of registers */
99672 r.pKeyInfo = pC->pKeyInfo;
99675 (void)sqlite3FaultSim(50); /* For use by --counter in TH3 */
99679 if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
99682 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, &r, &pC->seekResult);
99685 assert( r.aMem->flags & MEM_Blob );
99686 assert( pOp->opcode!=OP_NoConflict );
99690 pIdxKey = sqlite3VdbeAllocUnpackedRecord(pC->pKeyInfo);
99692 sqlite3VdbeRecordUnpack(pC->pKeyInfo, r.aMem->n, r.aMem->z, pIdxKey);
99693 pIdxKey->default_rc = 0;
99694 rc = sqlite3BtreeIndexMoveto(pC->uc.pCursor, pIdxKey, &pC->seekResult);
99700 alreadyExists = (pC->seekResult==0);
99701 pC->nullRow = 1-alreadyExists;
99702 pC->deferredMoveto = 0;
99703 pC->cacheStatus = CACHE_STALE;
99704 if( pOp->opcode==OP_Found ){
99712 if( pOp->opcode==OP_NoConflict ){
99724 if( pOp->opcode==OP_IfNoHope ){
99725 pC->seekHit = pOp->p4.i;
99734 ** P1 is the index of a cursor open on an SQL table btree (with integer
99735 ** keys). If register P3 does not contain an integer or if P1 does not
99737 ** Or, if P2 is 0, raise an SQLITE_CORRUPT error. If P1 does contain
99743 ** the P3 register must be guaranteed to contain an integer value. With this
99744 ** opcode, register P3 might not contain an integer.
99747 ** (with arbitrary multi-value keys).
99758 ** P1 is the index of a cursor open on an SQL table btree (with integer
99759 ** keys). P3 is an integer rowid. If P1 does not contain a record with
99760 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
99766 ** P3 register to contain a non-integer value, in which case the jump is
99767 ** always taken. This opcode requires that P3 always contain an integer.
99770 ** (with arbitrary multi-value keys).
99784 pIn3 = &aMem[pOp->p3];
99785 testcase( pIn3->flags & MEM_Int );
99786 testcase( pIn3->flags & MEM_IntReal );
99787 testcase( pIn3->flags & MEM_Real );
99788 testcase( (pIn3->flags & (MEM_Str|MEM_Int))==MEM_Str );
99789 if( (pIn3->flags & (MEM_Int|MEM_IntReal))==0 ){
99790 /* If pIn3->u.i does not contain an integer, compute iKey as the
99792 ** into an integer without loss of information. Take care to avoid
99804 pIn3 = &aMem[pOp->p3];
99805 assert( (pIn3->flags & MEM_Int)!=0 || pOp->opcode==OP_SeekRowid );
99806 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99807 iKey = pIn3->u.i;
99809 pC = p->apCsr[pOp->p1];
99812 if( pOp->opcode==OP_SeekRowid ) pC->seekOp = OP_SeekRowid;
99814 assert( pC->isTable );
99815 assert( pC->eCurType==CURTYPE_BTREE );
99816 pCrsr = pC->uc.pCursor;
99821 pC->movetoTarget = iKey; /* Used by OP_Delete */
99822 pC->nullRow = 0;
99823 pC->cacheStatus = CACHE_STALE;
99824 pC->deferredMoveto = 0;
99826 pC->seekResult = res;
99829 if( pOp->p2==0 ){
99848 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99849 assert( p->apCsr[pOp->p1]!=0 );
99850 assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
99852 pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
99868 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
99875 int res; /* Result of an sqlite3BtreeLast() */
99885 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
99886 pC = p->apCsr[pOp->p1];
99888 assert( pC->isTable );
99889 assert( pC->eCurType==CURTYPE_BTREE );
99890 assert( pC->uc.pCursor!=0 );
99893 ** thing) is obtained in a two-step algorithm.
99905 assert( pC->isTable );
99917 if( !pC->useRandomRowid ){
99918 rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
99923 v = 1; /* IMP: R-61914-48074 */
99925 assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
99926 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
99928 pC->useRandomRowid = 1;
99930 v++; /* IMP: R-29538-34987 */
99936 if( pOp->p3 ){
99938 assert( pOp->p3>0 );
99939 if( p->pFrame ){
99940 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
99942 assert( pOp->p3<=pFrame->nMem );
99943 pMem = &pFrame->aMem[pOp->p3];
99946 assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
99947 pMem = &aMem[pOp->p3];
99952 REGISTER_TRACE(pOp->p3, pMem);
99954 assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
99955 if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
99956 rc = SQLITE_FULL; /* IMP: R-17817-00630 */
99959 if( v<pMem->u.i+1 ){
99960 v = pMem->u.i + 1;
99962 pMem->u.i = v;
99965 if( pC->useRandomRowid ){
99966 /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
99970 assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
99971 ** an AUTOINCREMENT table. */
99976 }while( ((rc = sqlite3BtreeTableMoveto(pC->uc.pCursor, (u64)v,
99982 rc = SQLITE_FULL; /* IMP: R-38219-53002 */
99985 assert( v>0 ); /* EV: R-40812-03570 */
99987 pC->deferredMoveto = 0;
99988 pC->cacheStatus = CACHE_STALE;
99990 pOut->u.i = v;
99997 ** Write an entry into the table of cursor P1. A new entry is
99998 ** created if it doesn't already exist or the data for an existing
100009 ** run faster by avoiding an unnecessary seek on cursor P1. However,
100013 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
100015 ** is part of an INSERT operation. The difference is only important to
100019 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
100022 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
100023 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
100036 const char *zDb; /* database name - used by the update hook */
100037 Table *pTab; /* Table structure - used by update and pre-update hooks */
100040 pData = &aMem[pOp->p2];
100041 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100043 pC = p->apCsr[pOp->p1];
100045 assert( pC->eCurType==CURTYPE_BTREE );
100046 assert( pC->deferredMoveto==0 );
100047 assert( pC->uc.pCursor!=0 );
100048 assert( (pOp->p5 & OPFLAG_ISNOOP) || pC->isTable );
100049 assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
100050 REGISTER_TRACE(pOp->p2, pData);
100053 pKey = &aMem[pOp->p3];
100054 assert( pKey->flags & MEM_Int );
100056 REGISTER_TRACE(pOp->p3, pKey);
100057 x.nKey = pKey->u.i;
100059 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
100060 assert( pC->iDb>=0 );
100061 zDb = db->aDb[pC->iDb].zDbSName;
100062 pTab = pOp->p4.pTab;
100063 assert( (pOp->p5 & OPFLAG_ISNOOP) || HasRowid(pTab) );
100070 /* Invoke the pre-update hook, if any */
100072 if( db->xPreUpdateCallback && !(pOp->p5 & OPFLAG_ISUPDATE) ){
100073 sqlite3VdbePreUpdateHook(p,pC,SQLITE_INSERT,zDb,pTab,x.nKey,pOp->p2,-1);
100075 if( db->xUpdateCallback==0 || pTab->aCol==0 ){
100076 /* Prevent post-update hook from running in cases when it should not */
100080 if( pOp->p5 & OPFLAG_ISNOOP ) break;
100083 assert( (pOp->p5 & OPFLAG_LASTROWID)==0 || (pOp->p5 & OPFLAG_NCHANGE)!=0 );
100084 if( pOp->p5 & OPFLAG_NCHANGE ){
100085 p->nChange++;
100086 if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = x.nKey;
100088 assert( (pData->flags & (MEM_Blob|MEM_Str))!=0 || pData->n==0 );
100089 x.pData = pData->z;
100090 x.nData = pData->n;
100091 seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
100092 if( pData->flags & MEM_Zero ){
100093 x.nZero = pData->u.nZero;
100099 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
100100 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
100103 pC->deferredMoveto = 0;
100104 pC->cacheStatus = CACHE_STALE;
100107 /* Invoke the update-hook if required. */
100110 assert( db->xUpdateCallback!=0 );
100111 assert( pTab->aCol!=0 );
100112 db->xUpdateCallback(db->pUpdateArg,
100113 (pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT,
100114 zDb, pTab->zName, x.nKey);
100122 ** of table - intkey or index. This opcode is used as part of copying
100127 ** This opcode must be followed by either an Insert or InsertIdx opcode
100135 assert( pOp[1].opcode==OP_Insert || pOp->p3==0 );
100136 assert( pOp[1].opcode==OP_IdxInsert || pOp->p3>0 );
100138 pDest = p->apCsr[pOp->p1];
100139 pSrc = p->apCsr[pOp->p2];
100140 iKey = pOp->p3 ? aMem[pOp->p3].u.i : 0;
100141 rc = sqlite3BtreeTransferRow(pDest->uc.pCursor, pSrc->uc.pCursor, iKey);
100153 ** the next Next instruction will be a no-op. As a result, in this case
100156 ** left in an undefined state.
100168 ** pre-update-hook for deletes is run, but the btree is otherwise unchanged.
100169 ** This happens when the OP_Delete is to be shortly followed by an OP_Insert
100172 ** P1 must not be pseudo-table. It has to be a real table with
100176 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
100178 ** this case. Specifically, if one is configured, the pre-update hook is
100179 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
100192 opflags = pOp->p2;
100193 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100194 pC = p->apCsr[pOp->p1];
100196 assert( pC->eCurType==CURTYPE_BTREE );
100197 assert( pC->uc.pCursor!=0 );
100198 assert( pC->deferredMoveto==0 );
100202 if( pOp->p4type==P4_TABLE
100203 && HasRowid(pOp->p4.pTab)
100204 && pOp->p5==0
100205 && sqlite3BtreeCursorIsValidNN(pC->uc.pCursor)
100208 ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
100210 i64 iKey = sqlite3BtreeIntegerKey(pC->uc.pCursor);
100211 assert( CORRUPT_DB || pC->movetoTarget==iKey );
100215 /* If the update-hook or pre-update-hook will be invoked, set zDb to
100220 if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
100221 assert( pC->iDb>=0 );
100222 assert( pOp->p4.pTab!=0 );
100223 zDb = db->aDb[pC->iDb].zDbSName;
100224 pTab = pOp->p4.pTab;
100225 if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
100226 pC->movetoTarget = sqlite3BtreeIntegerKey(pC->uc.pCursor);
100234 /* Invoke the pre-update-hook if required. */
100235 assert( db->xPreUpdateCallback==0 || pTab==pOp->p4.pTab );
100236 if( db->xPreUpdateCallback && pTab ){
100239 || (aMem[pOp->p3].flags & MEM_Int)
100243 zDb, pTab, pC->movetoTarget,
100244 pOp->p3, -1
100251 assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
100256 if( p->pFrame==0 ){
100257 if( pC->isEphemeral==0
100258 && (pOp->p5 & OPFLAG_AUXDELETE)==0
100259 && (pC->wrFlag & OPFLAG_FORDELETE)==0
100263 if( pOp->p2 & OPFLAG_NCHANGE ){
100264 nExtraDelete--;
100269 rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
100270 pC->cacheStatus = CACHE_STALE;
100272 pC->seekResult = 0;
100275 /* Invoke the update-hook if required. */
100277 p->nChange++;
100278 if( db->xUpdateCallback && ALWAYS(pTab!=0) && HasRowid(pTab) ){
100279 db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
100280 pC->movetoTarget);
100281 assert( pC->iDb>=0 );
100295 sqlite3VdbeSetChanges(db, p->nChange);
100296 p->nChange = 0;
100320 pC = p->apCsr[pOp->p1];
100322 assert( pOp->p4type==P4_INT32 );
100323 pIn3 = &aMem[pOp->p3];
100324 nKeyCol = pOp->p4.i;
100340 ** a register that is the source for a pseudo-table cursor created using
100341 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
100348 pOut = &aMem[pOp->p2];
100349 pC = p->apCsr[pOp->p1];
100352 assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
100353 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100355 p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
100368 ** If cursor P1 is an index, then the content is the key of the row.
100372 ** of a real table, not a pseudo-table.
100374 ** If P3!=0 then this opcode is allowed to make an ephemeral pointer
100376 ** register will be invalidated as soon as the cursor moves - including
100394 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100395 pC = p->apCsr[pOp->p1];
100397 assert( pC->eCurType==CURTYPE_BTREE );
100399 assert( pC->nullRow==0 );
100400 assert( pC->uc.pCursor!=0 );
100401 pCrsr = pC->uc.pCursor;
100411 assert( pC->deferredMoveto==0 );
100415 if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
100421 if( !pOp->p3 ) Deephemeralize(pOut);
100423 REGISTER_TRACE(pOp->p2, pOut);
100430 ** Store in register P2 an integer which is the key of the table entry that
100433 ** P1 can be either an ordinary table or a virtual table. There used to
100444 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100445 pC = p->apCsr[pOp->p1];
100447 assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
100448 if( pC->nullRow ){
100449 pOut->flags = MEM_Null;
100451 }else if( pC->deferredMoveto ){
100452 v = pC->movetoTarget;
100454 }else if( pC->eCurType==CURTYPE_VTAB ){
100455 assert( pC->uc.pVCur!=0 );
100456 pVtab = pC->uc.pVCur->pVtab;
100457 pModule = pVtab->pModule;
100458 assert( pModule->xRowid );
100459 rc = pModule->xRowid(pC->uc.pVCur, &v);
100464 assert( pC->eCurType==CURTYPE_BTREE );
100465 assert( pC->uc.pCursor!=0 );
100468 if( pC->nullRow ){
100469 pOut->flags = MEM_Null;
100472 v = sqlite3BtreeIntegerKey(pC->uc.pCursor);
100474 pOut->u.i = v;
100485 ** pseudo-cursor that always returns NULL for every column.
100490 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100491 pC = p->apCsr[pOp->p1];
100494 ** pseudo-cursor that always gives null rows. */
100495 pC = allocateCursor(p, pOp->p1, 1, CURTYPE_PSEUDO);
100497 pC->seekResult = 0;
100498 pC->isTable = 1;
100499 pC->noReuse = 1;
100500 pC->uc.pCursor = sqlite3BtreeFakeValidCursor();
100502 pC->nullRow = 1;
100503 pC->cacheStatus = CACHE_STALE;
100504 if( pC->eCurType==CURTYPE_BTREE ){
100505 assert( pC->uc.pCursor!=0 );
100506 sqlite3BtreeClearCursor(pC->uc.pCursor);
100509 if( pC->seekOp==0 ) pC->seekOp = OP_NullRow;
100542 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100543 pC = p->apCsr[pOp->p1];
100545 assert( pC->eCurType==CURTYPE_BTREE );
100546 pCrsr = pC->uc.pCursor;
100550 pC->seekOp = pOp->opcode;
100552 if( pOp->opcode==OP_SeekEnd ){
100553 assert( pOp->p2==0 );
100554 pC->seekResult = -1;
100560 pC->nullRow = (u8)res;
100561 pC->deferredMoveto = 0;
100562 pC->cacheStatus = CACHE_STALE;
100564 if( pOp->p2>0 ){
100574 ** with cursor P1 and let X be 10*log2(N) if N is positive or -1
100585 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100586 assert( pOp->p4type==P4_INT32 );
100587 assert( pOp->p3>=-1 && pOp->p3<=640*2 );
100588 assert( pOp->p4.i>=-1 && pOp->p4.i<=640*2 );
100589 pC = p->apCsr[pOp->p1];
100591 pCrsr = pC->uc.pCursor;
100596 sz = -1; /* -Infinity encoding */
100602 res = sz>=pOp->p3 && sz<=pOp->p4.i;
100615 ** This opcode is an alias for OP_Sort and OP_Rewind that is used
100621 ** it increments an undocumented global variable used for testing.
100634 sqlite3_search_count--;
100636 p->aCounter[SQLITE_STMTSTATUS_SORT]++;
100648 ** If P2 is zero, that is an assertion that the P1 table is never
100660 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100661 assert( pOp->p5==0 );
100662 assert( pOp->p2>=0 && pOp->p2<p->nOp );
100664 pC = p->apCsr[pOp->p1];
100666 assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
100669 pC->seekOp = OP_Rewind;
100674 assert( pC->eCurType==CURTYPE_BTREE );
100675 pCrsr = pC->uc.pCursor;
100678 pC->deferredMoveto = 0;
100679 pC->cacheStatus = CACHE_STALE;
100682 pC->nullRow = (u8)res;
100683 if( pOp->p2>0 ){
100697 ** The Next opcode is only valid following an SeekGT, SeekGE, or
100701 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
100705 ** means P1 is an SQL index and that this instruction could have been
100710 ** number P5-1 in the prepared statement is incremented.
100722 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
100726 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
100730 ** means P1 is an SQL index and that this instruction could have been
100735 ** number P5-1 in the prepared statement is incremented.
100747 pC = p->apCsr[pOp->p1];
100753 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100754 assert( pOp->p5==0
100755 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
100756 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
100757 pC = p->apCsr[pOp->p1];
100759 assert( pC->deferredMoveto==0 );
100760 assert( pC->eCurType==CURTYPE_BTREE );
100761 assert( pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
100762 || pC->seekOp==OP_Last || pC->seekOp==OP_IfNoHope
100763 || pC->seekOp==OP_NullRow);
100764 rc = sqlite3BtreePrevious(pC->uc.pCursor, pOp->p3);
100768 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100769 assert( pOp->p5==0
100770 || pOp->p5==SQLITE_STMTSTATUS_FULLSCAN_STEP
100771 || pOp->p5==SQLITE_STMTSTATUS_AUTOINDEX);
100772 pC = p->apCsr[pOp->p1];
100774 assert( pC->deferredMoveto==0 );
100775 assert( pC->eCurType==CURTYPE_BTREE );
100776 assert( pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
100777 || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found
100778 || pC->seekOp==OP_NullRow|| pC->seekOp==OP_SeekRowid
100779 || pC->seekOp==OP_IfNoHope);
100780 rc = sqlite3BtreeNext(pC->uc.pCursor, pOp->p3);
100783 pC->cacheStatus = CACHE_STALE;
100786 pC->nullRow = 0;
100787 p->aCounter[pOp->p5]++;
100795 pC->nullRow = 1;
100802 ** Register P2 holds an SQL index key made using the
100809 ** be an optimization.
100811 ** If P5 has the OPFLAG_APPEND bit set, that is a hint to the b-tree layer
100812 ** that this insert is likely to be an append.
100819 ** run faster by avoiding an unnecessary seek on cursor P1. However,
100831 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100832 pC = p->apCsr[pOp->p1];
100836 pIn2 = &aMem[pOp->p2];
100837 assert( (pIn2->flags & MEM_Blob) || (pOp->p5 & OPFLAG_PREFORMAT) );
100838 if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
100839 assert( pC->eCurType==CURTYPE_BTREE );
100840 assert( pC->isTable==0 );
100843 x.nKey = pIn2->n;
100844 x.pKey = pIn2->z;
100845 x.aMem = aMem + pOp->p3;
100846 x.nMem = (u16)pOp->p4.i;
100847 rc = sqlite3BtreeInsert(pC->uc.pCursor, &x,
100848 (pOp->p5 & (OPFLAG_APPEND|OPFLAG_SAVEPOSITION|OPFLAG_PREFORMAT)),
100849 ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
100851 assert( pC->deferredMoveto==0 );
100852 pC->cacheStatus = CACHE_STALE;
100860 ** Register P2 holds an SQL index key made using the
100867 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100868 pC = p->apCsr[pOp->p1];
100872 pIn2 = &aMem[pOp->p2];
100873 assert( pIn2->flags & MEM_Blob );
100874 assert( pC->isTable==0 );
100886 ** an unpacked index key. This opcode removes that entry from the
100889 ** If P5 is not zero, then raise an SQLITE_CORRUPT_INDEX error
100891 ** an UPDATE or DELETE statement and the index entry to be updated
100895 ** this (self-correcting and non-critical) error if in writable_schema mode.
100903 assert( pOp->p3>0 );
100904 assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
100905 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100906 pC = p->apCsr[pOp->p1];
100908 assert( pC->eCurType==CURTYPE_BTREE );
100910 pCrsr = pC->uc.pCursor;
100912 r.pKeyInfo = pC->pKeyInfo;
100913 r.nField = (u16)pOp->p3;
100915 r.aMem = &aMem[pOp->p2];
100921 }else if( pOp->p5 && !sqlite3WritableSchema(db) ){
100925 assert( pC->deferredMoveto==0 );
100926 pC->cacheStatus = CACHE_STALE;
100927 pC->seekResult = 0;
100934 ** P1 is an open index cursor and P3 is a cursor on the corresponding
100942 ** P4 may be an array of integers (type P4_INTARRAY) containing
100944 ** is non-zero, then reading column a(i)-1 from cursor P3 is
100953 ** Write into register P2 an integer which is the last entry in the record at
100965 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
100966 pC = p->apCsr[pOp->p1];
100968 assert( pC->eCurType==CURTYPE_BTREE || IsNullCursor(pC) );
100969 assert( pC->uc.pCursor!=0 );
100970 assert( pC->isTable==0 || IsNullCursor(pC) );
100971 assert( pC->deferredMoveto==0 );
100972 assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
100979 ** since it was last positioned and an error (e.g. OOM or an IO error)
100983 if( !pC->nullRow ){
100985 rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
100989 if( pOp->opcode==OP_DeferredSeek ){
100990 assert( pOp->p3>=0 && pOp->p3<p->nCursor );
100991 pTabCur = p->apCsr[pOp->p3];
100993 assert( pTabCur->eCurType==CURTYPE_BTREE );
100994 assert( pTabCur->uc.pCursor!=0 );
100995 assert( pTabCur->isTable );
100996 pTabCur->nullRow = 0;
100997 pTabCur->movetoTarget = rowid;
100998 pTabCur->deferredMoveto = 1;
100999 pTabCur->cacheStatus = CACHE_STALE;
101000 assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
101001 assert( !pTabCur->isEphemeral );
101002 pTabCur->ub.aAltMap = pOp->p4.ai;
101003 assert( !pC->isEphemeral );
101004 pTabCur->pAltCursor = pC;
101007 pOut->u.i = rowid;
101010 assert( pOp->opcode==OP_IdxRowid );
101011 sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
101020 ** already occurred, this instruction is a no-op.
101025 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
101026 pC = p->apCsr[pOp->p1];
101027 if( pC->deferredMoveto ){
101037 ** The P4 register values beginning with P3 form an unpacked index
101048 ** The P4 register values beginning with P3 form an unpacked index
101059 ** The P4 register values beginning with P3 form an unpacked index
101070 ** The P4 register values beginning with P3 form an unpacked index
101086 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
101087 pC = p->apCsr[pOp->p1];
101089 assert( pC->isOrdered );
101090 assert( pC->eCurType==CURTYPE_BTREE );
101091 assert( pC->uc.pCursor!=0);
101092 assert( pC->deferredMoveto==0 );
101093 assert( pOp->p4type==P4_INT32 );
101094 r.pKeyInfo = pC->pKeyInfo;
101095 r.nField = (u16)pOp->p4.i;
101096 if( pOp->opcode<OP_IdxLT ){
101097 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
101098 r.default_rc = -1;
101100 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
101103 r.aMem = &aMem[pOp->p3];
101109 REGISTER_TRACE(pOp->p3+i, &aMem[pOp->p3+i]);
101120 assert( pC->eCurType==CURTYPE_BTREE );
101121 pCur = pC->uc.pCursor;
101139 if( (pOp->opcode&1)==(OP_IdxLT&1) ){
101140 assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
101141 res = -res;
101143 assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
101154 ** Delete an entire database table or index whose root page in the database
101164 ** value of the root page that moved - its value before the move occurred -
101170 ** This opcode throws an error if there are any active reader VMs when
101172 ** updating existing cursors when a root page is moved in an AUTOVACUUM
101173 ** database. This error is thrown even if the database is not an AUTOVACUUM
101174 ** db in order to avoid introducing an incompatibility between autovacuum
101175 ** and non-autovacuum modes.
101184 assert( p->readOnly==0 );
101185 assert( pOp->p1>1 );
101187 pOut->flags = MEM_Null;
101188 if( db->nVdbeRead > db->nVDestroy+1 ){
101190 p->errorAction = OE_Abort;
101193 iDb = pOp->p3;
101194 assert( DbMaskTest(p->btreeMask, iDb) );
101196 rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
101197 pOut->flags = MEM_Int;
101198 pOut->u.i = iMoved;
101202 sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
101222 ** If the P3 value is non-zero, then the row change count is incremented
101234 assert( p->readOnly==0 );
101235 assert( DbMaskTest(p->btreeMask, pOp->p2) );
101236 rc = sqlite3BtreeClearTable(db->aDb[pOp->p2].pBt, (u32)pOp->p1, &nChange);
101237 if( pOp->p3 ){
101238 p->nChange += nChange;
101239 if( pOp->p3>0 ){
101240 assert( memIsValid(&aMem[pOp->p3]) );
101241 memAboutToChange(p, &aMem[pOp->p3]);
101242 aMem[pOp->p3].u.i += nChange;
101260 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
101261 pC = p->apCsr[pOp->p1];
101264 sqlite3VdbeSorterReset(db, pC->uc.pSorter);
101266 assert( pC->eCurType==CURTYPE_BTREE );
101267 assert( pC->isEphemeral );
101268 rc = sqlite3BtreeClearTableOfCursor(pC->uc.pCursor);
101277 ** Allocate a new b-tree in the main database file if P1==0 or in the
101278 ** TEMP database file if P1==1 or in an attached database if
101280 ** it must be 2 (BTREE_BLOBKEY) for an index or WITHOUT ROWID table.
101281 ** The root page number of the new b-tree is stored in register P2.
101290 assert( pOp->p3==BTREE_INTKEY || pOp->p3==BTREE_BLOBKEY );
101291 assert( pOp->p1>=0 && pOp->p1<db->nDb );
101292 assert( DbMaskTest(p->btreeMask, pOp->p1) );
101293 assert( p->readOnly==0 );
101294 pDb = &db->aDb[pOp->p1];
101295 assert( pDb->pBt!=0 );
101296 rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, pOp->p3);
101298 pOut->u.i = pgno;
101311 ** 0x0002 Set db->nAnalysisLimit to P2 while the statements in
101324 db->nSqlExec++;
101327 xAuth = db->xAuth;
101329 mTrace = db->mTrace;
101330 savedAnalysisLimit = db->nAnalysisLimit;
101331 if( pOp->p1 & 0x0001 ){
101333 db->xAuth = 0;
101335 db->mTrace = 0;
101337 if( pOp->p1 & 0x0002 ){
101338 db->nAnalysisLimit = pOp->p2;
101340 rc = sqlite3_exec(db, pOp->p4.z, 0, 0, &zErr);
101341 db->nSqlExec--;
101343 db->xAuth = xAuth;
101345 db->mTrace = mTrace;
101346 db->nAnalysisLimit = savedAnalysisLimit;
101363 ** then runs the new virtual machine. It is thus a re-entrant opcode.
101376 for(iDb=0; iDb<db->nDb; iDb++){
101377 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
101381 iDb = pOp->p1;
101382 assert( iDb>=0 && iDb<db->nDb );
101384 || db->mallocFailed
101385 || (CORRUPT_DB && (db->flags & SQLITE_NoSchemaError)!=0) );
101388 if( pOp->p4.z==0 ){
101389 sqlite3SchemaClear(db->aDb[iDb].pSchema);
101390 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
101391 rc = sqlite3InitOne(db, iDb, &p->zErrMsg, pOp->p5);
101392 db->mDbFlags |= DBFLAG_SchemaChange;
101393 p->expired = 0;
101400 initData.pzErrMsg = &p->zErrMsg;
101402 initData.mxPage = sqlite3BtreeLastPage(db->aDb[iDb].pBt);
101405 db->aDb[iDb].zDbSName, zSchema, pOp->p4.z);
101409 assert( db->init.busy==0 );
101410 db->init.busy = 1;
101413 assert( !db->mallocFailed );
101417 /* The OP_ParseSchema opcode with a non-NULL P4 argument should parse
101423 db->init.busy = 0;
101444 assert( pOp->p1>=0 && pOp->p1<db->nDb );
101445 rc = sqlite3AnalysisLoad(db, pOp->p1);
101453 ** Remove the internal (in-memory) data structures that describe
101461 sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
101467 ** Remove the internal (in-memory) data structures that describe
101468 ** the index named P4 in database P1. This is called after an index
101475 sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
101481 ** Remove the internal (in-memory) data structures that describe
101489 sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
101497 ** Do an analysis of the currently open database. Store in
101498 ** register (P1+1) the text of an error message describing any problems.
101521 assert( p->bIsReader );
101522 assert( pOp->p4type==P4_INTARRAY );
101523 nRoot = pOp->p2;
101524 aRoot = pOp->p4.ai;
101528 assert( pOp->p1>0 && (pOp->p1+1)<=(p->nMem+1 - p->nCursor) );
101529 pnErr = &aMem[pOp->p1];
101530 assert( (pnErr->flags & MEM_Int)!=0 );
101531 assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
101532 pIn1 = &aMem[pOp->p1+1];
101533 assert( pOp->p5<db->nDb );
101534 assert( DbMaskTest(p->btreeMask, pOp->p5) );
101535 rc = sqlite3BtreeIntegrityCheck(db, db->aDb[pOp->p5].pBt, &aRoot[1],
101536 &aMem[pOp->p3], nRoot, (int)pnErr->u.i+1, &nErr, &z);
101544 pnErr->u.i -= nErr-1;
101545 sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
101559 ** An assertion fails if P2 is not an integer.
101562 pIn1 = &aMem[pOp->p1];
101563 pIn2 = &aMem[pOp->p2];
101564 assert( (pIn2->flags & MEM_Int)!=0 );
101565 if( (pIn1->flags & MEM_Blob)==0 ){
101569 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn2->u.i);
101584 pIn1 = &aMem[pOp->p1];
101585 assert( (pIn1->flags & MEM_Blob)==0 || sqlite3VdbeMemIsRowSet(pIn1) );
101586 if( (pIn1->flags & MEM_Blob)==0
101587 || sqlite3RowSetNext((RowSet*)pIn1->z, &val)==0
101596 sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
101604 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
101613 ** must have P4==0, the final set must have P4==-1, and for all other sets
101618 ** (b) when P4==-1 there is no need to insert the value, as it will
101628 pIn1 = &aMem[pOp->p1];
101629 pIn3 = &aMem[pOp->p3];
101630 iSet = pOp->p4.i;
101631 assert( pIn3->flags&MEM_Int );
101634 ** delete it now and initialize P1 with an empty rowset
101636 if( (pIn1->flags & MEM_Blob)==0 ){
101640 assert( pOp->p4type==P4_INT32 );
101641 assert( iSet==-1 || iSet>=0 );
101643 exists = sqlite3RowSetTest((RowSet*)pIn1->z, iSet, pIn3->u.i);
101648 sqlite3RowSetInsert((RowSet*)pIn1->z, pIn3->u.i);
101661 ** cell in an array of values used as arguments to the sub-program. P2
101662 ** contains the address to jump to if the sub-program throws an IGNORE
101664 ** no possibility that an IGNORE exception will be raised.
101667 ** memory required by the sub-vdbe at runtime.
101671 ** If P5 is non-zero, then recursive program invocation is enabled.
101674 int nMem; /* Number of memory registers for sub-program */
101675 i64 nByte; /* Bytes of runtime space required for sub-program */
101680 SubProgram *pProgram; /* Sub-program to execute */
101683 pProgram = pOp->p4.pProgram;
101684 pRt = &aMem[pOp->p3];
101685 assert( pProgram->nOp>0 );
101688 ** disabled for backwards compatibility (p5 is set if this sub-program
101698 if( pOp->p5 ){
101699 t = pProgram->token;
101700 for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
101704 if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
101714 if( (pRt->flags&MEM_Blob)==0 ){
101720 nMem = pProgram->nMem + pProgram->nCsr;
101722 if( pProgram->nCsr==0 ) nMem++;
101725 + pProgram->nCsr * sizeof(VdbeCursor*)
101726 + (7 + (i64)pProgram->nOp)/8;
101732 pRt->flags = MEM_Blob|MEM_Dyn;
101733 pRt->z = (char*)pFrame;
101734 pRt->n = (int)nByte;
101735 pRt->xDel = sqlite3VdbeFrameMemDel;
101737 pFrame->v = p;
101738 pFrame->nChildMem = nMem;
101739 pFrame->nChildCsr = pProgram->nCsr;
101740 pFrame->pc = (int)(pOp - aOp);
101741 pFrame->aMem = p->aMem;
101742 pFrame->nMem = p->nMem;
101743 pFrame->apCsr = p->apCsr;
101744 pFrame->nCursor = p->nCursor;
101745 pFrame->aOp = p->aOp;
101746 pFrame->nOp = p->nOp;
101747 pFrame->token = pProgram->token;
101749 pFrame->iFrameMagic = SQLITE_FRAME_MAGIC;
101752 pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
101754 pMem->flags = MEM_Undefined;
101755 pMem->db = db;
101758 pFrame = (VdbeFrame*)pRt->z;
101759 assert( pRt->xDel==sqlite3VdbeFrameMemDel );
101760 assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
101761 || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
101762 assert( pProgram->nCsr==pFrame->nChildCsr );
101763 assert( (int)(pOp - aOp)==pFrame->pc );
101766 p->nFrame++;
101767 pFrame->pParent = p->pFrame;
101768 pFrame->lastRowid = db->lastRowid;
101769 pFrame->nChange = p->nChange;
101770 pFrame->nDbChange = p->db->nChange;
101771 assert( pFrame->pAuxData==0 );
101772 pFrame->pAuxData = p->pAuxData;
101773 p->pAuxData = 0;
101774 p->nChange = 0;
101775 p->pFrame = pFrame;
101776 p->aMem = aMem = VdbeFrameMem(pFrame);
101777 p->nMem = pFrame->nChildMem;
101778 p->nCursor = (u16)pFrame->nChildCsr;
101779 p->apCsr = (VdbeCursor **)&aMem[p->nMem];
101780 pFrame->aOnce = (u8*)&p->apCsr[pProgram->nCsr];
101781 memset(pFrame->aOnce, 0, (pProgram->nOp + 7)/8);
101782 p->aOp = aOp = pProgram->aOp;
101783 p->nOp = pProgram->nOp;
101789 for(i=0; i<p->nMem; i++){
101790 aMem[i].pScopyFrom = 0; /* Prevent false-positive AboutToChange() errs */
101795 pOp = &aOp[-1];
101801 ** This opcode is only ever present in sub-programs called via the
101815 pFrame = p->pFrame;
101816 pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
101828 ** If P1 is non-zero, the database constraint counter is incremented
101833 if( pOp->p1 ){
101834 db->nDeferredCons += pOp->p2;
101836 if( db->flags & SQLITE_DeferFKs ){
101837 db->nDeferredImmCons += pOp->p2;
101839 p->nFkConstraint += pOp->p2;
101848 ** This opcode tests if a foreign key constraint-counter is currently zero.
101852 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
101854 ** zero, the jump is taken if the statement constraint-counter is zero
101858 if( pOp->p1 ){
101859 VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
101860 if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
101862 VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
101863 if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
101875 ** within a sub-program). Set the value of register P1 to the maximum of
101878 ** This instruction throws an error if the memory cell is not initially
101879 ** an integer.
101883 if( p->pFrame ){
101884 for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
101885 pIn1 = &pFrame->aMem[pOp->p1];
101887 pIn1 = &aMem[pOp->p1];
101891 pIn2 = &aMem[pOp->p2];
101893 if( pIn1->u.i<pIn2->u.i){
101894 pIn1->u.i = pIn2->u.i;
101901 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
101903 ** Register P1 must contain an integer.
101911 pIn1 = &aMem[pOp->p1];
101912 assert( pIn1->flags&MEM_Int );
101913 VdbeBranchTaken( pIn1->u.i>0, 2);
101914 if( pIn1->u.i>0 ){
101915 pIn1->u.i -= pOp->p3;
101922 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
101935 ** and r[P2] is set to -1.
101941 pIn1 = &aMem[pOp->p1];
101942 pIn3 = &aMem[pOp->p3];
101944 assert( pIn1->flags & MEM_Int );
101945 assert( pIn3->flags & MEM_Int );
101946 x = pIn1->u.i;
101947 if( x<=0 || sqlite3AddInt64(&x, pIn3->u.i>0?pIn3->u.i:0) ){
101955 pOut->u.i = -1;
101957 pOut->u.i = x;
101963 ** Synopsis: if r[P1]!=0 then r[P1]--, goto P2
101965 ** Register P1 must contain an integer. If the content of register P1 is
101967 ** If it is non-zero (negative or positive) and then also jump to P2.
101971 pIn1 = &aMem[pOp->p1];
101972 assert( pIn1->flags&MEM_Int );
101973 VdbeBranchTaken(pIn1->u.i<0, 2);
101974 if( pIn1->u.i ){
101975 if( pIn1->u.i>0 ) pIn1->u.i--;
101982 ** Synopsis: if (--r[P1])==0 goto P2
101984 ** Register P1 must hold an integer. Decrement the value in P1
101988 pIn1 = &aMem[pOp->p1];
101989 assert( pIn1->flags&MEM_Int );
101990 if( pIn1->u.i>SMALLEST_INT64 ) pIn1->u.i--;
101991 VdbeBranchTaken(pIn1->u.i==0, 2);
101992 if( pIn1->u.i==0 ) goto jump_to_p2;
102000 ** Execute the xStep function for an aggregate.
102011 ** Execute the xInverse function for an aggregate.
102022 ** Execute the xStep (if P1==0) or xInverse (if P1!=0) function for an
102031 ** the FuncDef stored in P4 is converted into an sqlite3_context and
102042 assert( pOp->p4type==P4_FUNCDEF );
102043 n = pOp->p5;
102044 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
102045 assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
102046 assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
102048 /* Allocate space for (a) the context object and (n-1) extra pointers
102051 ** cell is 8-byte aligned, even on platforms where a pointer is 32-bits.
102058 pCtx->pOut = (Mem*)((u8*)pCtx + nAlloc);
102059 assert( EIGHT_BYTE_ALIGNMENT(pCtx->pOut) );
102061 sqlite3VdbeMemInit(pCtx->pOut, db, MEM_Null);
102062 pCtx->pMem = 0;
102063 pCtx->pFunc = pOp->p4.pFunc;
102064 pCtx->iOp = (int)(pOp - aOp);
102065 pCtx->pVdbe = p;
102066 pCtx->skipFlag = 0;
102067 pCtx->isError = 0;
102068 pCtx->enc = encoding;
102069 pCtx->argc = n;
102070 pOp->p4type = P4_FUNCCTX;
102071 pOp->p4.pCtx = pCtx;
102074 assert( pOp->p1==(pOp->opcode==OP_AggInverse) );
102076 pOp->opcode = OP_AggStep1;
102085 assert( pOp->p4type==P4_FUNCCTX );
102086 pCtx = pOp->p4.pCtx;
102087 pMem = &aMem[pOp->p3];
102090 if( pOp->p1 ){
102091 /* This is an OP_AggInverse call. Verify that xStep has always
102093 assert( pMem->uTemp==0x1122e0e3 );
102095 /* This is an OP_AggStep call. Mark it as such. */
102096 pMem->uTemp = 0x1122e0e3;
102104 if( pCtx->pMem != pMem ){
102105 pCtx->pMem = pMem;
102106 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
102110 for(i=0; i<pCtx->argc; i++){
102111 assert( memIsValid(pCtx->argv[i]) );
102112 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
102116 pMem->n++;
102117 assert( pCtx->pOut->flags==MEM_Null );
102118 assert( pCtx->isError==0 );
102119 assert( pCtx->skipFlag==0 );
102121 if( pOp->p1 ){
102122 (pCtx->pFunc->xInverse)(pCtx,pCtx->argc,pCtx->argv);
102125 (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
102127 if( pCtx->isError ){
102128 if( pCtx->isError>0 ){
102129 sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
102130 rc = pCtx->isError;
102132 if( pCtx->skipFlag ){
102133 assert( pOp[-1].opcode==OP_CollSeq );
102134 i = pOp[-1].p1;
102136 pCtx->skipFlag = 0;
102138 sqlite3VdbeMemRelease(pCtx->pOut);
102139 pCtx->pOut->flags = MEM_Null;
102140 pCtx->isError = 0;
102143 assert( pCtx->pOut->flags==MEM_Null );
102144 assert( pCtx->skipFlag==0 );
102151 ** P1 is the memory location that is the accumulator for an aggregate
102153 ** for an aggregate and store the result in P1.
102177 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
102178 assert( pOp->p3==0 || pOp->opcode==OP_AggValue );
102179 pMem = &aMem[pOp->p1];
102180 assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
102182 if( pOp->p3 ){
102183 memAboutToChange(p, &aMem[pOp->p3]);
102184 rc = sqlite3VdbeMemAggValue(pMem, &aMem[pOp->p3], pOp->p4.pFunc);
102185 pMem = &aMem[pOp->p3];
102189 rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
102198 REGISTER_TRACE((int)(pMem-aMem), pMem);
102205 ** Checkpoint database P1. This is a no-op if P1 is not currently in
102211 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
102212 ** mem[P3+2] are initialized to -1.
102219 assert( p->readOnly==0 );
102221 aRes[1] = aRes[2] = -1;
102222 assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
102223 || pOp->p2==SQLITE_CHECKPOINT_FULL
102224 || pOp->p2==SQLITE_CHECKPOINT_RESTART
102225 || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
102227 rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
102233 for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
102250 ** Write a string containing the final journal-mode to register P2.
102262 eNew = pOp->p3;
102271 assert( pOp->p1>=0 && pOp->p1<db->nDb );
102272 assert( p->readOnly==0 );
102274 pBt = db->aDb[pOp->p1].pBt;
102289 || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
102297 if( !db->autoCommit || db->nVdbeRead>1 ){
102308 ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
102309 ** file. An EXCLUSIVE lock may still be held on the database file
102318 ** as an intermediate */
102336 pOut->flags = MEM_Str|MEM_Static|MEM_Term;
102337 pOut->z = (char *)sqlite3JournalModename(eNew);
102338 pOut->n = sqlite3Strlen30(pOut->z);
102339 pOut->enc = SQLITE_UTF8;
102350 ** for an attached database. The "temp" database may not be vacuumed.
102357 assert( p->readOnly==0 );
102358 rc = sqlite3RunVacuum(&p->zErrMsg, db, pOp->p1,
102359 pOp->p2 ? &aMem[pOp->p2] : 0);
102375 assert( pOp->p1>=0 && pOp->p1<db->nDb );
102376 assert( DbMaskTest(p->btreeMask, pOp->p1) );
102377 assert( p->readOnly==0 );
102378 pBt = db->aDb[pOp->p1].pBt;
102392 ** Cause precompiled statements to expire. When an expired statement
102397 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
102407 assert( pOp->p2==0 || pOp->p2==1 );
102408 if( !pOp->p1 ){
102409 sqlite3ExpirePreparedStatements(db, pOp->p2);
102411 p->expired = pOp->p2+1;
102419 ** written by an other cursor.
102423 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
102424 pC = p->apCsr[pOp->p1];
102426 assert( pC->eCurType==CURTYPE_BTREE );
102427 sqlite3BtreeCursorPin(pC->uc.pCursor);
102438 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
102439 pC = p->apCsr[pOp->p1];
102441 assert( pC->eCurType==CURTYPE_BTREE );
102442 sqlite3BtreeCursorUnpin(pC->uc.pCursor);
102451 ** the shared-cache feature is enabled.
102457 ** P2 contains the root-page of the table to lock.
102460 ** used to generate an error message if the lock cannot be obtained.
102463 u8 isWriteLock = (u8)pOp->p3;
102464 if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommit) ){
102465 int p1 = pOp->p1;
102466 assert( p1>=0 && p1<db->nDb );
102467 assert( DbMaskTest(p->btreeMask, p1) );
102469 rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
102472 const char *z = pOp->p4.z;
102485 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
102494 pVTab = pOp->p4.pVtab;
102496 if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
102516 assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
102517 assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
102518 rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
102521 assert( zTab || db->mallocFailed );
102523 rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
102538 db->nVDestroy++;
102539 rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
102540 db->nVDestroy--;
102541 assert( p->errorAction==OE_Abort && p->usesStmtJournal );
102550 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
102560 assert( p->bIsReader );
102563 pVtab = pOp->p4.pVtab->pVtab;
102564 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
102568 pModule = pVtab->pModule;
102569 rc = pModule->xOpen(pVtab, &pVCur);
102574 pVCur->pVtab = pVtab;
102577 pCur = allocateCursor(p, pOp->p1, 0, CURTYPE_VTAB);
102579 pCur->uc.pVCur = pVCur;
102580 pVtab->nRef++;
102582 assert( db->mallocFailed );
102583 pModule->xClose(pVCur);
102596 ** an error is reported back, the table name is prepended to the error
102606 pOut = &aMem[pOp->p2];
102608 assert( pOp->p4type==P4_TABLEREF );
102609 pTab = pOp->p4.pTab;
102611 assert( pTab->nTabRef>0 );
102613 if( pTab->u.vtab.p==0 ) break;
102614 pVtab = pTab->u.vtab.p->pVtab;
102616 pModule = pVtab->pModule;
102618 assert( pModule->iVersion>=4 );
102619 assert( pModule->xIntegrity!=0 );
102620 sqlite3VtabLock(pTab->u.vtab.p);
102621 assert( pOp->p1>=0 && pOp->p1<db->nDb );
102622 rc = pModule->xIntegrity(pVtab, db->aDb[pOp->p1].zDbSName, pTab->zName,
102623 pOp->p3, &zErr);
102624 sqlite3VtabUnlock(pTab->u.vtab.p);
102630 sqlite3VdbeMemSetStr(pOut, zErr, -1, SQLITE_UTF8, sqlite3_free);
102651 pC = p->apCsr[pOp->p1];
102654 pRhs->pCsr = pC->uc.pCursor;
102655 pRhs->pOut = &aMem[pOp->p3];
102657 pOut->flags = MEM_Null;
102668 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
102697 pQuery = &aMem[pOp->p3];
102699 pCur = p->apCsr[pOp->p1];
102701 REGISTER_TRACE(pOp->p3, pQuery);
102703 assert( pCur->eCurType==CURTYPE_VTAB );
102704 pVCur = pCur->uc.pVCur;
102705 pVtab = pVCur->pVtab;
102706 pModule = pVtab->pModule;
102709 assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
102710 nArg = (int)pArgc->u.i;
102711 iQuery = (int)pQuery->u.i;
102714 apArg = p->apArg;
102715 assert( nArg<=p->napArg );
102719 rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
102722 res = pModule->xEof(pVCur);
102723 pCur->nullRow = 0;
102734 ** Store in register P3 the value of the P2-th column of
102735 ** the current row of the virtual-table of cursor P1.
102738 ** an unchanging column during an UPDATE operation, then the P5
102752 VdbeCursor *pCur = p->apCsr[pOp->p1];
102754 assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
102755 pDest = &aMem[pOp->p3];
102757 if( pCur->nullRow ){
102761 assert( pCur->eCurType==CURTYPE_VTAB );
102762 pVtab = pCur->uc.pVCur->pVtab;
102763 pModule = pVtab->pModule;
102764 assert( pModule->xColumn );
102771 assert( pOp->p5==OPFLAG_NOCHNG || pOp->p5==0 );
102772 if( pOp->p5 & OPFLAG_NOCHNG ){
102774 pDest->flags = MEM_Null|MEM_Zero;
102775 pDest->u.nZero = 0;
102779 rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
102786 REGISTER_TRACE(pOp->p3, pDest);
102807 pCur = p->apCsr[pOp->p1];
102809 assert( pCur->eCurType==CURTYPE_VTAB );
102810 if( pCur->nullRow ){
102813 pVtab = pCur->uc.pVCur->pVtab;
102814 pModule = pVtab->pModule;
102815 assert( pModule->xNext );
102818 ** underlying implementation to return an error if one occurs during
102819 ** xNext(). Instead, if an error occurs, true is returned (indicating that
102823 rc = pModule->xNext(pCur->uc.pVCur);
102826 res = pModule->xEof(pCur->uc.pVCur);
102839 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
102848 isLegacy = (db->flags & SQLITE_LegacyAlter);
102849 db->flags |= SQLITE_LegacyAlter;
102850 pVtab = pOp->p4.pVtab->pVtab;
102851 pName = &aMem[pOp->p1];
102852 assert( pVtab->pModule->xRename );
102854 assert( p->readOnly==0 );
102855 REGISTER_TRACE(pOp->p1, pName);
102856 assert( pName->flags & MEM_Str );
102857 testcase( pName->enc==SQLITE_UTF8 );
102858 testcase( pName->enc==SQLITE_UTF16BE );
102859 testcase( pName->enc==SQLITE_UTF16LE );
102862 rc = pVtab->pModule->xRename(pVtab, pName->z);
102863 if( isLegacy==0 ) db->flags &= ~(u64)SQLITE_LegacyAlter;
102865 p->expired = 0;
102875 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
102878 ** invocation. The value in register (P3+P2-1) corresponds to the
102881 ** The xUpdate method will do a DELETE or an INSERT or both.
102897 ** apply in the case of a constraint failure on an insert or update.
102908 assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
102909 || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
102911 assert( p->readOnly==0 );
102912 if( db->mallocFailed ) goto no_mem;
102914 pVtab = pOp->p4.pVtab->pVtab;
102915 if( pVtab==0 || NEVER(pVtab->pModule==0) ){
102919 pModule = pVtab->pModule;
102920 nArg = pOp->p2;
102921 assert( pOp->p4type==P4_VTAB );
102922 if( ALWAYS(pModule->xUpdate) ){
102923 u8 vtabOnConflict = db->vtabOnConflict;
102924 apArg = p->apArg;
102925 pX = &aMem[pOp->p3];
102926 assert( nArg<=p->napArg );
102933 db->vtabOnConflict = pOp->p5;
102934 rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
102935 db->vtabOnConflict = vtabOnConflict;
102937 if( rc==SQLITE_OK && pOp->p1 ){
102938 assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
102939 db->lastRowid = rowid;
102941 if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
102942 if( pOp->p5==OE_Ignore ){
102945 p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
102948 p->nChange++;
102963 pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
102983 pBt = db->aDb[pOp->p1].pBt;
102985 if( pOp->p3 ){
102987 if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
102989 pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
102997 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
103004 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
103016 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
103023 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
103032 ** purely non-deterministic. Some built-in date/time functions can be
103033 ** either deterministic of non-deterministic, depending on their arguments.
103034 ** When those function are used in a non-deterministic way, they will check
103036 ** if they were, they throw an error.
103045 assert( pOp->p4type==P4_FUNCCTX );
103046 pCtx = pOp->p4.pCtx;
103052 pOut = &aMem[pOp->p3];
103053 if( pCtx->pOut != pOut ){
103054 pCtx->pVdbe = p;
103055 pCtx->pOut = pOut;
103056 pCtx->enc = encoding;
103057 for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
103059 assert( pCtx->pVdbe==p );
103063 for(i=0; i<pCtx->argc; i++){
103064 assert( memIsValid(pCtx->argv[i]) );
103065 REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
103069 assert( pCtx->isError==0 );
103070 (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
103072 /* If the function returned an error, throw an exception */
103073 if( pCtx->isError ){
103074 if( pCtx->isError>0 ){
103076 rc = pCtx->isError;
103078 sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
103079 pCtx->isError = 0;
103083 assert( (pOut->flags&MEM_Str)==0
103084 || pOut->enc==encoding
103085 || db->mallocFailed );
103088 REGISTER_TRACE(pOp->p3, pOut);
103099 pIn1 = &aMem[pOp->p1];
103100 pIn1->flags &= ~MEM_Subtype;
103111 pIn1 = &aMem[pOp->p1];
103112 pOut = &aMem[pOp->p2];
103113 if( pIn1->flags & MEM_Subtype ){
103114 sqlite3VdbeMemSetInt64(pOut, pIn1->eSubtype);
103128 pIn1 = &aMem[pOp->p1];
103129 pOut = &aMem[pOp->p2];
103130 if( pIn1->flags & MEM_Null ){
103131 pOut->flags &= ~MEM_Subtype;
103133 assert( pIn1->flags & MEM_Int );
103134 pOut->flags |= MEM_Subtype;
103135 pOut->eSubtype = (u8)(pIn1->u.i & 0xff);
103149 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
103150 pIn1 = &aMem[pOp->p1];
103151 assert( pIn1->flags & MEM_Blob );
103152 assert( pIn1->n>0 );
103155 if( db->flags&SQLITE_VdbeTrace ){
103157 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
103160 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
103163 h %= (pIn1->n*8);
103164 pIn1->z[h/8] |= 1<<(h&7);
103179 ** answer. However, an incorrect answer may well arise from a
103180 ** false positive - if the jump is taken when it should fall through.
103185 assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
103186 pIn1 = &aMem[pOp->p1];
103187 assert( (pIn1->flags & MEM_Blob)!=0 );
103188 assert( pIn1->n >= 1 );
103191 if( db->flags&SQLITE_VdbeTrace ){
103193 for(ii=pOp->p3; ii<pOp->p3+pOp->p4.i; ii++){
103196 printf("hash: %llu modulo %d -> %u\n", h, pIn1->n, (int)(h%pIn1->n));
103199 h %= (pIn1->n*8);
103200 if( (pIn1->z[h/8] & (1<<(h&7)))==0 ){
103202 p->aCounter[SQLITE_STMTSTATUS_FILTER_HIT]++;
103205 p->aCounter[SQLITE_STMTSTATUS_FILTER_MISS]++;
103225 ** the UTF-8 string contained in P4 is emitted on the trace callback.
103233 ** If P3 is not zero, then it is an address to jump to if an SQLITE_CORRUPT
103243 /* If the P4 argument is not NULL, then it must be an SQL comment string.
103244 ** The "--" string is broken up to prevent false-positives with srcck1.c.
103247 ** EVIDENCE-OF: R-50676-09860 The callback can compute the same text that
103249 ** using the X argument when X begins with "--" and invoking
103252 assert( pOp->p4.z==0 || strncmp(pOp->p4.z, "-" "- ", 3)==0 );
103255 assert( pOp==p->aOp || pOp->opcode==OP_Trace );
103258 if( (db->mTrace & (SQLITE_TRACE_STMT|SQLITE_TRACE_LEGACY))!=0
103259 && p->minWriteFileFormat!=254 /* tag-20220401a */
103260 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
103263 if( db->mTrace & SQLITE_TRACE_LEGACY ){
103265 db->trace.xLegacy(db->pTraceArg, z);
103269 if( db->nVdbeExec>1 ){
103270 char *z = sqlite3MPrintf(db, "-- %s", zTrace);
103271 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, z);
103274 (void)db->trace.xV2(SQLITE_TRACE_STMT, db->pTraceArg, p, zTrace);
103278 zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
103281 for(j=0; j<db->nDb; j++){
103282 if( DbMaskTest(p->btreeMask, j)==0 ) continue;
103283 sqlite3_file_control(db, db->aDb[j].zDbSName, SQLITE_FCNTL_TRACE, zTrace);
103288 if( (db->flags & SQLITE_SqlTrace)!=0
103289 && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
103291 sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
103295 assert( pOp->p2>0 );
103296 if( pOp->p1>=sqlite3GlobalConfig.iOnceResetThreshold ){
103297 if( pOp->opcode==OP_Trace ) break;
103298 for(i=1; i<p->nOp; i++){
103299 if( p->aOp[i].opcode==OP_Once ) p->aOp[i].p1 = 0;
103301 pOp->p1 = 0;
103303 pOp->p1++;
103304 p->aCounter[SQLITE_STMTSTATUS_RUN]++;
103314 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
103319 assert( pOp->p1>=0 && pOp->p1<p->nCursor );
103320 assert( pOp->p4type==P4_EXPR );
103321 pC = p->apCsr[pOp->p1];
103323 assert( pC->eCurType==CURTYPE_BTREE );
103324 sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
103325 pOp->p4.pExpr, aMem);
103334 ** Verify that an Abort can happen. Assert if an Abort at this point
103338 ** An Abort is safe if either there have been no writes, or if there is
103339 ** an active statement journal.
103361 ** generate an assertion fault in sqlite3VdbeMemAboutToChange().
103365 ** register (before it is reinitialized) will generate an assertion fault.
103376 ** to computing an answer.
103382 assert( pOp->p1>0 );
103383 assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
103384 pMem = &aMem[pOp->p1];
103385 constMask = pOp->p3;
103386 for(i=0; i<pOp->p2; i++, pMem++){
103388 pMem->pScopyFrom = 0;
103389 if( i<32 && pOp->p5 ) MemSetTypeFlag(pMem, MEM_Undefined);
103406 ** The P4 value is human-readable text that describes the query plan
103411 ** then this element is a top-level element.
103423 assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
103430 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
103452 assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
103455 if( db->flags & SQLITE_VdbeTrace ){
103456 u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
103459 registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
103462 registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
103476 ** an error of some kind.
103479 if( db->mallocFailed ){
103486 if( db->flags & SQLITE_VdbeTrace ){
103487 const char *zTrace = p->zSql;
103494 printf("ABORT-due-to-error (rc=%d): %s\n", rc, zTrace);
103497 if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
103500 p->rc = rc;
103504 (int)(pOp - aOp), p->zErrMsg, p->zSql);
103505 if( p->eVdbeState==VDBE_RUN_STATE ) sqlite3VdbeHalt(p);
103507 if( rc==SQLITE_CORRUPT && db->autoCommit==0 ){
103508 db->flags |= SQLITE_CorruptRdOnly;
103512 sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
103532 while( nVmStep>=nProgressLimit && db->xProgress!=0 ){
103533 nProgressLimit += db->nProgressOps;
103534 if( db->xProgress(db->pProgressArg) ){
103541 p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
103542 if( DbMaskNonZero(p->lockMask) ){
103546 || sqlite3_strlike("DELETE%",p->zSql,0)!=0
103570 assert( AtomicLoad(&db->u1.isInterrupted) );
103616 ** the b-tree cursor associated with blob handle p to point to row iRow.
103620 ** If an error occurs, or if the specified row does not exist or does not
103622 ** blob handle was opened, then an error code is returned and *pzErr may
103623 ** be set to point to a buffer containing an error message. It is the
103627 ** If an error does occur, then the b-tree cursor is closed. All subsequent
103634 Vdbe *v = (Vdbe *)p->pStmt;
103639 sqlite3VdbeMemSetInt64(&v->aMem[1], iRow);
103643 ** have been down with an extra OP_Goto, but simply setting the program
103645 if( v->pc>4 ){
103646 v->pc = 4;
103647 assert( v->aOp[v->pc].opcode==OP_NotExists );
103650 rc = sqlite3_step(p->pStmt);
103653 VdbeCursor *pC = v->apCsr[0];
103656 assert( pC->eCurType==CURTYPE_BTREE );
103657 type = pC->nHdrParsed>p->iCol ? pC->aType[p->iCol] : 0;
103658 testcase( pC->nHdrParsed==p->iCol );
103659 testcase( pC->nHdrParsed==p->iCol+1 );
103661 zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
103665 sqlite3_finalize(p->pStmt);
103666 p->pStmt = 0;
103668 p->iOffset = pC->aType[p->iCol + pC->nField];
103669 p->nByte = sqlite3VdbeSerialTypeLen(type);
103670 p->pCsr = pC->uc.pCursor;
103671 sqlite3BtreeIncrblobCursor(p->pCsr);
103677 }else if( p->pStmt ){
103678 rc = sqlite3_finalize(p->pStmt);
103679 p->pStmt = 0;
103681 zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
103684 zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
103704 int wrFlag, /* True -> read/write access, false -> read-only */
103708 int iCol; /* Index of zColumn in row-record */
103729 sqlite3_mutex_enter(db->mutex);
103748 if( pTab && (pTab->tabFlags&TF_HasGenerated)!=0 ){
103760 || ((iDb = sqlite3SchemaToIndex(db, pTab->pSchema))==1 &&
103772 pBlob->pTab = pTab;
103773 pBlob->zDb = db->aDb[iDb].zDbSName;
103792 if( db->flags&SQLITE_ForeignKeys ){
103793 /* Check that the column is not part of an FK child key definition. It
103799 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
103801 for(j=0; j<pFKey->nCol; j++){
103802 if( pFKey->aCol[j].iFrom==iCol ){
103809 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
103811 for(j=0; j<pIdx->nKeyCol; j++){
103813 if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
103827 pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(&sParse);
103828 assert( pBlob->pStmt || db->mallocFailed );
103829 if( pBlob->pStmt ){
103833 ** of writing code to use the b-tree layer directly is that the
103837 ** After seeking the cursor, the vdbe executes an OP_ResultRow.
103838 ** Code external to the Vdbe then "borrows" the b-tree cursor and
103843 ** which closes the b-tree cursor and (possibly) commits the
103856 Vdbe *v = (Vdbe *)pBlob->pStmt;
103860 pTab->pSchema->schema_cookie,
103861 pTab->pSchema->iGeneration);
103863 assert( sqlite3VdbeCurrentAddr(v)==2 || db->mallocFailed );
103869 if( db->mallocFailed==0 ){
103876 aOp[0].p2 = pTab->tnum;
103878 sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
103880 if( db->mallocFailed==0 ){
103884 ** parameter of the other to pTab->tnum. */
103886 aOp[1].p2 = pTab->tnum;
103891 ** does. An OP_Column to retrieve this imaginary column will
103892 ** always return an SQL NULL. This is useful because it means
103897 aOp[1].p4.i = pTab->nCol+1;
103898 aOp[3].p2 = pTab->nCol;
103907 pBlob->iCol = iCol;
103908 pBlob->db = db;
103910 if( db->mallocFailed ){
103919 if( rc==SQLITE_OK && db->mallocFailed==0 ){
103922 if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
103929 sqlite3_mutex_leave(db->mutex);
103943 sqlite3_stmt *pStmt = p->pStmt;
103944 db = p->db;
103945 sqlite3_mutex_enter(db->mutex);
103947 sqlite3_mutex_leave(db->mutex);
103971 db = p->db;
103972 sqlite3_mutex_enter(db->mutex);
103973 v = (Vdbe*)p->pStmt;
103975 if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
103979 /* If there is no statement handle, then the blob-handle has
103985 ** returned, clean-up the statement handle.
103987 assert( db == v->db );
103988 sqlite3BtreeEnterCursor(p->pCsr);
103991 if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
103992 /* If a pre-update hook is registered and this is a write cursor,
103995 ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
103996 ** operation should really be an SQLITE_UPDATE. This is probably
103998 ** are not easily obtainable. And for the sessions module, an
104000 ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
104002 ** using the incremental-blob API, this works. For the sessions module
104006 iKey = sqlite3BtreeIntegerKey(p->pCsr);
104007 assert( v->apCsr[0]!=0 );
104008 assert( v->apCsr[0]->eCurType==CURTYPE_BTREE );
104010 v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1, p->iCol
104015 rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
104016 sqlite3BtreeLeaveCursor(p->pCsr);
104019 p->pStmt = 0;
104021 v->rc = rc;
104026 sqlite3_mutex_leave(db->mutex);
104052 return (p && p->pStmt) ? p->nByte : 0;
104056 ** Move an existing blob handle to point to a different row of the same
104059 ** If an error occurs, or if the specified row does not exist or does not
104060 ** contain a blob or text value, then an error code is returned and the
104071 db = p->db;
104072 sqlite3_mutex_enter(db->mutex);
104074 if( p->pStmt==0 ){
104075 /* If there is no statement handle, then the blob-handle has
104081 ((Vdbe*)p->pStmt)->rc = SQLITE_OK;
104091 assert( rc==SQLITE_OK || p->pStmt==0 );
104092 sqlite3_mutex_leave(db->mutex);
104101 ** 2011-07-09
104116 ** The VdbeSorter object implements a multi-threaded external merge sort
104120 ** Here is the (internal, non-API) interface between this module and the
104130 ** the complete record for an index entry
104173 ** an in-memory merge sort. In this case, no temporary files are required
104180 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
104181 ** of PMAs may be created by merging existing PMAs together - for example
104182 ** merging two or more level-0 PMAs together creates a level-1 PMA.
104186 ** page-cache of the main database. Specifically, the threshold is set to
104190 ** If the sorter is running in single-threaded mode, then all PMAs generated
104192 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
104199 ** The sorter is running in multi-threaded mode if (a) the library was built
104200 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
104209 ** sorter is running in single-threaded mode, then these PMAs are merged
104214 ** Or, if running in multi-threaded mode, then a background thread is
104224 ** Rewind() is called, then a hierarchy of incremental-merges is used.
104230 ** If running in multi-threaded mode and there are more than
104243 ** characteristics of the sorter in multi-threaded mode.
104250 ** Hard-coded maximum amount of data to accumulate in memory before flushing
104263 typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
104265 typedef struct SorterList SorterList; /* In-memory list of records */
104278 ** An in-memory list of objects to be sorted.
104287 u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
104298 ** merged. An aReadr[] object either points to a valid key or else is at EOF.
104310 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
104324 ** aReadr[0] -> Banana
104325 ** aReadr[1] -> Feijoa
104326 ** aReadr[2] -> Elderberry
104327 ** aReadr[3] -> Currant
104328 ** aReadr[4] -> Grapefruit
104329 ** aReadr[5] -> Apple
104330 ** aReadr[6] -> Durian
104331 ** aReadr[7] -> EOF
104340 ** aReadr[5] -> Eggplant
104345 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
104368 ** single-threaded operation, there is exactly one instance of this object
104369 ** and for multi-threaded operation there are two or more instances.
104380 ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
104381 ** attempt to select a SortSubtask for which there is not already an
104398 VdbeSorter *pSorter; /* Sorter that owns this sub-task */
104402 SorterFile file; /* Temp file for level-0 PMAs */
104426 SorterList list; /* List of in-memory records */
104444 ** An instance of the following object is used to read records out of a
104467 ** Normally, a PmaReader object iterates through an existing PMA stored
104469 ** an object of the following type, it may be used to iterate/merge through
104472 ** There are two types of IncrMerger object - single (bUseThread==0) and
104473 ** multi-threaded (bUseThread==1).
104475 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
104490 ** A single-threaded IncrMerger does not open any temporary files of its
104492 ** at offset iStartOff of file pTask->file2. And instead of using a
104494 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
104509 ** An instance of this object is used for writing a PMA.
104511 ** The PMA is written one record at a time. Each record is of an arbitrary
104512 ** size. But I/O is more efficient if it occurs in page-sized blocks where
104514 ** the PMA so that aligned, page-size blocks are written.
104517 int eFWErr; /* Non-zero if in an error state */
104531 ** by this module. If using a separate allocation for each in-memory record
104539 ** has finished passing records to the sorter, or when the in-memory buffer
104572 sqlite3_free(pReadr->aAlloc);
104573 sqlite3_free(pReadr->aBuffer);
104574 if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
104575 vdbeIncrFree(pReadr->pIncr);
104582 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
104596 if( p->aMap ){
104597 *ppOut = &p->aMap[p->iReadOff];
104598 p->iReadOff += nByte;
104602 assert( p->aBuffer );
104605 ** p->nBuffer bytes of data from the file into it. Or, if there are less
104606 ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
104607 iBuf = p->iReadOff % p->nBuffer;
104613 if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
104614 nRead = p->nBuffer;
104616 nRead = (int)(p->iEof - p->iReadOff);
104620 /* Readr data from the file. Return early if an error occurs. */
104621 rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
104625 nAvail = p->nBuffer - iBuf;
104628 /* The requested data is available in the in-memory buffer. In this
104631 *ppOut = &p->aBuffer[iBuf];
104632 p->iReadOff += nByte;
104634 /* The requested data is not all available in the in-memory buffer.
104635 ** In this case, allocate space at p->aAlloc[] to copy the requested
104636 ** range into. Then return a copy of pointer p->aAlloc to the caller. */
104639 /* Extend the p->aAlloc[] allocation if required. */
104640 if( p->nAlloc<nByte ){
104642 sqlite3_int64 nNew = MAX(128, 2*(sqlite3_int64)p->nAlloc);
104644 aNew = sqlite3Realloc(p->aAlloc, nNew);
104646 p->nAlloc = nNew;
104647 p->aAlloc = aNew;
104651 ** p->aAlloc[]. */
104652 memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
104653 p->iReadOff += nAvail;
104654 nRem = nByte - nAvail;
104656 /* The following loop copies up to p->nBuffer bytes per iteration into
104657 ** the p->aAlloc[] buffer. */
104664 if( nRem>p->nBuffer ) nCopy = p->nBuffer;
104667 assert( aNext!=p->aAlloc );
104669 memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
104670 nRem -= nCopy;
104673 *ppOut = p->aAlloc;
104686 if( p->aMap ){
104687 p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
104689 iBuf = p->iReadOff % p->nBuffer;
104690 if( iBuf && (p->nBuffer-iBuf)>=9 ){
104691 p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
104713 ** Or, if an error occurs, return an SQLite error code. The final value of
104718 if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
104719 sqlite3_file *pFd = pFile->pFd;
104720 if( pFd->pMethods->iVersion>=3 ){
104721 rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
104731 ** if successful, or an SQLite error code if an error occurs.
104741 assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
104744 if( pReadr->aMap ){
104745 sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
104746 pReadr->aMap = 0;
104748 pReadr->iReadOff = iOff;
104749 pReadr->iEof = pFile->iEof;
104750 pReadr->pFd = pFile->pFd;
104752 rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
104753 if( rc==SQLITE_OK && pReadr->aMap==0 ){
104754 int pgsz = pTask->pSorter->pgsz;
104755 int iBuf = pReadr->iReadOff % pgsz;
104756 if( pReadr->aBuffer==0 ){
104757 pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
104758 if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
104759 pReadr->nBuffer = pgsz;
104762 int nRead = pgsz - iBuf;
104763 if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
104764 nRead = (int)(pReadr->iEof - pReadr->iReadOff);
104767 pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
104778 ** no error occurs, or an SQLite error code if one does.
104785 if( pReadr->iReadOff>=pReadr->iEof ){
104786 IncrMerger *pIncr = pReadr->pIncr;
104790 if( rc==SQLITE_OK && pIncr->bEof==0 ){
104792 pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
104799 /* This is an EOF condition */
104810 pReadr->nKey = (int)nRec;
104811 rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
104820 ** starting at offset iStart and ending at offset iEof-1. This function
104836 assert( pFile->iEof>iStart );
104837 assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
104838 assert( pReadr->aBuffer==0 );
104839 assert( pReadr->aMap==0 );
104845 pReadr->iEof = pReadr->iReadOff + nByte;
104862 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
104866 UnpackedRecord *r2 = pTask->pUnpacked;
104868 sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
104876 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
104880 ** it is assumed that (pTask->pUnpacked) contains the unpacked version
104881 ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
104884 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
104889 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
104893 UnpackedRecord *r2 = pTask->pUnpacked;
104895 sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
104908 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
104923 res = memcmp(v1, v2, (MIN(n1, n2) - 13)/2);
104925 res = n1 - n2;
104929 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
104935 assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
104936 if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
104937 res = res * -1;
104946 ** the first field of each key is an INTEGER value.
104950 int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
104972 if( (res = v1[i] - v2[i])!=0 ){
104974 res = v1[0] & 0x80 ? -1 : +1;
104980 res = s1 - s2;
104985 res = -1;
104987 res = s1 - s2;
104992 if( *v1 & 0x80 ) res = -1;
104999 if( pTask->pSorter->pKeyInfo->nKeyField>1 ){
105004 }else if( pTask->pSorter->pKeyInfo->aSortFlags[0] ){
105005 assert( !(pTask->pSorter->pKeyInfo->aSortFlags[0]&KEYINFO_ORDER_BIGNULL) );
105006 res = res * -1;
105015 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nKeyField)
105018 ** is non-zero and the sorter is able to guarantee a stable sort, nField
105026 ** The sorter can guarantee a stable sort when running in single-threaded
105027 ** mode, but not in multi-threaded mode.
105029 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
105039 KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
105040 int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
105054 nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
105062 nWorker = SORTER_MAX_MERGE_COUNT-1;
105066 assert( pCsr->pKeyInfo );
105067 assert( !pCsr->isEphemeral );
105068 assert( pCsr->eCurType==CURTYPE_SORTER );
105069 assert( sizeof(KeyInfo) + UMXV(pCsr->pKeyInfo->nKeyField)*sizeof(CollSeq*)
105071 szKeyInfo = SZ_KEYINFO(pCsr->pKeyInfo->nKeyField);
105075 pCsr->uc.pSorter = pSorter;
105079 Btree *pBt = db->aDb[0].pBt;
105080 pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
105081 memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
105082 pKeyInfo->db = 0;
105084 pKeyInfo->nKeyField = nField;
105087 pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(pBt);
105089 pSorter->nTask = nWorker + 1;
105090 pSorter->iPrev = (u8)(nWorker - 1);
105091 pSorter->bUseThreads = (pSorter->nTask>1);
105092 pSorter->db = db;
105093 for(i=0; i<pSorter->nTask; i++){
105094 SortSubtask *pTask = &pSorter->aTask[i];
105095 pTask->pSorter = pSorter;
105101 pSorter->mnPmaSize = szPma * pgsz;
105103 mxCache = db->aDb[0].pSchema->cache_size;
105105 /* A negative cache-size value C indicates that the cache is abs(C)
105107 mxCache = mxCache * -1024;
105112 pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
105117 assert( pSorter->iMemory==0 );
105118 pSorter->nMemory = pgsz;
105119 pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
105120 if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
105124 if( pKeyInfo->nAllField<13
105125 && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
105126 && (pKeyInfo->aSortFlags[0] & KEYINFO_ORDER_BIGNULL)==0
105128 pSorter->typeMask = SORTER_TYPE_INTEGER | SORTER_TYPE_TEXT;
105143 pNext = p->u.pNext;
105153 sqlite3DbFree(db, pTask->pUnpacked);
105155 /* pTask->list.aMemory can only be non-zero if it was handed memory
105157 if( pTask->list.aMemory ){
105158 sqlite3_free(pTask->list.aMemory);
105162 assert( pTask->list.aMemory==0 );
105163 vdbeSorterRecordFree(0, pTask->list.pList);
105165 if( pTask->file.pFd ){
105166 sqlite3OsCloseFree(pTask->file.pFd);
105168 if( pTask->file2.pFd ){
105169 sqlite3OsCloseFree(pTask->file2.pFd);
105177 int iTask = (pTask - pTask->pSorter->aTask);
105178 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
105192 int iTask = (pTask - pTask->pSorter->aTask);
105193 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
105203 sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
105216 ** Join thread pTask->thread.
105220 if( pTask->pThread ){
105222 int bDone = pTask->bDone;
105226 (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
105229 assert( pTask->bDone==1 );
105230 pTask->bDone = 0;
105231 pTask->pThread = 0;
105244 assert( pTask->pThread==0 && pTask->bDone==0 );
105245 return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
105250 ** level-0 PMAs.
105259 ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
105262 ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
105263 for(i=pSorter->nTask-1; i>=0; i--){
105264 SortSubtask *pTask = &pSorter->aTask[i];
105294 pNew->nTree = N;
105295 pNew->pTask = 0;
105296 pNew->aReadr = (PmaReader*)&pNew[1];
105297 pNew->aTree = (int*)&pNew->aReadr[N];
105308 for(i=0; i<pMerger->nTree; i++){
105309 vdbePmaReaderClear(&pMerger->aReadr[i]);
105322 if( pIncr->bUseThread ){
105323 vdbeSorterJoinThread(pIncr->pTask);
105324 if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
105325 if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
105328 vdbeMergeEngineFree(pIncr->pMerger);
105339 assert( pSorter->bUseThreads || pSorter->pReader==0 );
105341 if( pSorter->pReader ){
105342 vdbePmaReaderClear(pSorter->pReader);
105343 sqlite3DbFree(db, pSorter->pReader);
105344 pSorter->pReader = 0;
105347 vdbeMergeEngineFree(pSorter->pMerger);
105348 pSorter->pMerger = 0;
105349 for(i=0; i<pSorter->nTask; i++){
105350 SortSubtask *pTask = &pSorter->aTask[i];
105352 pTask->pSorter = pSorter;
105354 if( pSorter->list.aMemory==0 ){
105355 vdbeSorterRecordFree(0, pSorter->list.pList);
105357 pSorter->list.pList = 0;
105358 pSorter->list.szPMA = 0;
105359 pSorter->bUsePMA = 0;
105360 pSorter->iMemory = 0;
105361 pSorter->mxKeysize = 0;
105362 sqlite3DbFree(db, pSorter->pUnpacked);
105363 pSorter->pUnpacked = 0;
105371 assert( pCsr->eCurType==CURTYPE_SORTER );
105372 pSorter = pCsr->uc.pSorter;
105375 sqlite3_free(pSorter->list.aMemory);
105377 pCsr->uc.pSorter = 0;
105383 ** The first argument is a file-handle open on a temporary file. The file
105392 if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
105406 ** Allocate space for a file-handle and open a temporary file. If successful,
105407 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
105408 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
105417 rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
105434 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
105438 if( pTask->pUnpacked==0 ){
105439 pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pTask->pSorter->pKeyInfo);
105440 if( pTask->pUnpacked==0 ) return SQLITE_NOMEM_BKPT;
105441 pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nKeyField;
105442 pTask->pUnpacked->errCode = 0;
105463 res = pTask->xCompare(
105464 pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
105469 pp = &p1->u.pNext;
105470 p1 = p1->u.pNext;
105477 pp = &p2->u.pNext;
105478 p2 = p2->u.pNext;
105494 if( p->typeMask==SORTER_TYPE_INTEGER ){
105496 }else if( p->typeMask==SORTER_TYPE_TEXT ){
105503 ** Sort the linked list of records headed at pTask->pList. Return
105504 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
105505 ** an error occurs.
105516 p = pList->pList;
105517 pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
105522 if( pList->aMemory ){
105523 if( (u8*)p==pList->aMemory ){
105526 assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
105527 pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
105530 pNext = p->u.pNext;
105533 p->u.pNext = 0;
105536 /* ,--Each aSlot[] holds twice as much as the previous. So we cannot use
105537 ** | up all 64 aSlots[] with only a 64-bit address space.
105551 pList->pList = p;
105553 assert( pTask->pUnpacked->errCode==SQLITE_OK
105554 || pTask->pUnpacked->errCode==SQLITE_NOMEM
105556 return pTask->pUnpacked->errCode;
105560 ** Initialize a PMA-writer object.
105569 p->aBuffer = (u8*)sqlite3Malloc(nBuf);
105570 if( !p->aBuffer ){
105571 p->eFWErr = SQLITE_NOMEM_BKPT;
105573 p->iBufEnd = p->iBufStart = (iStart % nBuf);
105574 p->iWriteOff = iStart - p->iBufStart;
105575 p->nBuffer = nBuf;
105576 p->pFd = pFd;
105582 ** if successful, or an SQLite error code if an error occurs.
105586 while( nRem>0 && p->eFWErr==0 ){
105588 if( nCopy>(p->nBuffer - p->iBufEnd) ){
105589 nCopy = p->nBuffer - p->iBufEnd;
105592 memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
105593 p->iBufEnd += nCopy;
105594 if( p->iBufEnd==p->nBuffer ){
105595 p->eFWErr = sqlite3OsWrite(p->pFd,
105596 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
105597 p->iWriteOff + p->iBufStart
105599 p->iBufStart = p->iBufEnd = 0;
105600 p->iWriteOff += p->nBuffer;
105602 assert( p->iBufEnd<p->nBuffer );
105604 nRem -= nCopy;
105609 ** Flush any buffered data to disk and clean up the PMA-writer object.
105610 ** The results of using the PMA-writer after this call are undefined.
105612 ** required. Otherwise, return an SQLite error code.
105619 if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
105620 p->eFWErr = sqlite3OsWrite(p->pFd,
105621 &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
105622 p->iWriteOff + p->iBufStart
105625 *piEof = (p->iWriteOff + p->iBufEnd);
105626 sqlite3_free(p->aBuffer);
105627 rc = p->eFWErr;
105634 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
105644 ** Write the current contents of in-memory linked-list pList to a level-0
105645 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
105646 ** successful, or an SQLite error code otherwise.
105653 ** * One or more records packed end-to-end in order of ascending keys.
105658 sqlite3 *db = pTask->pSorter->db;
105663 /* Set iSz to the expected size of file pTask->file after writing the PMA.
105664 ** This is used by an assert() statement at the end of this function. */
105665 i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
105670 assert( pList->szPMA>0 );
105673 if( pTask->file.pFd==0 ){
105674 rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
105675 assert( rc!=SQLITE_OK || pTask->file.pFd );
105676 assert( pTask->file.iEof==0 );
105677 assert( pTask->nPMA==0 );
105682 vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
105694 vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
105695 pTask->file.iEof);
105696 pTask->nPMA++;
105697 vdbePmaWriteVarint(&writer, pList->szPMA);
105698 for(p=pList->pList; p; p=pNext){
105699 pNext = p->u.pNext;
105700 vdbePmaWriteVarint(&writer, p->nVal);
105701 vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
105702 if( pList->aMemory==0 ) sqlite3_free(p);
105704 pList->pList = p;
105705 rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
105709 assert( rc!=SQLITE_OK || pList->pList==0 );
105710 assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
105719 ** Return SQLITE_OK if successful or an error code if an error occurs.
105726 int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
105727 SortSubtask *pTask = pMerger->pTask;
105730 rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
105741 pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
105742 pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
105744 for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
105747 if( pReadr1->pFd==0 ){
105749 }else if( pReadr2->pFd==0 ){
105750 iRes = -1;
105752 iRes = pTask->xCompare(pTask, &bCached,
105753 pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
105759 ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
105764 ** was actually called above, then pTask->pUnpacked now contains
105773 pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
105774 pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
105777 if( pReadr1->pFd ) bCached = 0;
105778 pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
105779 pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
105782 *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
105785 return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
105790 ** The main routine for background threads that write level-0 PMAs.
105795 assert( pTask->bDone==0 );
105796 rc = vdbeSorterListToPMA(pTask, &pTask->list);
105797 pTask->bDone = 1;
105808 pSorter->bUsePMA = 1;
105809 return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
105814 int nWorker = (pSorter->nTask-1);
105818 pSorter->bUsePMA = 1;
105820 /* Select a sub-task to sort and flush the current list of in-memory
105821 ** records to disk. If the sorter is running in multi-threaded mode,
105822 ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
105823 ** the background thread from a sub-tasks previous turn is still running,
105824 ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
105825 ** fall back to using the final sub-task. The first (pSorter->nTask-1)
105826 ** sub-tasks are preferred as they use background threads - the final
105827 ** sub-task uses the main thread. */
105829 int iTest = (pSorter->iPrev + i + 1) % nWorker;
105830 pTask = &pSorter->aTask[iTest];
105831 if( pTask->bDone ){
105834 if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
105840 rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
105847 assert( pTask->pThread==0 && pTask->bDone==0 );
105848 assert( pTask->list.pList==0 );
105849 assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
105851 aMem = pTask->list.aMemory;
105853 pSorter->iPrev = (u8)(pTask - pSorter->aTask);
105854 pTask->list = pSorter->list;
105855 pSorter->list.pList = 0;
105856 pSorter->list.szPMA = 0;
105858 pSorter->list.aMemory = aMem;
105859 pSorter->nMemory = sqlite3MallocSize(aMem);
105860 }else if( pSorter->list.aMemory ){
105861 pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
105862 if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
105888 assert( pCsr->eCurType==CURTYPE_SORTER );
105889 pSorter = pCsr->uc.pSorter;
105890 getVarint32NR((const u8*)&pVal->z[1], t);
105892 pSorter->typeMask &= SORTER_TYPE_INTEGER;
105894 pSorter->typeMask &= SORTER_TYPE_TEXT;
105896 pSorter->typeMask = 0;
105904 ** If using the single large allocation mode (pSorter->aMemory!=0), then
105911 ** * The total memory allocated for the in-memory list is greater
105912 ** than (page-size * cache-size), or
105914 ** * The total memory allocated for the in-memory list is greater
105915 ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
105917 nReq = pVal->n + sizeof(SorterRecord);
105918 nPMA = pVal->n + sqlite3VarintLen(pVal->n);
105919 if( pSorter->mxPmaSize ){
105920 if( pSorter->list.aMemory ){
105921 bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
105924 (pSorter->list.szPMA > pSorter->mxPmaSize)
105925 || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
105930 pSorter->list.szPMA = 0;
105931 pSorter->iMemory = 0;
105932 assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
105936 pSorter->list.szPMA += nPMA;
105937 if( nPMA>pSorter->mxKeysize ){
105938 pSorter->mxKeysize = nPMA;
105941 if( pSorter->list.aMemory ){
105942 int nMin = pSorter->iMemory + nReq;
105944 if( nMin>pSorter->nMemory ){
105946 sqlite3_int64 nNew = 2 * (sqlite3_int64)pSorter->nMemory;
105947 int iListOff = -1;
105948 if( pSorter->list.pList ){
105949 iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
105952 if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
105954 aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
105957 pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
105959 pSorter->list.aMemory = aNew;
105960 pSorter->nMemory = nNew;
105963 pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
105964 pSorter->iMemory += ROUND8(nReq);
105965 if( pSorter->list.pList ){
105966 pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
105973 pNew->u.pNext = pSorter->list.pList;
105976 memcpy(SRVAL(pNew), pVal->z, pVal->n);
105977 pNew->nVal = pVal->n;
105978 pSorter->list.pList = pNew;
105984 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
105986 ** except that the number-of-bytes varint is omitted from the start.
105991 i64 iStart = pIncr->iStartOff;
105992 SorterFile *pOut = &pIncr->aFile[1];
105993 SortSubtask *pTask = pIncr->pTask;
105994 MergeEngine *pMerger = pIncr->pMerger;
105996 assert( pIncr->bEof==0 );
106000 vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
106003 PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
106004 int nKey = pReader->nKey;
106009 if( pReader->pFd==0 ) break;
106010 if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
106014 vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
106015 assert( pIncr->pMerger->pTask==pTask );
106016 rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
106019 rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
106028 ** multi-threaded IncrMerger objects.
106033 pIncr->pTask->bDone = 1;
106042 assert( pIncr->bUseThread );
106043 return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
106053 ** For single-threaded objects, this is accomplished by literally reading
106054 ** keys from pIncr->pMerger and repopulating aFile[0].
106056 ** For multi-threaded objects, all that is required is to wait until the
106062 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
106068 if( pIncr->bUseThread ){
106069 rc = vdbeSorterJoinThread(pIncr->pTask);
106072 SorterFile f0 = pIncr->aFile[0];
106073 pIncr->aFile[0] = pIncr->aFile[1];
106074 pIncr->aFile[1] = f0;
106078 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
106079 pIncr->bEof = 1;
106088 pIncr->aFile[0] = pIncr->aFile[1];
106089 if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
106090 pIncr->bEof = 1;
106100 ** If an OOM condition is encountered, return NULL. In this case free the
106112 pIncr->pMerger = pMerger;
106113 pIncr->pTask = pTask;
106114 pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
106115 pTask->file2.iEof += pIncr->mxSz;
106126 ** Set the "use-threads" flag on object pIncr.
106129 pIncr->bUseThread = 1;
106130 pIncr->pTask->file2.iEof -= pIncr->mxSz;
106137 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
106143 int iOut /* Store the result in pMerger->aTree[iOut] */
106151 assert( iOut<pMerger->nTree && iOut>0 );
106153 if( iOut>=(pMerger->nTree/2) ){
106154 i1 = (iOut - pMerger->nTree/2) * 2;
106157 i1 = pMerger->aTree[iOut*2];
106158 i2 = pMerger->aTree[iOut*2+1];
106161 p1 = &pMerger->aReadr[i1];
106162 p2 = &pMerger->aReadr[i2];
106164 if( p1->pFd==0 ){
106166 }else if( p2->pFd==0 ){
106169 SortSubtask *pTask = pMerger->pTask;
106172 assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
106173 res = pTask->xCompare(
106174 pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
106183 pMerger->aTree[iOut] = iRes;
106190 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
106221 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
106236 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
106240 assert( pMerger->pTask==0 );
106241 pMerger->pTask = pTask;
106243 nTree = pMerger->nTree;
106248 ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
106251 ** on this PmaReader before any of the multi-threaded PmaReaders takes
106252 ** better advantage of multi-processor hardware. */
106253 rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
106255 rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
106260 for(i=pMerger->nTree-1; i>0; i--){
106263 return pTask->pUnpacked->errCode;
106267 ** The PmaReader passed as the first argument is guaranteed to be an
106268 ** incremental-reader (pReadr->pIncr!=0). This function serves to open
106270 ** object at (pReadr->pIncr).
106273 ** in the sub-tree headed by pReadr are also initialized. Data is then
106278 ** to be a multi-threaded PmaReader and this function is being called in a
106279 ** background thread. In this case all PmaReaders in the sub-tree are
106287 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
106288 ** this entire function is being run by thread (pTask->thread), that will
106292 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
106293 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
106297 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
106301 IncrMerger *pIncr = pReadr->pIncr;
106302 SortSubtask *pTask = pIncr->pTask;
106303 sqlite3 *db = pTask->pSorter->db;
106305 /* eMode is always INCRINIT_NORMAL in single-threaded mode */
106308 rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
106310 /* Set up the required files for pIncr. A multi-threaded IncrMerge object
106311 ** requires two temp files to itself, whereas a single-threaded object
106312 ** only requires a region of pTask->file2. */
106314 int mxSz = pIncr->mxSz;
106316 if( pIncr->bUseThread ){
106317 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
106319 rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
106323 /*if( !pIncr->bUseThread )*/{
106324 if( pTask->file2.pFd==0 ){
106325 assert( pTask->file2.iEof>0 );
106326 rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
106327 pTask->file2.iEof = 0;
106330 pIncr->aFile[1].pFd = pTask->file2.pFd;
106331 pIncr->iStartOff = pTask->file2.iEof;
106332 pTask->file2.iEof += mxSz;
106338 if( rc==SQLITE_OK && pIncr->bUseThread ){
106340 ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
106342 ** pIncr->pTask->thread.
106371 pReader->pIncr->pTask->bDone = 1;
106377 ** If the PmaReader passed as the first argument is not an incremental-reader
106378 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
106382 ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
106388 IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
106392 assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
106393 if( pIncr->bUseThread ){
106395 rc = vdbeSorterCreateThread(pIncr->pTask, vdbePmaReaderBgIncrInit, pCtx);
106406 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
106407 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
106408 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
106409 ** to NULL and return an SQLite error code.
106412 ** first PMA to read from pTask->file. Assuming no error occurs, it is
106414 ** PMA before returning. If an error does occur, then the final value of
106420 i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
106421 MergeEngine **ppOut /* OUT: New merge-engine */
106433 PmaReader *pReadr = &pNew->aReadr[i];
106434 rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
106435 iOff = pReadr->iEof;
106452 ** nPMA<=16 -> TreeDepth() == 0
106453 ** nPMA<=256 -> TreeDepth() == 1
106454 ** nPMA<=65536 -> TreeDepth() == 2
106467 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
106471 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
106495 PmaReader *pReadr = &p->aReadr[iIter];
106497 if( pReadr->pIncr==0 ){
106502 rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
106506 p = pReadr->pIncr->pMerger;
106512 p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
106521 ** that has already written two or more level-0 PMAs to one or more temp
106526 ** MergeEngine object at the root of the tree before returning. Or, if an
106527 ** error occurs, an SQLite error code is returned and the final value
106539 /* If the sorter uses more than one task, then create the top-level
106541 ** one PmaReader per sub-task. */
106542 assert( pSorter->bUseThreads || pSorter->nTask==1 );
106543 if( pSorter->nTask>1 ){
106544 pMain = vdbeMergeEngineNew(pSorter->nTask);
106549 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
106550 SortSubtask *pTask = &pSorter->aTask[iTask];
106551 assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
106552 if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
106554 int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
106557 if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
106558 rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
106564 for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
106565 MergeEngine *pMerger = 0; /* New level-0 PMA merger */
106566 int nReader; /* Number of level-0 PMAs to merge */
106568 nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
106579 rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
106601 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
106604 ** (for multi-threaded sorters) so that it can be used to iterate through
106607 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
106611 SortSubtask *pTask0 = &pSorter->aTask[0];
106614 sqlite3 *db = pTask0->pSorter->db;
106617 for(i=0; i<pSorter->nTask; i++){
106618 pSorter->aTask[i].xCompare = xCompare;
106625 assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
106626 if( pSorter->bUseThreads ){
106629 SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
106633 pSorter->pReader = pReadr;
106637 rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
106639 vdbeIncrMergerSetThreads(pReadr->pIncr);
106640 for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
106642 if( (pIncr = pMain->aReadr[iTask].pIncr) ){
106644 assert( pIncr->pTask!=pLast );
106647 for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
106652 ** b) If it is using task (nTask-1), it is configured to run
106653 ** in single-threaded mode. This is important, as the
106657 PmaReader *p = &pMain->aReadr[iTask];
106658 assert( p->pIncr==0 || (
106659 (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
106660 && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
106674 pSorter->pMerger = pMain;
106695 assert( pCsr->eCurType==CURTYPE_SORTER );
106696 pSorter = pCsr->uc.pSorter;
106701 ** from the in-memory list. */
106702 if( pSorter->bUsePMA==0 ){
106703 if( pSorter->list.pList ){
106705 rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
106712 /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
106716 assert( pSorter->list.pList );
106726 assert( pSorter->pReader==0 );
106747 assert( pCsr->eCurType==CURTYPE_SORTER );
106748 pSorter = pCsr->uc.pSorter;
106749 assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
106750 if( pSorter->bUsePMA ){
106751 assert( pSorter->pReader==0 || pSorter->pMerger==0 );
106752 assert( pSorter->bUseThreads==0 || pSorter->pReader );
106753 assert( pSorter->bUseThreads==1 || pSorter->pMerger );
106755 if( pSorter->bUseThreads ){
106756 rc = vdbePmaReaderNext(pSorter->pReader);
106757 if( rc==SQLITE_OK && pSorter->pReader->pFd==0 ) rc = SQLITE_DONE;
106760 /*if( !pSorter->bUseThreads )*/ {
106762 assert( pSorter->pMerger!=0 );
106763 assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
106764 rc = vdbeMergeEngineStep(pSorter->pMerger, &res);
106768 SorterRecord *pFree = pSorter->list.pList;
106769 pSorter->list.pList = pFree->u.pNext;
106770 pFree->u.pNext = 0;
106771 if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
106772 rc = pSorter->list.pList ? SQLITE_OK : SQLITE_DONE;
106786 if( pSorter->bUsePMA ){
106789 if( pSorter->bUseThreads ){
106790 pReader = pSorter->pReader;
106793 /*if( !pSorter->bUseThreads )*/{
106794 pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
106796 *pnKey = pReader->nKey;
106797 pKey = pReader->aKey;
106799 *pnKey = pSorter->list.pList->nVal;
106800 pKey = SRVAL(pSorter->list.pList);
106812 assert( pCsr->eCurType==CURTYPE_SORTER );
106813 pSorter = pCsr->uc.pSorter;
106818 pOut->n = nKey;
106820 memcpy(pOut->z, pKey, nKey);
106833 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
106853 assert( pCsr->eCurType==CURTYPE_SORTER );
106854 pSorter = pCsr->uc.pSorter;
106855 r2 = pSorter->pUnpacked;
106856 pKeyInfo = pCsr->pKeyInfo;
106858 r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo);
106860 r2->nField = nKeyCol;
106862 assert( r2->nField==nKeyCol );
106867 if( r2->aMem[i].flags & MEM_Null ){
106868 *pRes = -1;
106873 *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
106880 ** 2020-03-23
106891 ** This file implements virtual-tables for examining the bytecode content
106898 /* An instance of the bytecode() table-valued function.
106902 sqlite3_vtab base; /* Base class - must be first */
106911 sqlite3_vtab_cursor base; /* Base class - must be first */
106926 ** Create a new bytecode() table-valued function.
106975 pNew->db = db;
106976 pNew->bTablesUsed = isTabUsed*2;
106999 sqlite3VdbeMemInit(&pCur->sub, pVTab->db, 1);
107000 *ppCursor = &pCur->base;
107008 sqlite3_free(pCur->zP4);
107009 pCur->zP4 = 0;
107010 sqlite3VdbeMemRelease(&pCur->sub);
107011 sqlite3VdbeMemSetNull(&pCur->sub);
107012 if( pCur->needFinalize ){
107013 sqlite3_finalize(pCur->pStmt);
107015 pCur->pStmt = 0;
107016 pCur->needFinalize = 0;
107017 pCur->zType = 0;
107018 pCur->zSchema = 0;
107019 pCur->zName = 0;
107038 bytecodevtab *pTab = (bytecodevtab*)cur->pVtab;
107040 if( pCur->zP4 ){
107041 sqlite3_free(pCur->zP4);
107042 pCur->zP4 = 0;
107044 if( pCur->zName ){
107045 pCur->zName = 0;
107046 pCur->zType = 0;
107047 pCur->zSchema = 0;
107050 (Vdbe*)pCur->pStmt,
107051 pCur->showSubprograms ? &pCur->sub : 0,
107052 pTab->bTablesUsed,
107053 &pCur->iRowid,
107054 &pCur->iAddr,
107055 &pCur->aOp);
107057 sqlite3VdbeMemSetNull(&pCur->sub);
107058 pCur->aOp = 0;
107069 return pCur->aOp==0;
107082 bytecodevtab *pVTab = (bytecodevtab*)cur->pVtab;
107083 Op *pOp = pCur->aOp + pCur->iAddr;
107084 if( pVTab->bTablesUsed ){
107088 if( i<=2 && pCur->zType==0 ){
107091 int iDb = pOp->p3;
107092 Pgno iRoot = (Pgno)pOp->p2;
107093 sqlite3 *db = pVTab->db;
107094 pSchema = db->aDb[iDb].pSchema;
107095 pCur->zSchema = db->aDb[iDb].zDbSName;
107096 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
107098 if( !IsVirtual(pTab) && pTab->tnum==iRoot ){
107099 pCur->zName = pTab->zName;
107100 pCur->zType = "table";
107104 if( pCur->zName==0 ){
107105 for(k=sqliteHashFirst(&pSchema->idxHash); k; k=sqliteHashNext(k)){
107107 if( pIdx->tnum==iRoot ){
107108 pCur->zName = pIdx->zName;
107109 pCur->zType = "index";
107119 sqlite3_result_int(ctx, pCur->iAddr);
107122 sqlite3_result_text(ctx, (char*)sqlite3OpcodeName(pOp->opcode),
107123 -1, SQLITE_STATIC);
107126 sqlite3_result_int(ctx, pOp->p1);
107129 sqlite3_result_int(ctx, pOp->p2);
107132 sqlite3_result_int(ctx, pOp->p3);
107136 if( pCur->zP4==0 ){
107137 pCur->zP4 = sqlite3VdbeDisplayP4(pVTab->db, pOp);
107140 sqlite3_result_text(ctx, pCur->zP4, -1, SQLITE_STATIC);
107143 char *zCom = sqlite3VdbeDisplayComment(pVTab->db, pOp, pCur->zP4);
107144 sqlite3_result_text(ctx, zCom, -1, sqlite3_free);
107149 sqlite3_result_int(ctx, pOp->p5);
107152 Op *aOp = pCur->aOp;
107154 assert( aOp[0].p4.z==0 || strncmp(aOp[0].p4.z,"-" "- ",3)==0 );
107155 if( pCur->iRowid==pCur->iAddr+1 ){
107158 sqlite3_result_text(ctx, aOp[0].p4.z+3, -1, SQLITE_STATIC);
107167 sqlite3_result_int64(ctx, pOp->nExec);
107170 sqlite3_result_int64(ctx, pOp->nCycle);
107180 sqlite3_result_text(ctx, pCur->zType, -1, SQLITE_STATIC);
107183 sqlite3_result_text(ctx, pCur->zSchema, -1, SQLITE_STATIC);
107186 sqlite3_result_text(ctx, pCur->zName, -1, SQLITE_STATIC);
107189 sqlite3_result_int(ctx, pOp->opcode==OP_OpenWrite);
107201 *pRowid = pCur->iRowid;
107217 bytecodevtab *pVTab = (bytecodevtab *)pVtabCursor->pVtab;
107222 pCur->iRowid = 0;
107223 pCur->iAddr = 0;
107224 pCur->showSubprograms = idxNum==0;
107231 rc = sqlite3_prepare_v2(pVTab->db, zSql, -1, &pCur->pStmt, 0);
107232 pCur->needFinalize = 1;
107235 pCur->pStmt = (sqlite3_stmt*)sqlite3_value_pointer(argv[0],"stmt-pointer");
107237 if( pCur->pStmt==0 ){
107238 pVTab->base.zErrMsg = sqlite3_mprintf(
107240 pVTab->bTablesUsed ? "tables_used" : "bytecode"
107252 ** then return an SQLITE_CONSTRAINT error.
107262 int iBaseCol = pVTab->bTablesUsed ? 4 : 10;
107263 pIdxInfo->estimatedCost = (double)100;
107264 pIdxInfo->estimatedRows = 100;
107265 pIdxInfo->idxNum = 0;
107266 for(i=0, p=pIdxInfo->aConstraint; i<pIdxInfo->nConstraint; i++, p++){
107267 if( p->usable==0 ) continue;
107268 if( p->op==SQLITE_INDEX_CONSTRAINT_EQ && p->iColumn==iBaseCol+1 ){
107270 pIdxInfo->aConstraintUsage[i].omit = 1;
107271 pIdxInfo->aConstraintUsage[i].argvIndex = 1;
107273 if( p->op==SQLITE_INDEX_CONSTRAINT_ISNULL && p->iColumn==iBaseCol ){
107274 pIdxInfo->aConstraintUsage[i].omit = 1;
107275 pIdxInfo->idxNum = 1;
107340 ** This file contains code use to implement an in-memory rollback journal.
107341 ** The in-memory rollback journal is used to journal transactions for
107344 ** Update: The in-memory journal is also used to temporarily cache
107345 ** smaller journals that are not critical for power-loss recovery.
107363 ** The zChunk array is always at least 8 bytes in size - usually much more.
107380 #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
107383 ** An instance of this object serves as a cursor into the rollback journal.
107392 ** This structure is a subclass of sqlite3_file. Each open memory-journal
107393 ** is an instance of this class.
107397 int nChunkSize; /* In-memory chunk-size */
107400 FileChunk *pFirst; /* Head of in-memory chunk-list */
107410 ** Read data from the in-memory journal file. This is the implementation
107425 if( (iAmt+iOfst)>p->endpoint.iOffset ){
107428 assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
107429 if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
107431 for(pChunk=p->pFirst;
107432 ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
107433 pChunk=pChunk->pNext
107435 iOff += p->nChunkSize;
107438 pChunk = p->readpoint.pChunk;
107442 iChunkOffset = (int)(iOfst%p->nChunkSize);
107444 int iSpace = p->nChunkSize - iChunkOffset;
107445 int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
107446 memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
107448 nRead -= iSpace;
107450 } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
107451 p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
107452 p->readpoint.pChunk = pChunk;
107464 pNext = pIter->pNext;
107483 for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
107485 nChunk = copy.endpoint.iOffset - iOff;
107487 rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
107492 /* No error has occurred. Free the in-memory buffers. */
107497 /* If an error occurred while creating or writing to the file, restore
107498 ** the original before returning. This way, SQLite uses the in-memory
107499 ** journal data to roll back changes made to the internal page-cache
107526 if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
107536 /* An in-memory journal file should only ever be appended to. Random
107538 ** the in-memory journal is being used by a connection using the
107539 ** atomic-write optimization. In this case the first 28 bytes of the
107541 assert( iOfst<=p->endpoint.iOffset );
107542 if( iOfst>0 && iOfst!=p->endpoint.iOffset ){
107545 if( iOfst==0 && p->pFirst ){
107546 assert( p->nChunkSize>iAmt );
107547 memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
107550 FileChunk *pChunk = p->endpoint.pChunk;
107551 int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
107552 int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
107557 FileChunk *pNew = sqlite3_malloc(fileChunkSize(p->nChunkSize));
107561 pNew->pNext = 0;
107563 assert( p->pFirst );
107564 pChunk->pNext = pNew;
107566 assert( !p->pFirst );
107567 p->pFirst = pNew;
107569 pChunk = p->endpoint.pChunk = pNew;
107573 memcpy((u8*)pChunk->zChunk + iChunkOffset, zWrite, iSpace);
107575 nWrite -= iSpace;
107576 p->endpoint.iOffset += iSpace;
107585 ** Truncate the in-memory file.
107589 assert( p->endpoint.pChunk==0 || p->endpoint.pChunk->pNext==0 );
107590 if( size<p->endpoint.iOffset ){
107593 memjrnlFreeChunks(p->pFirst);
107594 p->pFirst = 0;
107596 i64 iOff = p->nChunkSize;
107597 for(pIter=p->pFirst; ALWAYS(pIter) && iOff<size; pIter=pIter->pNext){
107598 iOff += p->nChunkSize;
107601 memjrnlFreeChunks(pIter->pNext);
107602 pIter->pNext = 0;
107606 p->endpoint.pChunk = pIter;
107607 p->endpoint.iOffset = size;
107608 p->readpoint.pChunk = 0;
107609 p->readpoint.iOffset = 0;
107619 memjrnlFreeChunks(p->pFirst);
107627 ** syncing an in-memory journal is a no-op.
107639 *pSize = (sqlite_int64) p->endpoint.iOffset;
107674 ** all content is always stored in main-memory. Finally, if nSpill is a
107675 ** positive value, then the journal file is initially created in-memory
107691 /* Zero the file-handle object. If nSpill was passed zero, initialize
107694 ** made on the journal file-handle. */
107701 p->nChunkSize = nSpill;
107703 p->nChunkSize = 8 + MEMJOURNAL_DFLT_FILECHUNKSIZE - sizeof(FileChunk);
107704 assert( MEMJOURNAL_DFLT_FILECHUNKSIZE==fileChunkSize(p->nChunkSize) );
107707 pJfd->pMethods = (const sqlite3_io_methods*)&MemJournalMethods;
107708 p->nSpill = nSpill;
107709 p->flags = flags;
107710 p->zJournal = zName;
107711 p->pVfs = pVfs;
107716 ** Open an in-memory journal file.
107719 sqlite3JournalOpen(0, 0, pJfd, 0, -1);
107725 ** If the argument p points to a MemJournal structure that is not an
107726 ** in-memory-only journal file (i.e. is one that was opened with a +ve
107733 if( pJfd->pMethods==&MemJournalMethods && (
107735 p->nSpill>0
107740 NEVER(p->nSpill>0)
107743 || (p->flags & SQLITE_OPEN_MAIN_JOURNAL)
107753 ** The file-handle passed as the only argument is open on a journal file.
107758 return p->pMethods==&MemJournalMethods;
107763 ** pVfs to create the underlying on-disk files.
107766 return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
107783 ** an SQL statement.
107797 for(pWin=pList; pWin; pWin=pWin->pNextWin){
107799 rc = sqlite3WalkExprList(pWalker, pWin->pOrderBy);
107801 rc = sqlite3WalkExprList(pWalker, pWin->pPartition);
107803 rc = sqlite3WalkExpr(pWalker, pWin->pFilter);
107805 rc = sqlite3WalkExpr(pWalker, pWin->pStart);
107807 rc = sqlite3WalkExpr(pWalker, pWin->pEnd);
107816 ** Walk an expression tree. Invoke the callback once for each node
107829 ** return from the top-level walk call.
107839 rc = pWalker->xExprCallback(pWalker, pExpr);
107842 assert( pExpr->x.pList==0 || pExpr->pRight==0 );
107843 if( pExpr->pLeft && sqlite3WalkExprNN(pWalker, pExpr->pLeft) ){
107846 if( pExpr->pRight ){
107848 pExpr = pExpr->pRight;
107852 if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
107854 if( pExpr->x.pList ){
107855 if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
107859 if( walkWindowList(pWalker, pExpr->y.pWin, 1) ) return WRC_Abort;
107874 ** an abort request is seen.
107880 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
107881 if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
107888 ** This is a no-op callback for Walker->xSelectCallback2. If this
107889 ** callback is set, then the Select->pWinDefn list is traversed.
107894 /* No-op */
107904 if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
107905 if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
107906 if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
107907 if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
107908 if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
107909 if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
107911 if( p->pWinDefn ){
107913 if( pWalker->xSelectCallback2==sqlite3WalkWinDefnDummyCallback
107914 || ((pParse = pWalker->pParse)!=0 && IN_RENAME_OBJECT)
107916 || pWalker->xSelectCallback2==sqlite3SelectPopWith
107921 int rc = walkWindowList(pWalker, p->pWinDefn, 0);
107941 pSrc = p->pSrc;
107943 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
107944 if( pItem->fg.isSubquery
107945 && sqlite3WalkSelect(pWalker, pItem->u4.pSubq->pSelect)
107949 if( pItem->fg.isTabFunc
107950 && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
107962 ** on the compound select chain, p->pPrior.
107967 ** but only if both xSelectCallback and xSelectCallback2 are both non-NULL
107971 ** there is an abort request.
107973 ** If the Walker does not have an xSelectCallback() then this routine
107974 ** is a no-op returning WRC_Continue.
107979 if( pWalker->xSelectCallback==0 ) return WRC_Continue;
107981 rc = pWalker->xSelectCallback(pWalker, p);
107988 if( pWalker->xSelectCallback2 ){
107989 pWalker->xSelectCallback2(pWalker, p);
107991 p = p->pPrior;
108001 pWalker->walkerDepth++;
108006 pWalker->walkerDepth--;
108011 ** No-op routine for the parse-tree walker.
108025 ** No-op routine for the parse-tree walker for SELECT statements.
108054 ** Magic table number to mean the EXCLUDED table in an UPSERT statement.
108061 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
108062 ** outer query into an inner subquery.
108065 ** is a helper function - a callback for the tree walker.
108070 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
108084 ** Turn the pExpr expression into an alias for the iCol-th column of the
108105 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
108106 Expr *pExpr, /* Transform this into an alias to the result set */
108109 Expr *pOrig; /* The iCol-th column of the result set */
108113 assert( iCol>=0 && iCol<pEList->nExpr );
108114 pOrig = pEList->a[iCol].pExpr;
108117 if( pExpr->pAggInfo ) return;
108118 db = pParse->db;
108120 if( db->mallocFailed ){
108126 if( pExpr->op==TK_COLLATE ){
108128 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
108134 if( ALWAYS(pExpr->y.pWin!=0) ){
108135 pExpr->y.pWin->pOwner = pExpr;
108145 ** and mark the expression-list item by setting ExprList.a[].fg.eEName
108148 ** Check to see if the zSpan/eEName of the expression-list item passed to this
108153 ** SF_NestedFrom subqueries also store an entry for the implicit rowid (or
108155 ** and setting zSpan to "DATABASE.TABLE.<rowid-alias>". This type of pItem
108168 int eEName = pItem->fg.eEName;
108173 zSpan = pItem->zEName;
108193 ** Return TRUE if the double-quoted string mis-feature should be supported.
108196 if( db->init.busy ) return 1; /* Always support for legacy schemas */
108197 if( pTopNC->ncFlags & NC_IsDDL ){
108199 if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
108202 return (db->flags & SQLITE_DqsDDL)!=0;
108205 return (db->flags & SQLITE_DqsDML)!=0;
108210 ** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
108217 n = pExpr->iColumn;
108219 pExTab = pExpr->y.pTab;
108221 assert( n < pExTab->nCol );
108222 if( (pExTab->tabFlags & TF_HasGenerated)!=0
108223 && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
108225 testcase( pExTab->nCol==BMS-1 );
108226 testcase( pExTab->nCol==BMS );
108227 return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
108229 testcase( n==BMS-1 );
108231 if( n>=BMS ) n = BMS-1;
108248 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
108250 pNew->iTable = pMatch->iCursor;
108251 pNew->iColumn = iColumn;
108252 pNew->y.pTab = pMatch->pSTab;
108253 assert( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 );
108260 ** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab.
108265 const char *zDb /* non-NULL if a database qualifier is present */
108269 assert( pTab->tnum==1 );
108271 zLegacy = pTab->zName;
108291 ** pExpr->iDb Set the index in db->aDb[] of the database X
108293 ** pExpr->iTable Set to the cursor number for the table obtained
108295 ** pExpr->y.pTab Points to the Table structure of X.Y (even if
108297 ** pExpr->iColumn Set to the column number within the table.
108298 ** pExpr->op Set to TK_COLUMN.
108299 ** pExpr->pLeft Any expression this points to is deleted
108300 ** pExpr->pRight Any expression this points to is deleted.
108309 ** If the name cannot be resolved unambiguously, leave an error message
108324 sqlite3 *db = pParse->db; /* The database connection */
108329 int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
108332 const char *zCol = pRight->u.zToken;
108339 /* Initialize the node to no-match */
108340 pExpr->iTable = -1;
108345 ** resulting in an appropriate error message toward the end of this routine
108348 testcase( pNC->ncFlags & NC_PartIdx );
108349 testcase( pNC->ncFlags & NC_IsCheck );
108350 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
108357 for(i=0; i<db->nDb; i++){
108358 assert( db->aDb[i].zDbSName );
108359 if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
108360 pSchema = db->aDb[i].pSchema;
108364 if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
108367 pSchema = db->aDb[0].pSchema;
108368 zDb = db->aDb[0].zDbSName;
108373 /* Start at the inner-most context and move outward until a match is found */
108377 SrcList *pSrcList = pNC->pSrcList;
108380 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
108381 pTab = pItem->pSTab;
108382 assert( pTab!=0 && pTab->zName!=0 );
108383 assert( pTab->nCol>0 || pParse->nErr );
108384 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem));
108385 if( pItem->fg.isNestedFrom ){
108390 ** This pItem -------------^
108394 assert( pItem->fg.isSubquery );
108395 assert( pItem->u4.pSubq!=0 );
108396 pSel = pItem->u4.pSubq->pSelect;
108398 pEList = pSel->pEList;
108400 assert( pEList->nExpr==pTab->nCol );
108401 for(j=0; j<pEList->nExpr; j++){
108403 if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb, &bRowid) ){
108408 if( pItem->fg.isUsing==0
108409 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
108412 ** not joined by USING. This is an error. Signal as much
108417 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
108418 /* An INNER or LEFT JOIN. Use the left-most table */
108421 if( (pItem->fg.jointype & JT_LEFT)==0 ){
108422 /* A RIGHT JOIN. Use the right-most table */
108428 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
108440 pExpr->iColumn = j;
108441 pEList->a[j].fg.bUsed = 1;
108443 /* rowid cannot be part of a USING clause - assert() this. */
108444 assert( bRowid==0 || pEList->a[j].fg.bUsingTerm==0 );
108445 if( pEList->a[j].fg.bUsingTerm ) break;
108452 if( pTab->pSchema!=pSchema ) continue;
108455 if( pItem->zAlias!=0 ){
108456 if( sqlite3StrICmp(zTab, pItem->zAlias)!=0 ){
108459 }else if( sqlite3StrICmp(zTab, pTab->zName)!=0 ){
108460 if( pTab->tnum!=1 ) continue;
108464 if( IN_RENAME_OBJECT && pItem->zAlias ){
108465 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
108471 if( pItem->fg.isUsing==0
108472 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
108475 ** not joined by USING. This is an error. Signal as much
108480 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
108481 /* An INNER or LEFT JOIN. Use the left-most table */
108484 if( (pItem->fg.jointype & JT_LEFT)==0 ){
108485 /* A RIGHT JOIN. Use the right-most table */
108491 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
108496 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
108497 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
108498 if( pItem->fg.isNestedFrom ){
108511 ** non-VIEW candidate plus multiple VIEW candidates. In other
108512 ** words non-VIEW candidate terms take precedence over VIEWs.
108517 && ALWAYS(pMatch->pSTab!=0)
108518 && (pMatch->pSTab->tabFlags & TF_Ephemeral)!=0
108519 && (pTab->tabFlags & TF_Ephemeral)==0)
108527 /* The (much more common) non-SQLITE_ALLOW_ROWID_IN_VIEW case is
108529 ** always be a non-VIEW
108537 pExpr->iTable = pMatch->iCursor;
108539 pExpr->y.pTab = pMatch->pSTab;
108540 if( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ){
108543 pSchema = pExpr->y.pTab->pSchema;
108550 ** maybe it is an excluded.* from an upsert. Or maybe it is
108556 if( pParse->pTriggerTab!=0 ){
108557 int op = pParse->eTriggerOp;
108559 if( pParse->bReturning ){
108560 if( (pNC->ncFlags & NC_UBaseReg)!=0
108562 || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0
108563 || isValidSchemaTableName(zTab, pParse->pTriggerTab, 0))
108565 pExpr->iTable = op!=TK_DELETE;
108566 pTab = pParse->pTriggerTab;
108569 pExpr->iTable = 1;
108570 pTab = pParse->pTriggerTab;
108572 pExpr->iTable = 0;
108573 pTab = pParse->pTriggerTab;
108578 if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){
108579 Upsert *pUpsert = pNC->uNC.pUpsert;
108581 pTab = pUpsert->pUpsertSrc->a[0].pSTab;
108582 pExpr->iTable = EXCLUDED_TABLE_NUMBER;
108589 pSchema = pTab->pSchema;
108593 if( pTab->iPKey==iCol ) iCol = -1;
108596 iCol = -1;
108598 iCol = pTab->nCol;
108601 if( iCol<pTab->nCol ){
108605 if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
108606 testcase( iCol==(-1) );
108609 pExpr->iColumn = iCol;
108610 pExpr->y.pTab = pTab;
108613 pExpr->iTable = pNC->uNC.pUpsert->regData +
108621 pExpr->y.pTab = pTab;
108622 if( pParse->bReturning ){
108624 pExpr->op2 = TK_COLUMN;
108625 pExpr->iColumn = iCol;
108626 pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
108629 pExpr->iColumn = (i16)iCol;
108633 pExpr->affExpr = SQLITE_AFF_INTEGER;
108634 }else if( pExpr->iTable==0 ){
108637 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
108641 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
108657 && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
108659 && ALWAYS(VisibleRowid(pMatch->pSTab) || pMatch->fg.isNestedFrom)
108663 if( pMatch->pSTab!=0 && IsView(pMatch->pSTab) ){
108667 if( pMatch->fg.isNestedFrom==0 ) pExpr->iColumn = -1;
108668 pExpr->affExpr = SQLITE_AFF_INTEGER;
108673 ** might refer to an result-set alias. This happens, for example, when
108683 ** The ability to use an output result-set column in the WHERE, GROUP BY,
108690 && (pNC->ncFlags & NC_UEList)!=0
108693 pEList = pNC->uNC.pEList;
108695 for(j=0; j<pEList->nExpr; j++){
108696 char *zAs = pEList->a[j].zEName;
108697 if( pEList->a[j].fg.eEName==ENAME_NAME
108701 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
108702 assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 );
108703 assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 );
108704 pOrig = pEList->a[j].pExpr;
108705 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
108710 && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
108735 pNC = pNC->pNext;
108742 ** supplied) and the value of Z is enclosed in double-quotes, then
108747 ** Because no reference was made to outer contexts, the pNC->nRef
108751 assert( pExpr->op==TK_ID );
108755 /* If a double-quoted identifier does not match any known column name,
108759 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
108762 ** rather than causing an error, to the frustration of countless
108770 "double-quoted string literal: \"%w\"", zCol);
108772 sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
108774 pExpr->op = TK_STRING;
108775 memset(&pExpr->y, 0, sizeof(pExpr->y));
108787 ** cnt==0 is always an error. cnt>1 is often an error, but might
108795 if( pFJMatch->nExpr==cnt-1 ){
108799 sqlite3ExprDelete(db, pExpr->pLeft);
108800 pExpr->pLeft = 0;
108801 sqlite3ExprDelete(db, pExpr->pRight);
108802 pExpr->pRight = 0;
108804 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
108805 pExpr->op = TK_FUNCTION;
108806 pExpr->u.zToken = "coalesce";
108807 pExpr->x.pList = pFJMatch;
108821 sqlite3ErrorMsg(pParse, "%s: \"%s\" - should this be a"
108822 " string literal in single-quotes?",
108827 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
108828 pParse->checkSchema = 1;
108829 pTopNC->nNcErr++;
108836 sqlite3ExprDelete(db, pExpr->pLeft);
108837 pExpr->pLeft = 0;
108838 sqlite3ExprDelete(db, pExpr->pRight);
108839 pExpr->pRight = 0;
108848 ** The colUsed mask is an optimization used to help determine if an
108858 if( pExpr->iColumn>=0 ){
108859 pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
108861 pMatch->fg.rowidUsed = 1;
108865 pExpr->op = eNewExprOp;
108870 if( pParse->db->xAuth
108871 && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER)
108873 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
108880 pTopNC->nRef++;
108882 pTopNC = pTopNC->pNext;
108891 ** Allocate and return a pointer to an expression to load the column iCol
108897 SrcItem *pItem = &pSrc->a[iSrc];
108900 pTab = p->y.pTab = pItem->pSTab;
108901 p->iTable = pItem->iCursor;
108902 if( p->y.pTab->iPKey==iCol ){
108903 p->iColumn = -1;
108905 p->iColumn = (ynVar)iCol;
108906 if( (pTab->tabFlags & TF_HasGenerated)!=0
108907 && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
108909 testcase( pTab->nCol==63 );
108910 testcase( pTab->nCol==64 );
108911 pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
108914 testcase( iCol==BMS-1 );
108915 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
108923 ** Report an error that an expression is not valid for some set of
108924 ** pNC->ncFlags values determined by validMask.
108934 ** As an optimization, since the conditional is almost always false
108946 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
108948 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
108951 else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
108954 if( pExpr ) pExpr->op = TK_NULL;
108955 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
108959 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
108963 ** Return 1024 times this value. Or return -1 if p is not a floating point
108967 double r = -1.0;
108968 if( p->op!=TK_FLOAT ) return -1;
108970 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
108972 if( r>1.0 ) return -1;
108991 pNC = pWalker->u.pNC;
108993 pParse = pNC->pParse;
108994 assert( pParse==pWalker->pParse );
108997 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
108998 SrcList *pSrcList = pNC->pSrcList;
109000 for(i=0; i<pNC->pSrcList->nSrc; i++){
109001 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
109005 switch( pExpr->op ){
109013 SrcList *pSrcList = pNC->pSrcList;
109015 assert( pSrcList && pSrcList->nSrc>=1 );
109016 pItem = pSrcList->a;
109017 pExpr->op = TK_COLUMN;
109019 pExpr->y.pTab = pItem->pSTab;
109020 pExpr->iTable = pItem->iCursor;
109021 pExpr->iColumn--;
109022 pExpr->affExpr = SQLITE_AFF_INTEGER;
109026 /* An optimization: Attempt to convert
109028 ** "expr IS NOT NULL" --> "TRUE"
109029 ** "expr IS NULL" --> "FALSE"
109034 ** If this optimization occurs, also restore the NameContext ref-counts
109040 ** 2024-03-28: Beware of aggregates. A bare column of aggregated table
109058 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
109059 anRef[i] = p->nRef;
109061 sqlite3WalkExpr(pWalker, pExpr->pLeft);
109063 if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
109068 for(i=0, p=pNC; p; p=p->pNext, i++){
109069 if( (p->ncFlags & NC_Where)==0 ){
109079 pExpr->op==TK_NOTNULL
109084 pExpr->u.iValue = (pExpr->op==TK_NOTNULL);
109085 pExpr->flags |= EP_IntValue;
109086 pExpr->op = TK_INTEGER;
109087 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
109088 p->nRef = anRef[i];
109090 sqlite3ExprDelete(pParse->db, pExpr->pLeft);
109091 pExpr->pLeft = 0;
109100 ** be one call to lookupName(). Then the compiler will in-line
109109 if( pExpr->op==TK_ID ){
109115 Expr *pLeft = pExpr->pLeft;
109116 testcase( pNC->ncFlags & NC_IdxExpr );
109117 testcase( pNC->ncFlags & NC_GenCol );
109120 pRight = pExpr->pRight;
109121 if( pRight->op==TK_ID ){
109124 assert( pRight->op==TK_DOT );
109126 zDb = pLeft->u.zToken;
109127 pLeft = pRight->pLeft;
109128 pRight = pRight->pRight;
109131 zTable = pLeft->u.zToken;
109135 sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
109148 int is_agg = 0; /* True if is an aggregate function */
109151 u8 enc = ENC(pParse->db); /* The database encoding */
109152 int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
109154 Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
109157 assert( pExpr->pLeft==0 || pExpr->pLeft->op==TK_ORDER );
109158 pList = pExpr->x.pList;
109159 n = pList ? pList->nExpr : 0;
109160 zId = pExpr->u.zToken;
109161 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
109163 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
109170 is_agg = pDef->xFinalize!=0;
109171 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
109174 pExpr->iTable = exprProbability(pList->a[1].pExpr);
109175 if( pExpr->iTable<0 ){
109179 pNC->nNcErr++;
109182 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
109184 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
109185 ** short-hand for likelihood(X,0.0625).
109186 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
109188 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
109191 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
109196 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
109201 pNC->nNcErr++;
109203 pExpr->op = TK_NULL;
109211 ** where.c from replacing the expression with a value read from an
109214 ** an EP_SubtArg expression. In this case subtypes are required as
109217 if( (pDef->funcFlags & SQLITE_SUBTYPE)
109222 ExprSetProperty(pList->a[ii].pExpr, EP_SubtArg);
109226 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
109233 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
109234 /* Clearly non-deterministic functions like random(), but also
109237 ** in an index or generated column. Curiously, they can be used
109240 sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
109244 pExpr->op2 = pNC->ncFlags & NC_SelfRef;
109246 if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
109247 && pParse->nested==0
109248 && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
109250 /* Internal-use-only functions are disallowed unless the
109252 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
109257 if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
109260 if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
109267 assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
109268 || (pDef->xValue==0 && pDef->xInverse==0)
109269 || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
109271 if( pDef && pDef->xValue==0 && pWin ){
109275 pNC->nNcErr++;
109277 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
109278 || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
109279 || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
109282 if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
109288 pNC->nNcErr++;
109292 if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
109294 pNC->nNcErr++;
109298 else if( no_such_func && pParse->db->init.busy==0
109300 && pParse->explain==0
109304 pNC->nNcErr++;
109308 pNC->nNcErr++;
109313 "FILTER may not be used with non-aggregate %#T()",
109316 pNC->nNcErr++;
109319 else if( is_agg==0 && pExpr->pLeft ){
109321 pNC->nNcErr++;
109328 pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
109330 pNC->ncFlags &= ~NC_AllowAgg;
109334 else if( ExprHasProperty(pExpr, EP_WinFunc) || pExpr->pLeft ){
109339 if( pExpr->pLeft ){
109340 assert( pExpr->pLeft->op==TK_ORDER );
109341 assert( ExprUseXList(pExpr->pLeft) );
109342 sqlite3WalkExprList(pWalker, pExpr->pLeft->x.pList);
109345 if( pWin && pParse->nErr==0 ){
109346 Select *pSel = pNC->pWinSelect;
109347 assert( ExprUseYWin(pExpr) && pWin==pExpr->y.pWin );
109349 sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
109350 if( pParse->db->mallocFailed ) break;
109352 sqlite3WalkExprList(pWalker, pWin->pPartition);
109353 sqlite3WalkExprList(pWalker, pWin->pOrderBy);
109354 sqlite3WalkExpr(pWalker, pWin->pFilter);
109356 pNC->ncFlags |= NC_HasWin;
109361 pExpr->op = TK_AGG_FUNCTION;
109362 pExpr->op2 = 0;
109365 sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
109370 && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
109372 pExpr->op2 += (1 + pNC2->nNestedSelect);
109373 pNC2 = pNC2->pNext;
109377 pExpr->op2 += pNC2->nNestedSelect;
109380 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
109381 testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
109382 pNC2->ncFlags |= NC_HasAgg
109383 | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
109387 pNC->ncFlags |= savedAllowFlags;
109389 /* FIX ME: Compute pExpr->affinity based on the expected return
109396 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
109399 testcase( pExpr->op==TK_IN );
109401 int nRef = pNC->nRef;
109402 testcase( pNC->ncFlags & NC_IsCheck );
109403 testcase( pNC->ncFlags & NC_PartIdx );
109404 testcase( pNC->ncFlags & NC_IdxExpr );
109405 testcase( pNC->ncFlags & NC_GenCol );
109406 assert( pExpr->x.pSelect );
109407 if( pNC->ncFlags & NC_SelfRef ){
109410 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
109412 assert( pNC->nRef>=nRef );
109413 if( nRef!=pNC->nRef ){
109415 pExpr->x.pSelect->selFlags |= SF_Correlated;
109417 pNC->ncFlags |= NC_Subquery;
109422 testcase( pNC->ncFlags & NC_IsCheck );
109423 testcase( pNC->ncFlags & NC_PartIdx );
109424 testcase( pNC->ncFlags & NC_IdxExpr );
109425 testcase( pNC->ncFlags & NC_GenCol );
109432 Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
109436 if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
109439 if( pRight->op==TK_TRUEFALSE ){
109440 pExpr->op2 = pExpr->op;
109441 pExpr->op = TK_TRUTH;
109455 if( pParse->db->mallocFailed ) break;
109456 assert( pExpr->pLeft!=0 );
109457 nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
109458 if( pExpr->op==TK_BETWEEN ){
109460 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
109462 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
109465 assert( pExpr->pRight!=0 );
109466 nRight = sqlite3ExprVectorSize(pExpr->pRight);
109469 testcase( pExpr->op==TK_EQ );
109470 testcase( pExpr->op==TK_NE );
109471 testcase( pExpr->op==TK_LT );
109472 testcase( pExpr->op==TK_LE );
109473 testcase( pExpr->op==TK_GT );
109474 testcase( pExpr->op==TK_GE );
109475 testcase( pExpr->op==TK_IS );
109476 testcase( pExpr->op==TK_ISNOT );
109477 testcase( pExpr->op==TK_BETWEEN );
109479 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
109484 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
109485 return pParse->nErr ? WRC_Abort : WRC_Continue;
109490 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
109492 ** to the AS-name of one of the terms of the expression list. If it is,
109493 ** this routine return an integer between 1 and N where N is the number of
109509 if( pE->op==TK_ID ){
109512 zCol = pE->u.zToken;
109513 for(i=0; i<pEList->nExpr; i++){
109514 if( pEList->a[i].fg.eEName==ENAME_NAME
109515 && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
109525 ** pE is a pointer to an expression which is a single term in the
109530 ** ORDER BY term is not an integer index into the result set. That
109533 ** Attempt to match pE against result set columns in the left-most
109535 ** as an indication to the caller that it should sort by the i-th column.
109536 ** The left-most column is 1. In other words, the value returned is the
109540 ** If there is no match, return 0. Return -1 if an error occurs.
109552 u8 savedSuppErr; /* Saved value of db->suppressErr */
109555 pEList = pSelect->pEList;
109561 nc.pSrcList = pSelect->pSrc;
109565 db = pParse->db;
109566 savedSuppErr = db->suppressErr;
109567 db->suppressErr = 1;
109569 db->suppressErr = savedSuppErr;
109572 /* Try to match the ORDER BY expression against an expression
109573 ** in the result set. Return an 1-based index of the matching
109574 ** result-set entry.
109576 for(i=0; i<pEList->nExpr; i++){
109577 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
109587 ** Generate an ORDER BY or GROUP BY term out-of-range error.
109592 int i, /* The index (1-based) of the term out of range */
109597 "%r %s BY term out of range - should be "
109599 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
109607 ** ORDER BY terms that are already an integer between 1 and N are
109609 ** 1 through N generate an error. ORDER BY terms that are expressions
109611 ** beginning with the left-most SELECT and working toward the right.
109627 pOrderBy = pSelect->pOrderBy;
109629 db = pParse->db;
109630 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
109634 for(i=0; i<pOrderBy->nExpr; i++){
109635 pOrderBy->a[i].fg.done = 0;
109637 pSelect->pNext = 0;
109638 while( pSelect->pPrior ){
109639 pSelect->pPrior->pNext = pSelect;
109640 pSelect = pSelect->pPrior;
109645 pEList = pSelect->pEList;
109647 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
109648 int iCol = -1;
109650 if( pItem->fg.done ) continue;
109651 pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
109654 if( iCol<=0 || iCol>pEList->nExpr ){
109655 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
109668 ** If this is running as part of an ALTER TABLE operation and
109673 if( !db->mallocFailed ){
109684 /* Convert the ORDER BY term into an integer column number iCol,
109689 pNew->flags |= EP_IntValue;
109690 pNew->u.iValue = iCol;
109691 if( pItem->pExpr==pE ){
109692 pItem->pExpr = pNew;
109694 Expr *pParent = pItem->pExpr;
109695 assert( pParent->op==TK_COLLATE );
109696 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
109697 assert( pParent->pLeft==pE );
109698 pParent->pLeft = pNew;
109701 pItem->u.x.iOrderByCol = (u16)iCol;
109703 pItem->fg.done = 1;
109708 pSelect = pSelect->pNext;
109710 for(i=0; i<pOrderBy->nExpr; i++){
109711 if( pOrderBy->a[i].fg.done==0 ){
109727 ** If any errors are detected, add an error message to pParse and
109728 ** return non-zero. Return zero if no errors are seen.
109737 sqlite3 *db = pParse->db;
109741 if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
109742 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
109746 pEList = pSelect->pEList;
109748 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
109749 if( pItem->u.x.iOrderByCol ){
109750 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
109751 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
109754 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
109767 Window *pWin = pExpr->y.pWin;
109778 if( pSelect->pWin ){
109791 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
109795 ** This routine resolves each term of the clause into an expression.
109796 ** If the order-by term is an integer I between 1 and N (where N is the
109798 ** in the resolution is a copy of the I-th result-set expression. If
109799 ** the order-by term is an identifier that corresponds to the AS-name of
109800 ** a result-set expression, then the term resolves to a copy of the
109801 ** result-set expression. Otherwise, the expression is resolved in
109802 ** the usual way - using sqlite3ResolveExprNames().
109805 ** an appropriate error message might be left in pParse. (OOM errors
109811 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
109821 nResult = pSelect->pEList->nExpr;
109822 pParse = pNC->pParse;
109823 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
109824 Expr *pE = pItem->pExpr;
109828 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
109830 /* If an AS-name match is found, mark this ORDER BY column as being
109831 ** a copy of the iCol-th result-set column. The subsequent call to
109833 ** copy of the iCol-th result-set expression. */
109834 pItem->u.x.iOrderByCol = (u16)iCol;
109839 /* The ORDER BY term is an integer constant. Again, set the column
109841 ** order-by term to a copy of the result-set expression */
109846 pItem->u.x.iOrderByCol = (u16)iCol;
109850 /* Otherwise, treat the ORDER BY term as an ordinary expression */
109851 pItem->u.x.iOrderByCol = 0;
109855 for(j=0; j<pSelect->pEList->nExpr; j++){
109856 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
109858 ** to an identical expression in the result set, remove all Window
109861 pItem->u.x.iOrderByCol = j+1;
109879 Select *pLeftmost; /* Left-most of SELECT of a compound */
109884 if( p->selFlags & SF_Resolved ){
109887 pOuterNC = pWalker->u.pNC;
109888 pParse = pWalker->pParse;
109889 db = pParse->db;
109893 ** an expression, sqlite3ResolveExprNames() will be called without a
109899 if( (p->selFlags & SF_Expanded)==0 ){
109901 return pParse->nErr ? WRC_Abort : WRC_Prune;
109904 isCompound = p->pPrior!=0;
109908 assert( (p->selFlags & SF_Expanded)!=0 );
109909 assert( (p->selFlags & SF_Resolved)==0 );
109910 p->selFlags |= SF_Resolved;
109913 ** are not allowed to refer to any names, so pass an empty NameContext.
109918 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
109924 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
109925 ** as if it were part of the sub-query, not the parent. This block
109926 ** moves the pOrderBy down to the sub-query. It will be moved back
109928 if( p->selFlags & SF_Converted ){
109930 assert( p->pSrc->a[0].fg.isSubquery );
109931 assert( p->pSrc->a[0].u4.pSubq!=0 );
109932 pSub = p->pSrc->a[0].u4.pSubq->pSelect;
109934 assert( p->pSrc->nSrc==1 && p->pOrderBy );
109935 assert( pSub->pPrior && pSub->pOrderBy==0 );
109936 pSub->pOrderBy = p->pOrderBy;
109937 p->pOrderBy = 0;
109942 if( pOuterNC ) pOuterNC->nNestedSelect++;
109943 for(i=0; i<p->pSrc->nSrc; i++){
109944 SrcItem *pItem = &p->pSrc->a[i];
109945 assert( pItem->zName!=0
109946 || pItem->fg.isSubquery ); /* Test of tag-20240424-1*/
109947 if( pItem->fg.isSubquery
109948 && (pItem->u4.pSubq->pSelect->selFlags & SF_Resolved)==0
109950 int nRef = pOuterNC ? pOuterNC->nRef : 0;
109951 const char *zSavedContext = pParse->zAuthContext;
109953 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
109954 sqlite3ResolveSelectNames(pParse, pItem->u4.pSubq->pSelect, pOuterNC);
109955 pParse->zAuthContext = zSavedContext;
109956 if( pParse->nErr ) return WRC_Abort;
109957 assert( db->mallocFailed==0 );
109960 ** expressions in the sub-select were resolved, the sub-select
109966 assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
109967 pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
109971 if( pOuterNC && ALWAYS(pOuterNC->nNestedSelect>0) ){
109972 pOuterNC->nNestedSelect--;
109975 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
109976 ** resolve the result-set expression list.
109979 sNC.pSrcList = p->pSrc;
109983 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
109986 /* If there are no aggregate functions in the result-set, and no GROUP BY
109989 assert( (p->selFlags & SF_Aggregate)==0 );
109990 pGroupBy = p->pGroupBy;
109994 p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
109999 /* Add the output column list to the name-context before parsing the
110005 ** re-evaluated for each reference to it.
110008 sNC.uNC.pEList = p->pEList;
110010 if( p->pHaving ){
110011 if( (p->selFlags & SF_Aggregate)==0 ){
110012 sqlite3ErrorMsg(pParse, "HAVING clause on a non-aggregate query");
110015 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
110018 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
110021 /* Resolve names in table-valued-function arguments */
110022 for(i=0; i<p->pSrc->nSrc; i++){
110023 SrcItem *pItem = &p->pSrc->a[i];
110024 if( pItem->fg.isTabFunc
110025 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
110034 for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
110035 if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
110036 || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
110051 ** the sub-query back to the parent query. At this point each term
110052 ** within the ORDER BY clause has been transformed to an integer value.
110055 if( p->selFlags & SF_Converted ){
110057 assert( p->pSrc->a[0].fg.isSubquery );
110058 pSub = p->pSrc->a[0].u4.pSubq->pSelect;
110060 p->pOrderBy = pSub->pOrderBy;
110061 pSub->pOrderBy = 0;
110066 ** below, after all of the result-sets for all of the elements of
110069 ** If there is an ORDER BY clause on a term of a compound-select other
110070 ** than the right-most term, then that is a syntax error. But the error
110074 if( p->pOrderBy!=0
110075 && isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
110076 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
110080 if( db->mallocFailed ){
110091 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
110094 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
110095 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
110105 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
110106 sqlite3SelectWrongNumTermsError(pParse, p->pNext);
110112 p = p->pPrior;
110127 ** This routine walks an expression tree and resolves references to
110128 ** table columns and result-set columns. At the same time, do error
110136 ** the symbolic name assigned to an ATTACH-ed database.
110147 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
110151 ** To resolve result-set references, look for expression nodes of the
110152 ** form Z (with no X and Y prefix) where the Z matches the right-hand
110153 ** size of an AS clause in the result-set of a SELECT. The Z expression
110154 ** is replaced by a copy of the left-hand side of the result-set expression.
110155 ** Table-name and function resolution occurs on the substituted expression
110166 ** If the function is an aggregate function, then the NC_HasAgg flag is
110168 ** If an expression contains aggregate functions then the EP_Agg
110171 ** An error message is left in pParse if anything is amiss. The number
110182 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
110183 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
110184 w.pParse = pNC->pParse;
110186 w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
110190 w.pParse->nHeight += pExpr->nHeight;
110191 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
110198 w.pParse->nHeight -= pExpr->nHeight;
110202 testcase( pNC->ncFlags & NC_HasAgg );
110203 testcase( pNC->ncFlags & NC_HasWin );
110204 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
110205 pNC->ncFlags |= savedHasAgg;
110206 return pNC->nNcErr>0 || w.pParse->nErr>0;
110210 ** Resolve all names for all expression in an expression list. This is
110211 ** just like sqlite3ResolveExprNames() except that it works for an expression
110225 w.pParse = pNC->pParse;
110230 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
110231 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
110232 for(i=0; i<pList->nExpr; i++){
110233 Expr *pExpr = pList->a[i].pExpr;
110236 w.pParse->nHeight += pExpr->nHeight;
110237 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
110243 w.pParse->nHeight -= pExpr->nHeight;
110247 testcase( pNC->ncFlags & NC_HasAgg );
110248 testcase( pNC->ncFlags & NC_HasWin );
110249 if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
110250 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
110251 savedHasAgg |= pNC->ncFlags &
110253 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
110255 if( w.pParse->nErr>0 ) return SQLITE_ERROR;
110257 pNC->ncFlags |= savedHasAgg;
110263 ** descendants of the SELECT, including compounds off of p->pPrior,
110294 ** ------------
110302 ** nodes of the expression is set to -1 and the Expr.iColumn value is
110303 ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
110305 ** Any errors cause an error message to be set in pParse.
110314 SrcList *pSrc; /* Fake SrcList for pParse->pNewTable */
110315 NameContext sNC; /* Name context for pParse->pNewTable */
110326 pSrc->nSrc = 1;
110327 pSrc->a[0].zName = pTab->zName;
110328 pSrc->a[0].pSTab = pTab;
110329 pSrc->a[0].iCursor = -1;
110330 if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
110331 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
110370 if( iCol<0 || NEVER(iCol>=pTab->nCol) ) return SQLITE_AFF_INTEGER;
110371 return pTab->aCol[iCol].affinity;
110377 ** If pExpr is a column, a reference to a column via an 'AS' alias,
110378 ** or a sub-select with a column as the return value, then the
110383 ** have an affinity:
110392 op = pExpr->op;
110393 while( 1 /* exit-by-break */ ){
110394 if( op==TK_COLUMN || (op==TK_AGG_COLUMN && pExpr->y.pTab!=0) ){
110396 assert( pExpr->y.pTab!=0 );
110397 return sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
110401 assert( pExpr->x.pSelect!=0 );
110402 assert( pExpr->x.pSelect->pEList!=0 );
110403 assert( pExpr->x.pSelect->pEList->a[0].pExpr!=0 );
110404 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
110409 return sqlite3AffinityType(pExpr->u.zToken, 0);
110413 assert( pExpr->pLeft!=0 && ExprUseXSelect(pExpr->pLeft) );
110414 assert( pExpr->iColumn < pExpr->iTable );
110415 assert( pExpr->iColumn >= 0 );
110416 assert( pExpr->iTable==pExpr->pLeft->x.pSelect->pEList->nExpr );
110418 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
110422 || (op==TK_FUNCTION && pExpr->affExpr==SQLITE_AFF_DEFER)
110425 return sqlite3ExprAffinity(pExpr->x.pList->a[0].pExpr);
110428 assert( pExpr->op==TK_COLLATE
110429 || pExpr->op==TK_IF_NULL_ROW
110430 || (pExpr->op==TK_REGISTER && pExpr->op2==TK_IF_NULL_ROW) );
110431 pExpr = pExpr->pLeft;
110432 op = pExpr->op;
110436 op = pExpr->op2;
110439 return pExpr->affExpr;
110444 ** be returned by an expression. Return a bitmask indicating the answer:
110454 switch( pExpr->op ){
110458 pExpr = pExpr->pLeft;
110493 ExprList *pList = pExpr->x.pList;
110495 assert( pList->nExpr > 0);
110496 for(ii=1; ii<pList->nExpr; ii+=2){
110497 res |= sqlite3ExprDataType(pList->a[ii].pExpr);
110499 if( pList->nExpr % 2 ){
110500 res |= sqlite3ExprDataType(pList->a[pList->nExpr-1].pExpr);
110517 ** If a memory allocation error occurs, that fact is recorded in pParse->db
110526 if( pCollName->n>0 ){
110527 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
110529 pNew->pLeft = pExpr;
110530 pNew->flags |= EP_Collate|EP_Skip;
110552 assert( pExpr->op==TK_COLLATE );
110553 pExpr = pExpr->pLeft;
110560 ** or likelihood() or likely() functions at the root of an
110567 assert( pExpr->x.pList->nExpr>0 );
110568 assert( pExpr->op==TK_FUNCTION );
110569 pExpr = pExpr->x.pList->a[0].pExpr;
110570 }else if( pExpr->op==TK_COLLATE ){
110571 pExpr = pExpr->pLeft;
110594 sqlite3 *db = pParse->db;
110598 int op = p->op;
110599 if( op==TK_REGISTER ) op = p->op2;
110600 if( (op==TK_AGG_COLUMN && p->y.pTab!=0)
110605 assert( p->y.pTab!=0 );
110606 if( (j = p->iColumn)>=0 ){
110607 const char *zColl = sqlite3ColumnColl(&p->y.pTab->aCol[j]);
110613 p = p->pLeft;
110617 || (op==TK_FUNCTION && p->affExpr==SQLITE_AFF_DEFER)
110620 p = p->x.pList->a[0].pExpr;
110625 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
110628 if( p->flags & EP_Collate ){
110629 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
110630 p = p->pLeft;
110632 Expr *pNext = p->pRight;
110634 assert( !ExprUseXList(p) || p->x.pList==0 || p->pRight==0 );
110635 if( ExprUseXList(p) && p->x.pList!=0 && !db->mallocFailed ){
110637 for(i=0; i<p->x.pList->nExpr; i++){
110638 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
110639 pNext = p->x.pList->a[i].pExpr;
110668 if( p==0 ) p = pParse->db->pDfltColl;
110679 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
110683 ** pExpr is an operand of a comparison operator. aff2 is the
110711 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
110712 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
110713 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
110714 assert( pExpr->pLeft );
110715 aff = sqlite3ExprAffinity(pExpr->pLeft);
110716 if( pExpr->pRight ){
110717 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
110719 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
110728 ** idx_affinity is the affinity of an indexed column. Return true
110776 if( pLeft->flags & EP_Collate ){
110778 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
110799 return sqlite3BinaryCompareCollSeq(pParse, p->pRight, p->pLeft);
110801 return sqlite3BinaryCompareCollSeq(pParse, p->pLeft, p->pRight);
110822 if( pParse->nErr ) return 0;
110829 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
110831 sqlite3VdbeChangeP5(pParse->pVdbe, (u16)p5);
110839 ** columns of result. Every TK_VECTOR node is an vector because the
110851 ** is a sub-select, return the number of columns in the sub-select. For
110855 u8 op = pExpr->op;
110856 if( op==TK_REGISTER ) op = pExpr->op2;
110859 return pExpr->x.pList->nExpr;
110862 return pExpr->x.pSelect->pEList->nExpr;
110869 ** Return a pointer to a subexpression of pVector that is the i-th
110879 ** just the expression for the i-th term of the result set, and may
110884 assert( i<sqlite3ExprVectorSize(pVector) || pVector->op==TK_ERROR );
110886 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
110887 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
110889 return pVector->x.pSelect->pEList->a[i].pExpr;
110892 return pVector->x.pList->a[i].pExpr;
110901 ** the iField-th column of the vector expression pVector.
110921 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
110926 if( pVector->op==TK_SELECT ){
110933 ** iTable: 0 or the number of columns on the LHS of an assignment
110934 ** pLeft->iTable: First in an array of register holding result, or 0
110947 pRet->iTable = nField;
110948 pRet->iColumn = iField;
110949 pRet->pLeft = pVector;
110952 if( pVector->op==TK_VECTOR ){
110955 ppVector = &pVector->x.pList->a[iField].pExpr;
110963 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
110971 ** sub-select returns more than one column, the first in an array
110979 if( pExpr->op==TK_SELECT ){
110987 ** Argument pVector points to a vector expression - either a TK_VECTOR
110994 ** case parameter regSelect should be the first in an array of registers
110995 ** containing the results of the sub-select.
111012 u8 op = pVector->op;
111016 return pVector->iTable+iField;
111020 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
111025 *ppExpr = pVector->x.pList->a[iField].pExpr;
111038 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
111039 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
111040 ** otherwise: op==pExpr->op and p5==0
111049 Vdbe *v = pParse->pVdbe;
111050 Expr *pLeft = pExpr->pLeft;
111051 Expr *pRight = pExpr->pRight;
111062 if( pParse->nErr ) return;
111067 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
111068 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
111069 || pExpr->op==TK_LT || pExpr->op==TK_GT
111070 || pExpr->op==TK_LE || pExpr->op==TK_GE
111072 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
111073 || (pExpr->op==TK_ISNOT && op==TK_NE) );
111074 assert( p5==0 || pExpr->op!=op );
111075 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
111103 if( (opx==TK_LT || opx==TK_GT) && i<nLeft-1 ){
111113 if( i==nLeft-1 ){
111121 if( i==nLeft-2 ) opx = op;
111134 ** expression depth allowed. If it is not, leave an error message in
111139 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
111160 if( p->nHeight>*pnHeight ){
111161 *pnHeight = p->nHeight;
111168 for(i=0; i<p->nExpr; i++){
111169 heightOfExpr(p->a[i].pExpr, pnHeight);
111175 for(p=pSelect; p; p=p->pPrior){
111176 heightOfExpr(p->pWhere, pnHeight);
111177 heightOfExpr(p->pHaving, pnHeight);
111178 heightOfExpr(p->pLimit, pnHeight);
111179 heightOfExprList(p->pEList, pnHeight);
111180 heightOfExprList(p->pGroupBy, pnHeight);
111181 heightOfExprList(p->pOrderBy, pnHeight);
111186 ** Set the Expr.nHeight variable in the structure passed as an
111187 ** argument. An expression with no children, Expr.pList or
111196 int nHeight = p->pLeft ? p->pLeft->nHeight : 0;
111197 if( NEVER(p->pRight) && p->pRight->nHeight>nHeight ){
111198 nHeight = p->pRight->nHeight;
111201 heightOfSelect(p->x.pSelect, &nHeight);
111202 }else if( p->x.pList ){
111203 heightOfExprList(p->x.pList, &nHeight);
111204 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
111206 p->nHeight = nHeight + 1;
111212 ** leave an error in pParse.
111218 if( pParse->nErr ) return;
111220 sqlite3ExprCheckHeight(pParse, p->nHeight);
111225 ** by the select statement passed as an argument.
111238 if( pParse->nErr ) return;
111239 if( p && ExprUseXList(p) && p->x.pList ){
111240 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
111247 ** Set the error offset for an Expr node, if possible.
111252 pExpr->w.iOfst = iOfst;
111266 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
111269 ** Special case (tag-20240227-a): If op==TK_INTEGER and pToken points to
111270 ** a string that can be translated into a 32-bit integer, then the token is
111274 ** See also tag-20240227-b.
111288 if( op!=TK_INTEGER || pToken->z==0
111289 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
111290 nExtra = pToken->n+1; /* tag-20240227-a */
111297 pNew->op = (u8)op;
111298 pNew->iAgg = -1;
111301 pNew->flags |= EP_IntValue|EP_Leaf|(iValue?EP_IsTrue:EP_IsFalse);
111302 pNew->u.iValue = iValue;
111304 pNew->u.zToken = (char*)&pNew[1];
111305 assert( pToken->z!=0 || pToken->n==0 );
111306 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
111307 pNew->u.zToken[pToken->n] = 0;
111308 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
111314 pNew->nHeight = 1;
111321 ** Allocate a new expression node from a zero-terminated token that has
111348 assert( db->mallocFailed );
111353 assert( pRoot->x.pSelect==0 );
111355 pRoot->pRight = pRight;
111356 pRoot->flags |= EP_Propagate & pRight->flags;
111358 pRoot->nHeight = pRight->nHeight+1;
111360 pRoot->nHeight = 1;
111364 pRoot->pLeft = pLeft;
111365 pRoot->flags |= EP_Propagate & pLeft->flags;
111367 if( pLeft->nHeight>=pRoot->nHeight ){
111368 pRoot->nHeight = pLeft->nHeight+1;
111376 ** Allocate an Expr node which joins as many as two subtrees.
111379 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
111389 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
111392 p->op = op & 0xff;
111393 p->iAgg = -1;
111394 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
111395 sqlite3ExprCheckHeight(pParse, p->nHeight);
111397 sqlite3ExprDelete(pParse->db, pLeft);
111398 sqlite3ExprDelete(pParse->db, pRight);
111409 pExpr->x.pSelect = pSelect;
111413 assert( pParse->db->mallocFailed );
111414 sqlite3SelectDelete(pParse->db, pSelect);
111432 ** an error message is left in pParse.
111441 for(ii=0; ii<pEList->nExpr; ii++){
111443 Expr *pExpr = pEList->a[ii].pExpr;
111445 if( pExpr->op==TK_VECTOR ){
111447 nExprElem = pExpr->x.pList->nExpr;
111452 sqlite3ErrorMsg(pParse, "IN(...) element has %d term%s - expected %d",
111458 pSel = sqlite3SelectNew(pParse, pExpr->x.pList, 0, 0, 0, 0, 0, SF_Values,0);
111459 pExpr->x.pList = 0;
111462 pSel->op = TK_ALL;
111463 pSel->pPrior = pRet;
111469 if( pRet && pRet->pPrior ){
111470 pRet->selFlags |= SF_MultiValue;
111472 sqlite3ExprListDelete(pParse->db, pEList);
111477 ** Join two expressions using an AND operator. If either expression is
111481 ** is part of an ON clause, then instead of returning an AND expression,
111485 sqlite3 *db = pParse->db;
111491 u32 f = pLeft->flags | pRight->flags;
111515 sqlite3 *db = pParse->db;
111523 pNew->w.iOfst = (int)(pToken->z - pParse->zTail);
111525 && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG]
111526 && !pParse->nested
111530 pNew->x.pList = pList;
111539 ** Report an error when attempting to use an ORDER BY clause within
111540 ** the arguments of a non-aggregate function.
111544 "ORDER BY may not be used with non-aggregate %#T()", p
111549 ** Attach an ORDER BY clause to a function call.
111564 sqlite3 *db = pParse->db;
111566 assert( db->mallocFailed );
111570 assert( db->mallocFailed );
111574 assert( pExpr->op==TK_FUNCTION );
111575 assert( pExpr->pLeft==0 );
111577 if( pExpr->x.pList==0 || NEVER(pExpr->x.pList->nExpr==0) ){
111578 /* Ignore ORDER BY on zero-argument aggregates */
111593 pOB->x.pList = pOrderBy;
111595 pExpr->pLeft = pOB;
111603 ** SQLITE_FUNC_DIRECT - Only usable from top-level SQL
111605 ** SQLITE_FUNC_UNSAFE - Usable if TRUSTED_SCHEMA or from
111606 ** top-level SQL
111608 ** If the function is not usable, create an error.
111616 assert( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0 );
111618 if( (pDef->funcFlags & SQLITE_FUNC_DIRECT)!=0
111619 || (pParse->db->flags & SQLITE_TrustedSchema)==0
111634 ** Assign a variable number to an expression that encodes a wildcard
111642 ** the SQL statement comes from an external source.
111650 sqlite3 *db = pParse->db;
111656 z = pExpr->u.zToken;
111663 x = (ynVar)(++pParse->nVar);
111667 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
111671 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
111672 i = z[1]-'0'; /* The common case of ?N for a single digit N */
111675 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
111679 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
111680 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
111681 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
111683 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
111684 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
111688 if( x>pParse->nVar ){
111689 pParse->nVar = (int)x;
111691 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
111699 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
111701 x = (ynVar)(++pParse->nVar);
111706 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
111709 pExpr->iColumn = x;
111710 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
111712 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
111717 ** Recursively delete an expression tree.
111723 assert( !ExprUseUValue(p) || p->u.iValue>=0 );
111725 assert( !ExprUseYWin(p) || p->y.pWin!=0 || db->mallocFailed );
111726 assert( p->op!=TK_FUNCTION || !ExprUseYSub(p) );
111729 assert( p->pLeft==0 );
111730 assert( p->pRight==0 );
111731 assert( !ExprUseXSelect(p) || p->x.pSelect==0 );
111732 assert( !ExprUseXList(p) || p->x.pList==0 );
111737 assert( (ExprUseXList(p) && p->x.pList==0) || p->pRight==0 );
111738 if( p->pRight ){
111740 sqlite3ExprDeleteNN(db, p->pRight);
111743 sqlite3SelectDelete(db, p->x.pSelect);
111745 sqlite3ExprListDelete(db, p->x.pList);
111748 sqlite3WindowDelete(db, p->y.pWin);
111752 if( p->pLeft && p->op!=TK_SELECT_COLUMN ){
111753 Expr *pLeft = p->pLeft;
111778 ** Clear both elements of an OnOrUsing object
111783 }else if( p->pOn ){
111784 sqlite3ExprDeleteNN(db, p->pOn);
111785 }else if( p->pUsing ){
111786 sqlite3IdListDelete(db, p->pUsing);
111795 ** The pExpr might be deleted immediately on an OOM error.
111797 ** Return 0 if the delete was successfully deferred. Return non-zero
111798 ** if the delete happened immediately because of an OOM.
111812 sqlite3ExprDeleteNN(pParse->db, p);
111829 ** to store a copy of an expression or expression tree. They differ in
111838 ** The dupedExprStructSize() function returns two values OR-ed together:
111851 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
111856 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
111872 if( p->pLeft || p->x.pList ){
111875 assert( p->pRight==0 );
111889 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
111890 nByte += sqlite3Strlen30NN(p->u.zToken)+1;
111910 if( p->pLeft ) nByte += dupedExprSize(p->pLeft);
111911 if( p->pRight ) nByte += dupedExprSize(p->pRight);
111917 ** An EdupBuf is a memory allocation used to stored multiple Expr objects
111919 ** compression while doing sqlite3ExprDup(). The top-level Expr does the
111920 ** allocation for itself and many of its decendents, then passes an instance
111935 ** of the input Expr p together with its p->u.zToken (if any). pEdupBuf
111947 int nToken = -1; /* Space needed for p->u.zToken. -1 means unknown */
111956 sEdupBuf.zAlloc = pEdupBuf->zAlloc;
111958 sEdupBuf.zEnd = pEdupBuf->zEnd;
111967 }else if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
111968 nToken = sqlite3Strlen30NN(p->u.zToken)+1;
111989 ** by the copy of the p->u.zToken string (if any).
111994 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
111995 nToken = sqlite3Strlen30(p->u.zToken) + 1;
112001 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >= nNewSize+nToken );
112006 assert( (int)(sEdupBuf.zEnd - sEdupBuf.zAlloc) >=
112010 memset(&sEdupBuf.zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
112016 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
112017 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
112018 pNew->flags |= staticFlag;
112024 /* Copy the p->u.zToken string, if any. */
112027 char *zToken = pNew->u.zToken = (char*)&sEdupBuf.zAlloc[nNewSize];
112028 memcpy(zToken, p->u.zToken, nToken);
112033 if( ((p->flags|pNew->flags)&(EP_TokenOnly|EP_Leaf))==0 ){
112035 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
112037 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
112039 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList,
112040 p->op!=TK_ORDER ? dupFlags : 0);
112045 pNew->y.pWin = sqlite3WindowDup(db, pNew, p->y.pWin);
112050 /* Fill in pNew->pLeft and pNew->pRight. */
112052 if( p->op==TK_SELECT_COLUMN ){
112053 pNew->pLeft = p->pLeft;
112054 assert( p->pRight==0
112055 || p->pRight==p->pLeft
112056 || ExprHasProperty(p->pLeft, EP_Subquery) );
112058 pNew->pLeft = p->pLeft ?
112059 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &sEdupBuf) : 0;
112061 pNew->pRight = p->pRight ?
112062 exprDup(db, p->pRight, EXPRDUP_REDUCE, &sEdupBuf) : 0;
112064 if( p->op==TK_SELECT_COLUMN ){
112065 pNew->pLeft = p->pLeft;
112066 assert( p->pRight==0
112067 || p->pRight==p->pLeft
112068 || ExprHasProperty(p->pLeft, EP_Subquery) );
112070 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
112072 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
112083 ** argument. If an OOM condition is encountered, NULL is returned
112084 ** and the db->mallocFailed flag set.
112090 sqlite3_int64 nByte = SZ_WITH(p->nCte);
112094 pRet->nCte = p->nCte;
112095 for(i=0; i<p->nCte; i++){
112096 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
112097 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
112098 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
112099 pRet->a[i].eM10d = p->a[i].eM10d;
112113 ** an a newly duplicated SELECT statement and gather all of the Window
112114 ** objects found there, assembling them onto the linked list at Select->pWin.
112117 if( pExpr->op==TK_FUNCTION && ExprHasProperty(pExpr, EP_WinFunc) ){
112118 Select *pSelect = pWalker->u.pSelect;
112119 Window *pWin = pExpr->y.pWin;
112122 assert( pWin->ppThis==0 );
112128 return p==pWalker->u.pSelect ? WRC_Continue : WRC_Prune;
112157 ** part of the in-memory representation of the database schema.
112174 pNew->nExpr = p->nExpr;
112175 pNew->nAlloc = p->nAlloc;
112176 pItem = pNew->a;
112177 pOldItem = p->a;
112178 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
112179 Expr *pOldExpr = pOldItem->pExpr;
112181 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
112183 && pOldExpr->op==TK_SELECT_COLUMN
112184 && (pNewExpr = pItem->pExpr)!=0
112186 if( pNewExpr->pRight ){
112187 pPriorSelectColOld = pOldExpr->pRight;
112188 pPriorSelectColNew = pNewExpr->pRight;
112189 pNewExpr->pLeft = pNewExpr->pRight;
112191 if( pOldExpr->pLeft!=pPriorSelectColOld ){
112192 pPriorSelectColOld = pOldExpr->pLeft;
112194 pNewExpr->pRight = pPriorSelectColNew;
112196 pNewExpr->pLeft = pPriorSelectColNew;
112199 pItem->zEName = sqlite3DbStrDup(db, pOldItem->zEName);
112200 pItem->fg = pOldItem->fg;
112201 pItem->u = pOldItem->u;
112219 pNew = sqlite3DbMallocRawNN(db, SZ_SRCLIST(p->nSrc) );
112221 pNew->nSrc = pNew->nAlloc = p->nSrc;
112222 for(i=0; i<p->nSrc; i++){
112223 SrcItem *pNewItem = &pNew->a[i];
112224 const SrcItem *pOldItem = &p->a[i];
112226 pNewItem->fg = pOldItem->fg;
112227 if( pOldItem->fg.isSubquery ){
112230 assert( db->mallocFailed );
112231 pNewItem->fg.isSubquery = 0;
112233 memcpy(pNewSubq, pOldItem->u4.pSubq, sizeof(*pNewSubq));
112234 pNewSubq->pSelect = sqlite3SelectDup(db, pNewSubq->pSelect, flags);
112235 if( pNewSubq->pSelect==0 ){
112238 pNewItem->fg.isSubquery = 0;
112241 pNewItem->u4.pSubq = pNewSubq;
112242 }else if( pOldItem->fg.fixedSchema ){
112243 pNewItem->u4.pSchema = pOldItem->u4.pSchema;
112245 pNewItem->u4.zDatabase = sqlite3DbStrDup(db, pOldItem->u4.zDatabase);
112247 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
112248 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
112249 pNewItem->iCursor = pOldItem->iCursor;
112250 if( pNewItem->fg.isIndexedBy ){
112251 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
112252 }else if( pNewItem->fg.isTabFunc ){
112253 pNewItem->u1.pFuncArg =
112254 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
112256 pNewItem->u1.nRow = pOldItem->u1.nRow;
112258 pNewItem->u2 = pOldItem->u2;
112259 if( pNewItem->fg.isCte ){
112260 pNewItem->u2.pCteUse->nUse++;
112262 pTab = pNewItem->pSTab = pOldItem->pSTab;
112264 pTab->nTabRef++;
112266 if( pOldItem->fg.isUsing ){
112267 assert( pNewItem->fg.isUsing );
112268 pNewItem->u3.pUsing = sqlite3IdListDup(db, pOldItem->u3.pUsing);
112270 pNewItem->u3.pOn = sqlite3ExprDup(db, pOldItem->u3.pOn, flags);
112272 pNewItem->colUsed = pOldItem->colUsed;
112281 pNew = sqlite3DbMallocRawNN(db, SZ_IDLIST(p->nId));
112283 pNew->nId = p->nId;
112284 for(i=0; i<p->nId; i++){
112285 struct IdList_item *pNewItem = &pNew->a[i];
112286 const struct IdList_item *pOldItem = &p->a[i];
112287 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
112298 for(p=pDup; p; p=p->pPrior){
112301 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
112302 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
112303 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
112304 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
112305 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
112306 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
112307 pNew->op = p->op;
112308 pNew->pNext = pNext;
112309 pNew->pPrior = 0;
112310 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
112311 pNew->iLimit = 0;
112312 pNew->iOffset = 0;
112313 pNew->selFlags = p->selFlags & ~(u32)SF_UsesEphemeral;
112314 pNew->addrOpenEphm[0] = -1;
112315 pNew->addrOpenEphm[1] = -1;
112316 pNew->nSelectRow = p->nSelectRow;
112317 pNew->pWith = sqlite3WithDup(db, p->pWith);
112319 pNew->pWin = 0;
112320 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
112321 if( p->pWin && db->mallocFailed==0 ) gatherSelectWindows(pNew);
112323 pNew->selId = p->selId;
112324 if( db->mallocFailed ){
112326 ** Delete the whole thing rather than allow an incomplete Select
112328 pNew->pNext = 0;
112333 pp = &pNew->pPrior;
112347 ** Add a new element to the end of an expression list. If pList is
112350 ** The pList argument must be either NULL or a pointer to an ExprList
112354 ** NULL is returned. If non-NULL is returned, then it is guaranteed
112370 pList->nAlloc = 4;
112371 pList->nExpr = 1;
112372 pItem = &pList->a[0];
112374 pItem->pExpr = pExpr;
112384 pList->nAlloc *= 2;
112385 pNew = sqlite3DbRealloc(db, pList, SZ_EXPRLIST(pList->nAlloc));
112393 pItem = &pList->a[pList->nExpr++];
112395 pItem->pExpr = pExpr;
112405 return sqlite3ExprListAppendNew(pParse->db,pExpr);
112407 if( pList->nAlloc<pList->nExpr+1 ){
112408 return sqlite3ExprListAppendGrow(pParse->db,pList,pExpr);
112410 pItem = &pList->a[pList->nExpr++];
112412 pItem->pExpr = pExpr;
112418 ** clause of an UPDATE statement. Like this:
112433 sqlite3 *db = pParse->db;
112436 int iFirst = pList ? pList->nExpr : 0;
112437 /* pColumns can only be NULL due to an OOM but an OOM will cause an
112447 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
112449 pColumns->nId, n);
112453 for(i=0; i<pColumns->nId; i++){
112454 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i, pColumns->nId);
112455 assert( pSubExpr!=0 || db->mallocFailed );
112459 assert( pList->nExpr==iFirst+i+1 );
112460 pList->a[pList->nExpr-1].zEName = pColumns->a[i].zName;
112461 pColumns->a[i].zName = 0;
112465 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
112466 Expr *pFirst = pList->a[iFirst].pExpr;
112468 assert( pFirst->op==TK_SELECT_COLUMN );
112472 pFirst->pRight = pExpr;
112477 pFirst->iTable = pColumns->nId;
112492 assert( p->nExpr>0 );
112504 pItem = &p->a[p->nExpr-1];
112505 assert( pItem->fg.bNulls==0 );
112509 pItem->fg.sortFlags = (u8)iSortOrder;
112512 pItem->fg.bNulls = 1;
112514 pItem->fg.sortFlags |= KEYINFO_ORDER_BIGNULL;
112523 ** pList might be NULL following an OOM error. But pName should never be
112524 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
112533 assert( pList!=0 || pParse->db->mallocFailed!=0 );
112534 assert( pParse->eParseMode!=PARSE_MODE_UNMAP || dequote==0 );
112537 assert( pList->nExpr>0 );
112538 pItem = &pList->a[pList->nExpr-1];
112539 assert( pItem->zEName==0 );
112540 assert( pItem->fg.eEName==ENAME_NAME );
112541 pItem->zEName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
112543 /* If dequote==0, then pName->z does not point to part of a DDL
112545 ** to the token-map. */
112546 sqlite3Dequote(pItem->zEName);
112548 sqlite3RenameTokenMap(pParse, (const void*)pItem->zEName, pName);
112558 ** pList might be NULL following an OOM error. But pSpan should never be
112559 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
112568 sqlite3 *db = pParse->db;
112569 assert( pList!=0 || db->mallocFailed!=0 );
112571 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
112572 assert( pList->nExpr>0 );
112573 if( pItem->zEName==0 ){
112574 pItem->zEName = sqlite3DbSpanDup(db, zStart, zEnd);
112575 pItem->fg.eEName = ENAME_SPAN;
112582 ** leave an error message in pParse.
112589 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
112590 testcase( pEList && pEList->nExpr==mx );
112591 testcase( pEList && pEList->nExpr==mx+1 );
112592 if( pEList && pEList->nExpr>mx ){
112598 ** Delete an entire expression list.
112601 int i = pList->nExpr;
112602 struct ExprList_item *pItem = pList->a;
112603 assert( pList->nExpr>0 );
112606 sqlite3ExprDelete(db, pItem->pExpr);
112607 if( pItem->zEName ) sqlite3DbNNFreeNN(db, pItem->zEName);
112609 }while( --i>0 );
112620 ** Return the bitwise-OR of all Expr.flags fields in the given
112627 for(i=0; i<pList->nExpr; i++){
112628 Expr *pExpr = pList->a[i].pExpr;
112630 m |= pExpr->flags;
112636 ** This is a SELECT-node callback for the expression walker that
112638 ** pWalker->eCode to zero and abort.
112644 pWalker->eCode = 0;
112664 ** If the input expression is an ID with the name "true" or "false"
112665 ** then convert it into an TK_TRUEFALSE term. Return non-zero if
112670 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
112672 && (v = sqlite3IsTrueOrFalse(pExpr->u.zToken))!=0
112674 pExpr->op = TK_TRUEFALSE;
112687 assert( pExpr->op==TK_TRUEFALSE );
112689 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
112690 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
112691 return pExpr->u.zToken[4]==0;
112695 ** If pExpr is an AND or OR expression, try to simplify it by eliminating
112709 if( pExpr->op==TK_AND || pExpr->op==TK_OR ){
112710 Expr *pRight = sqlite3ExprSimplifiedAndOr(pExpr->pRight);
112711 Expr *pLeft = sqlite3ExprSimplifiedAndOr(pExpr->pLeft);
112713 pExpr = pExpr->op==TK_AND ? pRight : pLeft;
112715 pExpr = pExpr->op==TK_AND ? pLeft : pRight;
112726 ** (1) It is a scalar function (not an aggregate or window function)
112731 ** This routine sets pWalker->eCode to 0 if pExpr is not a constant.
112732 ** It makes no changes to pWalker->eCode if pExpr is constant. In
112746 assert( pExpr->op==TK_FUNCTION );
112748 || (pList = pExpr->x.pList)==0
112752 n = pList->nExpr;
112754 if( pWalker->eCode==0 ) return WRC_Abort;
112756 db = pWalker->pParse->db;
112757 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
112759 || pDef->xFinalize!=0
112760 || (pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG))==0
112763 pWalker->eCode = 0;
112778 ** sqlite3ExprIsConstant() pWalker->eCode==1
112779 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
112780 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
112781 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
112788 ** when parsing an existing schema out of the sqlite_schema table and 4
112790 ** an error for new statements, but is silently converted
112797 assert( pWalker->eCode>0 );
112799 /* If pWalker->eCode is 2 then any term of the expression that comes from
112800 ** the ON or USING clauses of an outer join disqualifies the expression
112802 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_OuterON) ){
112803 pWalker->eCode = 0;
112807 switch( pExpr->op ){
112809 ** and either pWalker->eCode==4 or 5 or the function has the
112812 if( (pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc))
112815 if( pWalker->eCode==5 ) ExprSetProperty(pExpr, EP_FromDDL);
112817 }else if( pWalker->pParse ){
112820 pWalker->eCode = 0;
112833 testcase( pExpr->op==TK_ID );
112834 testcase( pExpr->op==TK_COLUMN );
112835 testcase( pExpr->op==TK_AGG_FUNCTION );
112836 testcase( pExpr->op==TK_AGG_COLUMN );
112837 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
112840 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
112848 testcase( pExpr->op==TK_REGISTER );
112849 testcase( pExpr->op==TK_IF_NULL_ROW );
112850 testcase( pExpr->op==TK_DOT );
112851 testcase( pExpr->op==TK_RAISE );
112852 pWalker->eCode = 0;
112855 if( pWalker->eCode==5 ){
112859 pExpr->op = TK_NULL;
112860 }else if( pWalker->eCode==4 ){
112862 ** sqlite3_prepare() causes an error */
112863 pWalker->eCode = 0;
112868 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
112869 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
112887 ** Walk an expression tree. Return non-zero if the expression is constant
112890 ** For the purposes of this function, a double-quoted string (ex: "abc")
112891 ** is considered a variable but a single-quoted string (ex: 'abc') is
112896 ** function calls will be considered to be non-constant. If pParse is
112905 ** Walk an expression tree. Return non-zero if
112914 ** can be added to the pParse->pConstExpr list and evaluated once when
112922 ** This routine examines sub-SELECT statements as an expression is being
112923 ** walked as part of sqlite3ExprIsTableConstant(). Sub-SELECTs are considered
112924 ** constant as long as they are uncorrelated - meaning that they do not
112929 assert( pWalker->eCode==3 || pWalker->eCode==0 );
112930 if( (pSelect->selFlags & SF_Correlated)!=0 ){
112931 pWalker->eCode = 0;
112938 ** Walk an expression tree. Return non-zero if the expression is constant
112940 ** expression must not refer to any non-deterministic function nor any
112965 ** Check pExpr to see if it is an constraint on the single data source
112966 ** pSrc = &pSrcList->a[iSrc]. In other words, check to see if pExpr
112968 ** sources anywhere else in the query. Return true (non-zero) if pExpr
112971 ** This is an optimization. False negatives will perhaps cause slower
112975 ** To be an single-source constraint, the following must be true:
112977 ** (1) pExpr cannot refer to any table other than pSrc->iCursor.
112980 ** true and the subquery is non-correlated
112982 ** (2b) pExpr cannot use non-deterministic functions.
112988 ** (4a) pExpr must come from an ON clause..
112993 ** clause, not an ON clause.
112997 ** (6a) pExpr does not originate in an ON or USING clause, or
113002 ** Without this restriction, accepting pExpr as a single-table
113006 ** on push-down.
113012 int bAllowSubq /* Allow non-correlated subqueries */
113014 const SrcItem *pSrc = &pSrcList->a[iSrc];
113015 if( pSrc->fg.jointype & JT_LTORJ ){
113018 if( pSrc->fg.jointype & JT_LEFT ){
113020 if( pExpr->w.iJoin!=pSrc->iCursor ) return 0; /* rule (4b) */
113025 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (6b) */
113029 if( pExpr->w.iJoin==pSrcList->a[jj].iCursor ){
113030 if( (pSrcList->a[jj].fg.jointype & JT_LTORJ)!=0 ){
113038 return sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor, bAllowSubq);
113046 ExprList *pGroupBy = pWalker->u.pGroupBy;
113051 for(i=0; i<pGroupBy->nExpr; i++){
113052 Expr *p = pGroupBy->a[i].pExpr;
113053 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
113054 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
113061 /* Check if pExpr is a sub-select. If so, consider it variable. */
113063 pWalker->eCode = 0;
113071 ** Walk the expression tree passed as the first argument. Return non-zero
113079 ** assumes that no other collating sequence will have a finer-grained
113085 ** alternative collating sequences are uncommon, and this is only an
113101 ** Walk an expression tree for the DEFAULT field of a column definition
113102 ** in a CREATE TABLE statement. Return non-zero if the expression is
113103 ** acceptable for use as a DEFAULT. That is to say, return non-zero if
113110 ** isInit is false, parameters raise an error. Parameters should not be
113117 ** For the purposes of this function, a double-quoted string (ex: "abc")
113118 ** is considered a variable but a single-quoted string (ex: 'abc') is
113128 ** Walk an expression tree. Return 1 if the expression contains a
113146 ** to fit in a 32-bit integer, return 1 and put the value of the integer
113147 ** in *pValue. If the expression is not an integer or if it is too big
113148 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
113151 ** a parameter (TK_VARIABLE) that is bound to an integer.
113158 /* If an expression is an integer literal that fits in a signed 32-bit
113160 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
113161 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
113163 if( p->flags & EP_IntValue ){
113164 *pValue = p->u.iValue;
113167 switch( p->op ){
113169 rc = sqlite3ExprIsInteger(p->pLeft, pValue, 0);
113174 if( sqlite3ExprIsInteger(p->pLeft, &v, 0) ){
113176 *pValue = -v;
113184 if( NEVER(pParse->pVdbe==0) ) break;
113185 if( (pParse->db->flags & SQLITE_EnableQPSG)!=0 ) break;
113186 sqlite3VdbeSetVarmask(pParse->pVdbe, p->iColumn);
113187 pVal = sqlite3VdbeGetBoundValue(pParse->pReprepare, p->iColumn,
113192 if( vv == (vv & 0x7fffffff) ){ /* non-negative numbers only */
113212 ** This routine is used as an optimization, to skip OP_IsNull opcodes
113217 ** will likely result in an incorrect answer. So when in doubt, return
113223 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
113224 p = p->pLeft;
113227 op = p->op;
113228 if( op==TK_REGISTER ) op = p->op2;
113238 || NEVER(p->y.pTab==0) /* Reference to column of index on expr */
113240 || (p->iColumn==XN_ROWID && IsView(p->y.pTab))
113242 || (p->iColumn>=0
113243 && p->y.pTab->aCol!=0 /* Possible due to prior error */
113244 && ALWAYS(p->iColumn<p->y.pTab->nCol)
113245 && p->y.pTab->aCol[p->iColumn].notNull==0);
113265 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){
113266 if( p->op==TK_UMINUS ) unaryMinus = 1;
113267 p = p->pLeft;
113269 op = p->op;
113270 if( op==TK_REGISTER ) op = p->op2;
113285 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
113286 return aff>=SQLITE_AFF_NUMERIC && p->iColumn<0;
113295 ** Return TRUE if the given string is a row-id column name.
113306 ** pTab. An alias is usable if there is not an explicit user-defined column
113320 ** pX is the RHS of an IN operator. If pX is a SELECT statement
113335 p = pX->x.pSelect;
113336 if( p->pPrior ) return 0; /* Not a compound SELECT */
113337 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
113338 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
113339 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
113342 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
113343 if( p->pLimit ) return 0; /* Has no LIMIT clause */
113344 if( p->pWhere ) return 0; /* Has no WHERE clause */
113345 pSrc = p->pSrc;
113347 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
113348 if( pSrc->a[0].fg.isSubquery) return 0;/* FROM is not a subquery or view */
113349 pTab = pSrc->a[0].pSTab;
113353 pEList = p->pEList;
113356 for(i=0; i<pEList->nExpr; i++){
113357 Expr *pRes = pEList->a[i].pExpr;
113358 if( pRes->op!=TK_COLUMN ) return 0;
113359 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
113367 ** Generate code that checks the left-most column of index table iCur to see if
113369 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
113386 ** The argument is an IN operator with a list (not a subquery) on the
113387 ** right-hand side. Return TRUE if that list is constant.
113393 pLHS = pIn->pLeft;
113394 pIn->pLeft = 0;
113396 pIn->pLeft = pLHS;
113406 ** The job of this routine is to find or create a b-tree object that can
113410 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
113413 ** The returned value of this function indicates the b-tree type, as follows:
113415 ** IN_INDEX_ROWID - The cursor was opened on a database table.
113416 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
113417 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
113418 ** IN_INDEX_EPH - The cursor was opened on a specially created and
113420 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
113423 ** An existing b-tree might be used if the RHS expression pX is a simple
113429 ** an ephemeral table might need to be generated from the RHS and then
113430 ** pX->iTable made to point to the ephemeral table instead of an
113433 ** will be set on pX and the pX->y.sub fields will be set to show where
113442 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
113443 ** through the set members) then the b-tree must not contain duplicates.
113444 ** An ephemeral table will be created unless the selected columns are guaranteed
113445 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
113448 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
113449 ** for fast set membership tests) then an ephemeral table must
113450 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
113451 ** index can be found with the specified <columns> as its left-most.
113455 ** routine might decide that creating an ephemeral b-tree for membership
113460 ** When the b-tree is being used for membership tests, the calling function
113469 ** the value in that register will be NULL if the b-tree contains one or more
113470 ** NULL values, and it will be some non-NULL value if the b-tree contains no
113473 ** If the aiMap parameter is not NULL, it must point to an array containing
113499 assert( pX->op==TK_IN );
113501 iTab = pParse->nTab++;
113510 ExprList *pEList = pX->x.pSelect->pEList;
113511 for(i=0; i<pEList->nExpr; i++){
113512 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
113514 if( i==pEList->nExpr ){
113519 /* Check to see if an existing table or index can be used to
113522 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
113523 sqlite3 *db = pParse->db; /* Database connection */
113526 ExprList *pEList = p->pEList;
113527 int nExpr = pEList->nExpr;
113529 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
113530 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
113531 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
113532 pTab = p->pSrc->a[0].pSTab;
113534 /* Code an OP_Transaction and OP_TableLock for <table>. */
113535 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
113538 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
113541 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
113549 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
113561 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
113562 int iCol = pEList->a[i].pExpr->iColumn;
113583 /* Search for an existing index that will work for this IN operator */
113584 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
113587 if( pIdx->nColumn<nExpr ) continue;
113588 if( pIdx->pPartIdxWhere!=0 ) continue;
113589 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
113591 testcase( pIdx->nColumn==BMS-2 );
113592 testcase( pIdx->nColumn==BMS-1 );
113593 if( pIdx->nColumn>=BMS-1 ) continue;
113595 if( pIdx->nKeyCol>nExpr
113596 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
113604 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
113605 Expr *pRhs = pEList->a[i].pExpr;
113610 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
113611 assert( pIdx->azColl[j] );
113612 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
113625 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
113626 if( colUsed==(MASKBIT(nExpr)-1) ){
113630 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
113631 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
113633 VdbeComment((v, "%s", pIdx->zName));
113635 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
113639 i64 mask = (1<<nExpr)-1;
113643 *prRhsHasNull = ++pParse->nMem;
113652 } /* End if not an rowid index */
113653 } /* End attempt to optimize using an index */
113656 ** and IN_INDEX_NOOP is an allowed reply
113659 ** then it is not worth creating an ephemeral table to evaluate
113665 && (!sqlite3InRhsIsConstant(pParse,pX) || pX->x.pList->nExpr<=2)
113667 pParse->nTab--; /* Back out the allocation of the unused cursor */
113668 iTab = -1; /* Cursor is not allocated */
113673 /* Could not find an existing table or index to use as the RHS b-tree.
113674 ** We will have to generate an ephemeral table to do the job.
113676 u32 savedNQueryLoop = pParse->nQueryLoop;
113680 pParse->nQueryLoop = 0;
113682 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
113684 assert( pX->op==TK_IN );
113689 pParse->nQueryLoop = savedNQueryLoop;
113694 n = sqlite3ExprVectorSize(pX->pLeft);
113704 ** Argument pExpr is an (?, ?...) IN(...) expression. This
113705 ** function allocates and returns a nul-terminated string containing
113712 Expr *pLeft = pExpr->pLeft;
113714 Select *pSelect = ExprUseXSelect(pExpr) ? pExpr->x.pSelect : 0;
113717 assert( pExpr->op==TK_IN );
113718 zRet = sqlite3DbMallocRaw(pParse->db, 1+(i64)nVal);
113725 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
113738 ** Load the Parse object passed as the first argument with an error
113741 ** "sub-select returns N columns - expected M"
113744 if( pParse->nErr==0 ){
113745 const char *zFmt = "sub-select returns %d columns - expected %d";
113753 ** it is not permitted. If pExpr is a sub-select vector, this routine
113756 ** "sub-select returns N columns - expected 1"
113765 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
113775 ** Scan all previously generated bytecode looking for an OP_BeginSubrtn
113789 if( (pParse->mSubrtnSig & (1<<(pNewSig->selId&7)))==0 ) return 0;
113790 assert( pExpr->op==TK_IN );
113793 assert( pExpr->x.pSelect!=0 );
113794 assert( (pExpr->x.pSelect->selFlags & SF_All)==0 );
113795 v = pParse->pVdbe;
113800 if( pOp->p4type!=P4_SUBRTNSIG ) continue;
113801 assert( pOp->opcode==OP_BeginSubrtn );
113802 pSig = pOp->p4.pSubrtnSig;
113804 if( !pSig->bComplete ) continue;
113805 if( pNewSig->selId!=pSig->selId ) continue;
113806 if( strcmp(pNewSig->zAff,pSig->zAff)!=0 ) continue;
113807 pExpr->y.sub.iAddr = pSig->iAddr;
113808 pExpr->y.sub.regReturn = pSig->regReturn;
113809 pExpr->iTable = pSig->iTable;
113819 ** Generate code that will construct an ephemeral table containing all terms
113820 ** in the RHS of an IN operator. The IN operator can be in either of two
113823 ** x IN (4,5,11) -- IN operator with list on right-hand side
113824 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
113828 ** table is computed, the cursor number is also stored in pExpr->iTable,
113853 v = pParse->pVdbe;
113859 ** * The right-hand side is a correlated subquery
113860 ** * The right-hand side is an expression list containing variables
113866 if( !ExprHasProperty(pExpr, EP_VarSelect) && pParse->iSelfTab==0 ){
113872 assert( !ExprUseXSelect(pExpr) || pExpr->x.pSelect!=0 );
113873 if( ExprUseXSelect(pExpr) && (pExpr->x.pSelect->selFlags & SF_All)==0 ){
113874 pSig = sqlite3DbMallocRawNN(pParse->db, sizeof(pSig[0]));
113876 pSig->selId = pExpr->x.pSelect->selId;
113877 pSig->zAff = exprINAffinity(pParse, pExpr);
113891 pExpr->x.pSelect->selId));
113894 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
113895 pExpr->y.sub.iAddr);
113896 assert( iTab!=pExpr->iTable );
113897 sqlite3VdbeAddOp2(v, OP_OpenDup, iTab, pExpr->iTable);
113900 sqlite3DbFree(pParse->db, pSig->zAff);
113901 sqlite3DbFree(pParse->db, pSig);
113910 pExpr->y.sub.regReturn = ++pParse->nMem;
113911 pExpr->y.sub.iAddr =
113912 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
113914 pSig->bComplete = 0;
113915 pSig->iAddr = pExpr->y.sub.iAddr;
113916 pSig->regReturn = pExpr->y.sub.regReturn;
113917 pSig->iTable = iTab;
113918 pParse->mSubrtnSig = 1 << (pSig->selId&7);
113919 sqlite3VdbeChangeP4(v, -1, (const char*)pSig, P4_SUBRTNSIG);
113925 pLeft = pExpr->pLeft;
113931 pExpr->iTable = iTab;
113932 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, nVal);
113935 VdbeComment((v, "Result of SELECT %u", pExpr->x.pSelect->selId));
113940 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
113948 Select *pSelect = pExpr->x.pSelect;
113949 ExprList *pEList = pSelect->pEList;
113952 addrOnce?"":"CORRELATED ", pSelect->selId
113956 if( ALWAYS(pEList->nExpr==nVal) ){
113964 pSelect->iLimit = 0;
113965 if( addrOnce && OptimizationEnabled(pParse->db, SQLITE_BloomFilter) ){
113966 int regBloom = ++pParse->nMem;
113971 testcase( pSelect->selFlags & SF_Distinct );
113973 pCopy = sqlite3SelectDup(pParse->db, pSelect, 0);
113974 rc = pParse->db->mallocFailed ? 1 :sqlite3Select(pParse, pCopy, &dest);
113975 sqlite3SelectDelete(pParse->db, pCopy);
113976 sqlite3DbFree(pParse->db, dest.zAffSdst);
113979 ** of the OP_Once that began this subroutine. tag-202407032019 */
113980 sqlite3VdbeGetOp(v, addrOnce)->p3 = dest.iSDParm2;
113983 sqlite3VdbeGetOp(v, addrBloom)->p1 = 10;
113992 assert( pEList->nExpr>0 );
113996 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
113997 pParse, p, pEList->a[i].pExpr
114001 }else if( ALWAYS(pExpr->x.pList!=0) ){
114004 ** For each expression, build an index key from the evaluation and
114011 ExprList *pList = pExpr->x.pList;
114022 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
114028 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
114029 Expr *pE2 = pItem->pExpr;
114033 ** this code only executes once. Because for a non-constant
114037 sqlite3VdbeChangeToNoop(v, addrOnce-1);
114051 if( pSig ) pSig->bComplete = 1;
114060 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
114061 || pParse->nErr );
114062 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
114063 pExpr->y.sub.iAddr, 1);
114074 ** (SELECT a FROM b) -- subquery
114075 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
114079 ** Return the register that holds the result. For a multi-column SELECT,
114081 ** return value is the register of the left-most result column.
114082 ** Return 0 if an error occurs.
114096 Vdbe *v = pParse->pVdbe;
114098 if( pParse->nErr ) return 0;
114099 testcase( pExpr->op==TK_EXISTS );
114100 testcase( pExpr->op==TK_SELECT );
114101 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
114103 pSel = pExpr->x.pSelect;
114108 ExplainQueryPlan((pParse, 0, "REUSE SUBQUERY %d", pSel->selId));
114110 sqlite3VdbeAddOp2(v, OP_Gosub, pExpr->y.sub.regReturn,
114111 pExpr->y.sub.iAddr);
114112 return pExpr->iTable;
114119 pExpr->y.sub.regReturn = ++pParse->nMem;
114120 pExpr->y.sub.iAddr =
114121 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pExpr->y.sub.regReturn) + 1;
114126 ** * The right-hand side is a correlated subquery
114127 ** * The right-hand side is an expression list containing variables
114138 ** the first row into an array of registers and return the index of
114141 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
114148 addrOnce?"":"CORRELATED ", pSel->selId));
114149 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, -1);
114150 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
114151 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
114152 pParse->nMem += nReg;
114153 if( pExpr->op==TK_SELECT ){
114157 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
114164 if( pSel->pLimit ){
114165 /* The subquery already has a limit. If the pre-existing limit is X
114167 sqlite3 *db = pParse->db;
114170 pLimit->affExpr = SQLITE_AFF_NUMERIC;
114172 sqlite3ExprDup(db, pSel->pLimit->pLeft, 0), pLimit);
114174 sqlite3ExprDeferredDelete(pParse, pSel->pLimit->pLeft);
114175 pSel->pLimit->pLeft = pLimit;
114177 /* If there is no pre-existing limit add a limit of 1 */
114178 pLimit = sqlite3Expr(pParse->db, TK_INTEGER, "1");
114179 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
114181 pSel->iLimit = 0;
114183 pExpr->op2 = pExpr->op;
114184 pExpr->op = TK_ERROR;
114187 pExpr->iTable = rReg = dest.iSDParm;
114192 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
114196 assert( sqlite3VdbeGetOp(v,pExpr->y.sub.iAddr-1)->opcode==OP_BeginSubrtn
114197 || pParse->nErr );
114198 sqlite3VdbeAddOp3(v, OP_Return, pExpr->y.sub.regReturn,
114199 pExpr->y.sub.iAddr, 1);
114208 ** Expr pIn is an IN(...) expression. This function checks that the
114209 ** sub-select on the RHS of the IN() operator has the same number of
114211 ** a sub-query, that the LHS is a vector of size 1.
114214 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
114215 if( ExprUseXSelect(pIn) && !pParse->db->mallocFailed ){
114216 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
114217 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
114221 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
114230 ** Generate code for an IN expression.
114235 ** The left-hand side (LHS) is a scalar or vector expression. The
114236 ** right-hand side (RHS) is an array of zero or more scalar values, or a
114251 ** See the separate in-operator.md documentation file in the canonical
114275 int addrTop; /* Top of the step-6 loop */
114277 u8 okConstFactor = pParse->okConstFactor;
114280 pLeft = pExpr->pLeft;
114283 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
114284 aiMap = (int*)sqlite3DbMallocZero(pParse->db, nVector*sizeof(int));
114285 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
114291 v = pParse->pVdbe;
114299 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
114304 ** nVector-1. */
114313 ** vector, then it is stored in an array of nVector registers starting
114317 ** so that the fields are in the same order as an existing index. The
114324 assert( pParse->okConstFactor==okConstFactor );
114325 pParse->okConstFactor = 0;
114327 pParse->okConstFactor = okConstFactor;
114340 /* If sqlite3FindInIndex() did not find or create an index that is
114344 ** This is step (1) in the in-operator.md optimized algorithm.
114354 pList = pExpr->x.pList;
114355 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
114360 for(ii=0; ii<pList->nExpr; ii++){
114361 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, ®ToFree);
114362 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
114366 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
114370 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_Eq);
114371 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_Eq);
114372 VdbeCoverageIf(v, ii<pList->nExpr-1 && op==OP_NotNull);
114373 VdbeCoverageIf(v, ii==pList->nExpr-1 && op==OP_NotNull);
114404 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
114405 if( pParse->nErr ) goto sqlite3ExprCodeIN_oom_error;
114412 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
114417 /* In this case, the RHS is the ROWID of table b-tree and so we also
114418 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
114428 const VdbeOp *pOp = sqlite3VdbeGetOp(v, pExpr->y.sub.iAddr);
114429 assert( pOp->opcode==OP_Once || pParse->nErr );
114430 if( pOp->opcode==OP_Once && pOp->p3>0 ){ /* tag-202407032019 */
114431 assert( OptimizationEnabled(pParse->db, SQLITE_BloomFilter) );
114432 sqlite3VdbeAddOp4Int(v, OP_Filter, pOp->p3, destIfFalse,
114445 /* Step 4. If the RHS is known to be non-NULL and we did not find
114446 ** an match on the search above, then the result must be FALSE.
114505 sqlite3DbFree(pParse->db, aiMap);
114506 sqlite3DbFree(pParse->db, zAff);
114512 ** Generate an instruction that will put the floating point
114513 ** value described by z[0..n-1] into register iMem.
114515 ** The z[] string will probably not be zero-terminated. But the
114524 if( negateFlag ) value = -value;
114532 ** Generate an instruction that will put the integer describe by
114533 ** text z[0..n-1] into register iMem.
114535 ** Expr.u.zToken is always UTF8 and zero-terminated.
114538 Vdbe *v = pParse->pVdbe;
114539 if( pExpr->flags & EP_IntValue ){
114540 int i = pExpr->u.iValue;
114542 if( negFlag ) i = -i;
114547 const char *z = pExpr->u.zToken;
114552 sqlite3ErrorMsg(pParse, "oversized integer: %s%#T", negFlag?"-":"",pExpr);
114557 negFlag?"-":"",pExpr);
114565 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
114573 ** appropriate for the iIdxCol-th column of index pIdx.
114582 i16 iTabCol = pIdx->aiColumn[iIdxCol];
114584 assert( pIdx->aColExpr );
114585 assert( pIdx->aColExpr->nExpr>iIdxCol );
114586 pParse->iSelfTab = iTabCur + 1;
114587 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
114588 pParse->iSelfTab = 0;
114590 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
114607 Vdbe *v = pParse->pVdbe;
114608 int nErr = pParse->nErr;
114610 assert( pParse->iSelfTab!=0 );
114611 if( pParse->iSelfTab>0 ){
114612 iAddr = sqlite3VdbeAddOp3(v, OP_IfNullRow, pParse->iSelfTab-1, 0, regOut);
114617 if( pCol->affinity>=SQLITE_AFF_TEXT ){
114618 sqlite3VdbeAddOp4(v, OP_Affinity, regOut, 1, 0, &pCol->affinity, 1);
114621 if( pParse->nErr>nErr ) pParse->db->errByteOffset = -1;
114626 ** Generate code to extract the value of the iCol-th column of a table.
114639 if( iCol<0 || iCol==pTab->iPKey ){
114641 VdbeComment((v, "%s.rowid", pTab->zName));
114649 }else if( (pCol = &pTab->aCol[iCol])->colFlags & COLFLAG_VIRTUAL ){
114651 if( pCol->colFlags & COLFLAG_BUSY ){
114653 pCol->zCnName);
114655 int savedSelfTab = pParse->iSelfTab;
114656 pCol->colFlags |= COLFLAG_BUSY;
114657 pParse->iSelfTab = iTabCur+1;
114659 pParse->iSelfTab = savedSelfTab;
114660 pCol->colFlags &= ~COLFLAG_BUSY;
114679 ** Generate code that will extract the iColumn-th column from
114682 ** There must be an open cursor to pTab in iTable when this routine
114693 assert( pParse->pVdbe!=0 );
114696 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pTab, iTable, iColumn, iReg);
114698 VdbeOp *pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
114699 if( pOp->opcode==OP_Column ) pOp->p5 = p5;
114700 if( pOp->opcode==OP_VColumn ) pOp->p5 = (p5 & OPFLAG_NOCHNG);
114706 ** Generate code to move content from registers iFrom...iFrom+nReg-1
114707 ** over to iTo..iTo+nReg-1.
114710 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
114721 if( p->op==TK_REGISTER ){
114722 assert( p->iTable==iReg );
114724 p->op2 = p->op;
114725 p->op = TK_REGISTER;
114726 p->iTable = iReg;
114732 ** Evaluate an expression (either a vector or a scalar expression) and store
114748 if( p->op==TK_SELECT ){
114756 iResult = pParse->nMem+1;
114757 pParse->nMem += nResult;
114760 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
114768 ** If the last opcode is a OP_Copy, then set the do-not-merge flag (p5)
114772 if( sqlite3VdbeGetLastOp(v)->opcode==OP_Copy ){
114779 ** in-line rather than by using the usual callbacks.
114788 Vdbe *v = pParse->pVdbe;
114791 nFarg = pFarg->nExpr;
114792 assert( nFarg>0 ); /* All in-line functions have at least one argument */
114795 /* Attempt a direct implementation of the built-in COALESCE() and
114797 ** arguments past the first non-NULL argument.
114802 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
114806 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
114821 Expr *pArg = pFarg->a[0].pExpr;
114822 if( pArg->op==TK_COLUMN && pArg->iTable>=0 ){
114823 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
114831 /* The UNLIKELY() function is a no-op. The result is the value
114835 target = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
114840 ** Test-only SQL functions that are only usable if enabled
114848 sqlite3ExprCompare(0,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
114857 sqlite3ExprImpliesExpr(pParse,pFarg->a[0].pExpr, pFarg->a[1].pExpr,-1),
114866 pA1 = pFarg->a[1].pExpr;
114867 if( pA1->op==TK_COLUMN ){
114869 sqlite3ExprImpliesNonNullRow(pFarg->a[0].pExpr,pA1->iTable,1),
114886 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
114890 (aff<=SQLITE_AFF_NONE) ? "none" : azAff[aff-SQLITE_AFF_BLOB]);
114907 ** Assume that every function is able to pass-through a subtype from
114919 if( pExpr->op!=TK_FUNCTION ){
114923 db = pWalker->pParse->db;
114924 n = ALWAYS(pExpr->x.pList) ? pExpr->x.pList->nExpr : 0;
114925 pDef = sqlite3FindFunction(db, pExpr->u.zToken, n, ENC(db), 0);
114926 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_RESULT_SUBTYPE)!=0 ){
114927 pWalker->eCode = 1;
114938 ** are acceptable as they only disable an optimization. False negatives,
114952 ** Check to see if pExpr is one of the indexed expressions on pParse->pIdxEpr.
114955 ** not an indexed expression, then return negative.
114964 for(p=pParse->pIdxEpr; p; p=p->pIENext){
114966 int iDataCur = p->iDataCur;
114968 if( pParse->iSelfTab ){
114969 if( p->iDataCur!=pParse->iSelfTab-1 ) continue;
114970 iDataCur = -1;
114972 if( sqlite3ExprCompare(0, pExpr, p->pExpr, iDataCur)!=0 ) continue;
114973 assert( p->aff>=SQLITE_AFF_BLOB && p->aff<=SQLITE_AFF_NUMERIC );
114975 if( (exprAff<=SQLITE_AFF_BLOB && p->aff!=SQLITE_AFF_BLOB)
114976 || (exprAff==SQLITE_AFF_TEXT && p->aff!=SQLITE_AFF_TEXT)
114977 || (exprAff>=SQLITE_AFF_NUMERIC && p->aff!=SQLITE_AFF_NUMERIC)
114985 ** value taken from an expression index if they are themselves an
114994 v = pParse->pVdbe;
114996 if( p->bMaybeNullRow ){
114997 /* If the index is on a NULL row due to an outer join, then we
115001 sqlite3VdbeAddOp3(v, OP_IfNullRow, p->iIdxCur, addr+3, target);
115003 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
115004 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
115006 p = pParse->pIdxEpr;
115007 pParse->pIdxEpr = 0;
115009 pParse->pIdxEpr = p;
115012 sqlite3VdbeAddOp3(v, OP_Column, p->iIdxCur, p->iIdxCol, target);
115013 VdbeComment((v, "%s expr-column %d", p->zIdxName, p->iIdxCol));
115017 return -1; /* Not found */
115033 for(p=pParse->pIdxPartExpr; p; p=p->pIENext){
115034 if( pExpr->iColumn==p->iIdxCol && pExpr->iTable==p->iDataCur ){
115035 Vdbe *v = pParse->pVdbe;
115039 if( p->bMaybeNullRow ){
115040 addr = sqlite3VdbeAddOp1(v, OP_IfNullRow, p->iIdxCur);
115042 ret = sqlite3ExprCodeTarget(pParse, p->pExpr, iTarget);
115043 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Affinity, ret, 1, 0,
115044 (const char*)&p->aff, 1);
115068 Vdbe *v = pParse->pVdbe; /* The VM under construction */
115071 int regFree1 = 0; /* If non-zero free this temporary register */
115072 int regFree2 = 0; /* If non-zero free this temporary register */
115077 assert( target>0 && target<=pParse->nMem );
115083 }else if( pParse->pIdxEpr!=0
115090 op = pExpr->op;
115095 AggInfo *pAggInfo = pExpr->pAggInfo;
115098 assert( pExpr->iAgg>=0 );
115099 if( pExpr->iAgg>=pAggInfo->nColumn ){
115101 ** is using an expression index */
115105 ** tag-20230325-2 */
115111 pCol = &pAggInfo->aCol[pExpr->iAgg];
115112 if( !pAggInfo->directMode ){
115113 return AggInfoColumnReg(pAggInfo, pExpr->iAgg);
115114 }else if( pAggInfo->useSortingIdx ){
115115 Table *pTab = pCol->pTab;
115116 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
115117 pCol->iSorterColumn, target);
115120 }else if( pCol->iColumn<0 ){
115121 VdbeComment((v,"%s.rowid",pTab->zName));
115124 pTab->zName, pTab->aCol[pCol->iColumn].zCnName));
115125 if( pTab->aCol[pCol->iColumn].affinity==SQLITE_AFF_REAL ){
115130 }else if( pExpr->y.pTab==0 ){
115131 /* This case happens when the argument to an aggregate function
115133 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, pExpr->iColumn, target);
115140 int iTab = pExpr->iTable;
115144 ** constraints, and that constant is coded by the pExpr->pLeft
115150 iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
115152 assert( pExpr->y.pTab!=0 );
115153 aff = sqlite3TableColumnAffinity(pExpr->y.pTab, pExpr->iColumn);
115159 &zAff[(aff-'B')*2], P4_STATIC);
115164 if( pParse->iSelfTab<0 ){
115168 ** 0-(pParse->iSelfTab). The rowid (if any) is in a register
115174 int iCol = pExpr->iColumn;
115176 pTab = pExpr->y.pTab;
115179 assert( iCol<pTab->nCol );
115181 return -1-pParse->iSelfTab;
115183 pCol = pTab->aCol + iCol;
115185 iSrc = sqlite3TableColumnToStorage(pTab, iCol) - pParse->iSelfTab;
115187 if( pCol->colFlags & COLFLAG_GENERATED ){
115188 if( pCol->colFlags & COLFLAG_BUSY ){
115190 pCol->zCnName);
115193 pCol->colFlags |= COLFLAG_BUSY;
115194 if( pCol->colFlags & COLFLAG_NOTAVAIL ){
115197 pCol->colFlags &= ~(COLFLAG_BUSY|COLFLAG_NOTAVAIL);
115201 if( pCol->affinity==SQLITE_AFF_REAL ){
115209 /* Coding an expression that is part of an index where column names
115211 iTab = pParse->iSelfTab - 1;
115214 else if( pParse->pIdxPartExpr
115220 assert( pExpr->y.pTab!=0 );
115221 iReg = sqlite3ExprCodeGetColumn(pParse, pExpr->y.pTab,
115222 pExpr->iColumn, iTab, target,
115223 pExpr->op2);
115237 codeReal(v, pExpr->u.zToken, 0, target);
115243 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
115247 /* Set a range of registers to NULL. pExpr->y.nReg registers starting
115249 sqlite3VdbeAddOp3(v, OP_Null, 0, target, target + pExpr->y.nReg - 1);
115253 /* Make NULL the default case so that if a bug causes an illegal
115257 assert( op==TK_NULL || op==TK_ERROR || pParse->db->mallocFailed );
115267 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
115268 assert( pExpr->u.zToken[1]=='\'' );
115269 z = &pExpr->u.zToken[2];
115270 n = sqlite3Strlen30(z) - 1;
115279 assert( pExpr->u.zToken!=0 );
115280 assert( pExpr->u.zToken[0]!=0 );
115281 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
115285 return pExpr->iTable;
115290 sqlite3ExprCode(pParse, pExpr->pLeft, target);
115294 sqlite3AffinityType(pExpr->u.zToken, 0));
115302 /* fall-through */
115309 Expr *pLeft = pExpr->pLeft;
115314 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
115316 codeCompare(pParse, pLeft, pExpr->pRight, op, r1, r2,
115358 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
115359 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
115366 Expr *pLeft = pExpr->pLeft;
115368 if( pLeft->op==TK_INTEGER ){
115372 }else if( pLeft->op==TK_FLOAT ){
115374 codeReal(v, pLeft->u.zToken, 1, target);
115383 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2);
115393 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
115401 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
115403 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
115404 bNormal = pExpr->op2==TK_IS;
115416 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
115426 AggInfo *pInfo = pExpr->pAggInfo;
115428 || NEVER(pExpr->iAgg<0)
115429 || NEVER(pExpr->iAgg>=pInfo->nFunc)
115434 return AggInfoFuncReg(pInfo, pExpr->iAgg);
115445 sqlite3 *db = pParse->db; /* The database connection */
115451 return pExpr->y.pWin->regResult;
115460 return sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
115464 pFarg = pExpr->x.pList;
115465 nFarg = pFarg ? pFarg->nExpr : 0;
115467 zId = pExpr->u.zToken;
115470 if( pDef==0 && pParse->explain ){
115474 if( pDef==0 || pDef->xFinalize!=0 ){
115478 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)!=0 && ALWAYS(pFarg!=0) ){
115479 assert( (pDef->funcFlags & SQLITE_FUNC_UNSAFE)==0 );
115480 assert( (pDef->funcFlags & SQLITE_FUNC_DIRECT)==0 );
115482 SQLITE_PTR_TO_INT(pDef->pUserData), target);
115483 }else if( pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE) ){
115488 if( i<32 && sqlite3ExprIsConstant(pParse, pFarg->a[i].pExpr) ){
115492 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
115493 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
115498 r1 = pParse->nMem+1;
115499 pParse->nMem += nFarg;
115509 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
115512 assert( pFarg->a[0].pExpr!=0 );
115513 exprOp = pFarg->a[0].pExpr->op;
115519 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_LENGTHARG );
115520 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_TYPEOFARG );
115521 testcase( (pDef->funcFlags & OPFLAG_BYTELENARG)==OPFLAG_BYTELENARG);
115522 pFarg->a[0].pExpr->op2 = pDef->funcFlags & OPFLAG_BYTELENARG;
115544 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
115546 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
115549 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
115550 if( !pColl ) pColl = db->pDfltColl;
115554 pDef, pExpr->op2);
115570 if( pParse->db->mallocFailed ){
115574 && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1
115584 Expr *pLeft = pExpr->pLeft;
115585 if( pLeft->iTable==0 || pParse->withinRJSubrtn > pLeft->op2 ){
115586 pLeft->iTable = sqlite3CodeSubselect(pParse, pLeft);
115587 pLeft->op2 = pParse->withinRJSubrtn;
115589 assert( pLeft->op==TK_SELECT || pLeft->op==TK_ERROR );
115591 if( pExpr->iTable!=n ){
115593 pExpr->iTable, n);
115595 return pLeft->iTable + pExpr->iColumn;
115618 ** X is stored in pExpr->pLeft.
115619 ** Y is stored in pExpr->pList->a[0].pExpr.
115620 ** Z is stored in pExpr->pList->a[1].pExpr.
115628 /* A TK_COLLATE Expr node without the EP_Collate tag is a so-called
115629 ** "SOFT-COLLATE" that is added to constraints that are pushed down
115630 ** from outer queries into sub-queries by the WHERE-clause push-down
115634 assert( pExpr->pLeft );
115635 sqlite3ExprCode(pParse, pExpr->pLeft, target);
115639 pExpr = pExpr->pLeft;
115640 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. */
115645 pExpr = pExpr->pLeft;
115646 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
115651 ** to a column in the new.* or old.* pseudo-tables available to
115653 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
115654 ** is set to the column of the pseudo-table to read, or to -1 to
115657 ** The expression is implemented using an OP_Param opcode. The p1
115658 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
115659 ** to reference another column of the old.* pseudo-table, where
115661 ** set to (n+1), where n is the number of columns in each pseudo-table.
115662 ** For a reference to any other column in the new.* pseudo-table, p1
115671 ** p1==0 -> old.rowid p1==3 -> new.rowid
115672 ** p1==1 -> old.a p1==4 -> new.a
115673 ** p1==2 -> old.b p1==5 -> new.b
115680 pTab = pExpr->y.pTab;
115681 iCol = pExpr->iColumn;
115682 p1 = pExpr->iTable * (pTab->nCol+1) + 1
115685 assert( pExpr->iTable==0 || pExpr->iTable==1 );
115686 assert( iCol>=-1 && iCol<pTab->nCol );
115687 assert( pTab->iPKey<0 || iCol!=pTab->iPKey );
115688 assert( p1>=0 && p1<(pTab->nCol*2+2) );
115692 (pExpr->iTable ? "new" : "old"),
115693 (pExpr->iColumn<0 ? "rowid" : pExpr->y.pTab->aCol[iCol].zCnName)
115697 /* If the column has REAL affinity, it may currently be stored as an
115700 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
115702 if( iCol>=0 && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
115715 ** that derive from the right-hand table of a LEFT JOIN. The
115716 ** Expr.iTable value is the table number for the right-hand table.
115722 u8 okConstFactor = pParse->okConstFactor;
115723 AggInfo *pAggInfo = pExpr->pAggInfo;
115725 assert( pExpr->iAgg>=0 && pExpr->iAgg<pAggInfo->nColumn );
115726 if( !pAggInfo->directMode ){
115727 inReg = AggInfoColumnReg(pAggInfo, pExpr->iAgg);
115730 if( pExpr->pAggInfo->useSortingIdx ){
115731 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
115732 pAggInfo->aCol[pExpr->iAgg].iSorterColumn,
115738 addrINR = sqlite3VdbeAddOp3(v, OP_IfNullRow, pExpr->iTable, 0, target);
115746 pParse->okConstFactor = 0; /* note (1) above */
115747 sqlite3ExprCode(pParse, pExpr->pLeft, target);
115749 pParse->okConstFactor = okConstFactor;
115765 ** X (if it exists) is in pExpr->pLeft.
115766 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
115769 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
115786 sqlite3 *db = pParse->db;
115788 assert( ExprUseXList(pExpr) && pExpr->x.pList!=0 );
115789 assert(pExpr->x.pList->nExpr > 0);
115790 pEList = pExpr->x.pList;
115791 aListelem = pEList->a;
115792 nExpr = pEList->nExpr;
115794 if( (pX = pExpr->pLeft)!=0 ){
115796 if( db->mallocFailed ){
115800 testcase( pX->op==TK_COLUMN );
115808 ** The value in regFree1 might get SCopy-ed into the file result.
115813 for(i=0; i<nExpr-1; i=i+2){
115821 testcase( pTest->op==TK_COLUMN );
115823 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
115829 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
115840 assert( pExpr->affExpr==OE_Rollback
115841 || pExpr->affExpr==OE_Abort
115842 || pExpr->affExpr==OE_Fail
115843 || pExpr->affExpr==OE_Ignore
115845 if( !pParse->pTriggerTab && !pParse->nested ){
115847 "RAISE() may only be used within a trigger-program");
115850 if( pExpr->affExpr==OE_Abort ){
115854 if( pExpr->affExpr==OE_Ignore ){
115858 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
115860 pParse->pTriggerTab ? SQLITE_CONSTRAINT_TRIGGER : SQLITE_ERROR,
115861 pExpr->affExpr, r1);
115876 ** If the expression uses functions (that might throw an exception) then
115877 ** guard them with an OP_Once opcode to ensure that the code is only executed
115897 p = pParse->pConstExpr;
115901 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
115902 if( pItem->fg.reusable
115903 && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0
115905 return pItem->u.iConstExprReg;
115909 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
115911 Vdbe *v = pParse->pVdbe;
115915 pParse->okConstFactor = 0;
115916 if( !pParse->db->mallocFailed ){
115917 if( regDest<0 ) regDest = ++pParse->nMem;
115920 pParse->okConstFactor = 1;
115921 sqlite3ExprDelete(pParse->db, pExpr);
115926 struct ExprList_item *pItem = &p->a[p->nExpr-1];
115927 pItem->fg.reusable = regDest<0;
115928 if( regDest<0 ) regDest = ++pParse->nMem;
115929 pItem->u.iConstExprReg = regDest;
115931 pParse->pConstExpr = p;
115945 u8 okConstFactor = pParse->okConstFactor;
115950 pParse->okConstFactor = 1;
115952 pParse->okConstFactor = okConstFactor;
115956 ** Generate code to evaluate an expression and store the results
115973 && pExpr->op!=TK_REGISTER
115977 r2 = sqlite3ExprCodeRunJustOnce(pParse, pExpr, -1);
116000 assert( target>0 && target<=pParse->nMem );
116001 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
116002 if( pParse->pVdbe==0 ) return;
116009 && (ExprHasProperty(pX,EP_Subquery) || pX->op==TK_REGISTER)
116015 sqlite3VdbeAddOp2(pParse->pVdbe, op, inReg, target);
116025 sqlite3 *db = pParse->db;
116027 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
116038 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pParse,pExpr) ){
116050 ** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
116075 Vdbe *v = pParse->pVdbe;
116078 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
116079 n = pList->nExpr;
116081 for(pItem=pList->a, i=0; i<n; i++, pItem++){
116082 Expr *pExpr = pItem->pExpr;
116084 if( pItem->fg.bSorterRef ){
116085 i--;
116086 n--;
116089 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
116091 i--;
116092 n--;
116094 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
116105 && (pOp=sqlite3VdbeGetLastOp(v))->opcode==OP_Copy
116106 && pOp->p1+pOp->p3+1==inReg
116107 && pOp->p2+pOp->p3+1==target+i
116108 && pOp->p5==0 /* The do-not-merge flag must be clear */
116110 pOp->p3++;
116152 sqlite3 *db = pParse->db;
116159 pDel = sqlite3ExprDup(db, pExpr->pLeft, 0);
116160 if( db->mallocFailed==0 ){
116166 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
116169 compRight.pRight = pExpr->x.pList->a[1].pExpr;
116179 pDel->flags |= EP_OuterON;
116213 Vdbe *v = pParse->pVdbe;
116223 op = pExpr->op;
116233 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,
116235 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
116239 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
116240 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
116246 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
116253 isNot = pExpr->op2==TK_ISNOT;
116254 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
116258 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
116261 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
116279 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
116281 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
116282 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
116283 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
116303 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
116331 /* No-op */
116356 Vdbe *v = pParse->pVdbe;
116367 /* The value of pExpr->op and op are related as follows:
116369 ** pExpr->op op
116370 ** --------- ----------
116380 ** For other values of pExpr->op, op is undefined and unused.
116385 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
116389 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
116390 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
116391 assert( pExpr->op!=TK_NE || op==OP_Eq );
116392 assert( pExpr->op!=TK_EQ || op==OP_Ne );
116393 assert( pExpr->op!=TK_LT || op==OP_Ge );
116394 assert( pExpr->op!=TK_LE || op==OP_Gt );
116395 assert( pExpr->op!=TK_GT || op==OP_Le );
116396 assert( pExpr->op!=TK_GE || op==OP_Lt );
116398 switch( pExpr->op ){
116404 }else if( pExpr->op==TK_AND ){
116406 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
116407 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
116411 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2,
116413 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
116420 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
116427 isNot = pExpr->op2==TK_ISNOT;
116428 isTrue = sqlite3ExprTruthValue(pExpr->pRight);
116433 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
116438 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
116445 testcase( pExpr->op==TK_IS );
116446 testcase( pExpr->op==TK_ISNOT );
116447 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
116456 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
116458 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
116459 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
116460 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
116478 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
116508 /* no-op */
116529 sqlite3 *db = pParse->db;
116531 if( db->mallocFailed==0 ){
116538 ** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
116541 ** If pExpr is a simple SQL value - an integer, real, string, blob
116542 ** or NULL value - then the VDBE currently being prepared is configured
116543 ** to re-prepare each time a new value is bound to variable pVar.
116546 ** same as that currently bound to variable pVar, non-zero is returned.
116562 if( pExpr->op==TK_VARIABLE && pVar->iColumn==pExpr->iColumn ){
116565 if( (pParse->db->flags & SQLITE_EnableQPSG)!=0 ) return 2;
116566 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
116568 iVar = pVar->iColumn;
116569 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
116570 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
116573 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
116587 ** other than the top-level COLLATE operator.
116589 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
116590 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
116601 ** this routine is used, it does not hurt to get an extra 2 - that
116603 ** an incorrect 0 or 1 could lead to a malfunction.
116606 ** terms in pA with bindings in pParse->pReprepare can be matched against
116607 ** literals in pB. The pParse->pVdbe->expmask bitmask is updated for
116620 if( pParse && pA->op==TK_VARIABLE ){
116623 combinedFlags = pA->flags | pB->flags;
116625 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
116630 if( pA->op!=pB->op || pA->op==TK_RAISE ){
116631 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
116634 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
116637 if( pA->op==TK_AGG_COLUMN && pB->op==TK_COLUMN
116638 && pB->iTable<0 && pA->iTable==iTab
116647 if( pA->u.zToken ){
116648 if( pA->op==TK_FUNCTION || pA->op==TK_AGG_FUNCTION ){
116649 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
116651 assert( pA->op==pB->op );
116656 if( sqlite3WindowCompare(pParse, pA->y.pWin, pB->y.pWin, 1)!=0 ){
116661 }else if( pA->op==TK_NULL ){
116663 }else if( pA->op==TK_COLLATE ){
116664 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
116666 if( pB->u.zToken!=0
116667 && pA->op!=TK_COLUMN
116668 && pA->op!=TK_AGG_COLUMN
116669 && strcmp(pA->u.zToken,pB->u.zToken)!=0
116674 if( (pA->flags & (EP_Distinct|EP_Commuted))
116675 != (pB->flags & (EP_Distinct|EP_Commuted)) ) return 2;
116679 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
116680 if( sqlite3ExprCompare(pParse, pA->pRight, pB->pRight, iTab) ) return 2;
116681 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
116682 if( pA->op!=TK_STRING
116683 && pA->op!=TK_TRUEFALSE
116686 if( pA->iColumn!=pB->iColumn ) return 2;
116687 if( pA->op2!=pB->op2 && pA->op==TK_TRUTH ) return 2;
116688 if( pA->op!=TK_IN && pA->iTable!=pB->iTable && pA->iTable!=iTab ){
116701 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
116702 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
116704 ** This routine might return non-zero for equivalent ExprLists. The
116710 ** always differs from a non-NULL pointer.
116716 if( pA->nExpr!=pB->nExpr ) return 1;
116717 for(i=0; i<pA->nExpr; i++){
116719 Expr *pExprA = pA->a[i].pExpr;
116720 Expr *pExprB = pB->a[i].pExpr;
116721 if( pA->a[i].fg.sortFlags!=pB->a[i].fg.sortFlags ) return 1;
116728 ** Like sqlite3ExprCompare() except COLLATE operators at the top-level
116739 ** Return non-zero if Expr p can only be true if pNN is not NULL.
116741 ** Or if seenNot is true, return non-zero if Expr p can only be
116742 ** non-NULL if pNN is not NULL
116749 int seenNot /* Return true only if p can be any non-NULL value */
116754 return pNN->op!=TK_NULL;
116756 switch( p->op ){
116759 assert( ExprUseXSelect(p) || (p->x.pList!=0 && p->x.pList->nExpr>0) );
116760 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
116765 pList = p->x.pList;
116767 assert( pList->nExpr==2 );
116769 if( exprImpliesNotNull(pParse, pList->a[0].pExpr, pNN, iTab, 1)
116770 || exprImpliesNotNull(pParse, pList->a[1].pExpr, pNN, iTab, 1)
116774 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
116794 if( exprImpliesNotNull(pParse, p->pRight, pNN, iTab, seenNot) ) return 1;
116801 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, seenNot);
116805 if( p->op2!=TK_IS ) return 0;
116806 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
116810 return exprImpliesNotNull(pParse, p->pLeft, pNN, iTab, 1);
116822 if( pExpr->op==TK_NULL ) return 1;
116823 if( pExpr->op==TK_TRUEFALSE && sqlite3ExprTruthValue(pExpr)==0 ) return 1;
116841 if( pExpr->op==TK_FUNCTION ){
116842 const char *z = pExpr->u.zToken;
116845 if( pExpr->x.pList==0 ) return 0;
116846 pDef = sqlite3FindFunction(db, z, pExpr->x.pList->nExpr, ENC(db), 0);
116852 if( (pDef->funcFlags & SQLITE_FUNC_INLINE)==0 ) return 0;
116853 if( SQLITE_PTR_TO_INT(pDef->pUserData)!=INLINEFUNC_iif ) return 0;
116854 }else if( pExpr->op==TK_CASE ){
116855 if( pExpr->pLeft!=0 ) return 0;
116859 pList = pExpr->x.pList;
116861 if( pList->nExpr==2 ) return 1;
116862 if( pList->nExpr==3 && sqlite3ExprIsNotTrue(pList->a[2].pExpr) ) return 1;
116885 ** compared against literal values in pE2 and pParse->pVdbe->expmask is
116902 if( pE2->op==TK_OR
116903 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
116904 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->pRight, iTab) )
116908 if( pE2->op==TK_NOTNULL
116909 && exprImpliesNotNull(pParse, pE1, pE2->pLeft, iTab, 0)
116913 if( sqlite3ExprIsIIF(pParse->db, pE1) ){
116914 return sqlite3ExprImpliesExpr(pParse,pE1->x.pList->a[0].pExpr,pE2,iTab);
116920 ** set pWalker->eCode to one only if *both* of the input expressions
116921 ** separately have the implies-not-null-row property.
116924 if( pWalker->eCode==0 ){
116926 if( pWalker->eCode ){
116927 pWalker->eCode = 0;
116935 ** If the expression node requires that the table at pWalker->iCur
116936 ** have one or more non-NULL column, then set pWalker->eCode to 1 and abort.
116938 ** pWalker->mWFlags is non-zero if this inquiry is being undertaking on
116940 ** evaluating terms in the ON clause of an inner join.
116942 ** This routine controls an optimization. False positives (setting
116943 ** pWalker->eCode to 1 when it should not be) are deadly, but false-negatives
116944 ** (never setting pWalker->eCode) is a harmless missed optimization.
116947 testcase( pExpr->op==TK_AGG_COLUMN );
116948 testcase( pExpr->op==TK_AGG_FUNCTION );
116950 if( ExprHasProperty(pExpr, EP_InnerON) && pWalker->mWFlags ){
116951 /* If iCur is used in an inner-join ON clause to the left of a
116952 ** RIGHT JOIN, that does *not* mean that the table must be non-null.
116954 ** To keep things simple, any use of iCur from any inner-join is
116958 switch( pExpr->op ){
116967 testcase( pExpr->op==TK_ISNOT );
116968 testcase( pExpr->op==TK_ISNULL );
116969 testcase( pExpr->op==TK_NOTNULL );
116970 testcase( pExpr->op==TK_IS );
116971 testcase( pExpr->op==TK_VECTOR );
116972 testcase( pExpr->op==TK_FUNCTION );
116973 testcase( pExpr->op==TK_TRUTH );
116974 testcase( pExpr->op==TK_CASE );
116978 if( pWalker->u.iCur==pExpr->iTable ){
116979 pWalker->eCode = 1;
116986 /* Both sides of an AND or OR must separately imply non-null-row.
116990 ** If only one of x or y is non-null-row, then the overall expression
116993 testcase( pExpr->op==TK_OR );
116994 testcase( pExpr->op==TK_AND );
116995 bothImplyNotNullRow(pWalker, pExpr->pLeft, pExpr->pRight);
117001 ** the left-hand side of the IN is NULL then the IN itself will be
117003 if( ExprUseXList(pExpr) && ALWAYS(pExpr->x.pList->nExpr>0) ){
117004 sqlite3WalkExpr(pWalker, pExpr->pLeft);
117009 /* In "x NOT BETWEEN y AND z" either x must be non-null-row or else
117010 ** both y and z must be non-null row */
117012 assert( pExpr->x.pList->nExpr==2 );
117013 sqlite3WalkExpr(pWalker, pExpr->pLeft);
117014 bothImplyNotNullRow(pWalker, pExpr->x.pList->a[0].pExpr,
117015 pExpr->x.pList->a[1].pExpr);
117027 Expr *pLeft = pExpr->pLeft;
117028 Expr *pRight = pExpr->pRight;
117029 testcase( pExpr->op==TK_EQ );
117030 testcase( pExpr->op==TK_NE );
117031 testcase( pExpr->op==TK_LT );
117032 testcase( pExpr->op==TK_LE );
117033 testcase( pExpr->op==TK_GT );
117034 testcase( pExpr->op==TK_GE );
117037 assert( pLeft->op!=TK_COLUMN || ExprUseYTab(pLeft) );
117038 assert( pRight->op!=TK_COLUMN || ExprUseYTab(pRight) );
117039 if( (pLeft->op==TK_COLUMN
117040 && ALWAYS(pLeft->y.pTab!=0)
117041 && IsVirtual(pLeft->y.pTab))
117042 || (pRight->op==TK_COLUMN
117043 && ALWAYS(pRight->y.pTab!=0)
117044 && IsVirtual(pRight->y.pTab))
117056 ** Return true (non-zero) if expression p can only be true if at least
117057 ** one column of table iTab is non-null. In other words, return true
117066 ** in an incorrect answer.
117072 ** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
117074 ** be non-NULL, then the LEFT JOIN can be safely converted into an
117081 if( p->op==TK_NOTNULL ){
117082 p = p->pLeft;
117084 while( p->op==TK_AND ){
117085 if( sqlite3ExprImpliesNonNullRow(p->pLeft, iTab, isRJ) ) return 1;
117086 p = p->pRight;
117100 ** An instance of the following structure is used by the tree walker
117101 ** to determine if an expression can be evaluated by reference to the
117113 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
117114 ** pWalker->u.pIdxCover->pIdx.
117117 if( pExpr->op==TK_COLUMN
117118 && pExpr->iTable==pWalker->u.pIdxCover->iCur
117119 && sqlite3TableColumnToIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
117121 pWalker->eCode = 1;
117128 ** Determine if an index pIdx on table with cursor iCur contains will
117133 ** An index covering an expression means that the expression can be
117173 struct RefSrcList *p = pWalker->u.pRefSrcList;
117174 SrcList *pSrc = pSelect->pSrc;
117177 if( pSrc->nSrc==0 ) return WRC_Continue;
117178 j = p->nExclude;
117179 p->nExclude += pSrc->nSrc;
117180 piNew = sqlite3DbRealloc(p->db, p->aiExclude, p->nExclude*sizeof(int));
117182 p->nExclude = 0;
117185 p->aiExclude = piNew;
117187 for(i=0; i<pSrc->nSrc; i++, j++){
117188 p->aiExclude[j] = pSrc->a[i].iCursor;
117193 struct RefSrcList *p = pWalker->u.pRefSrcList;
117194 SrcList *pSrc = pSelect->pSrc;
117195 if( p->nExclude ){
117196 assert( p->nExclude>=pSrc->nSrc );
117197 p->nExclude -= pSrc->nSrc;
117203 ** Set the 0x01 bit of pWalker->eCode if there is a reference to any
117206 ** Set the 0x02 bit of pWalker->eCode if there is a reference to a
117210 if( pExpr->op==TK_COLUMN
117211 || pExpr->op==TK_AGG_COLUMN
117214 struct RefSrcList *p = pWalker->u.pRefSrcList;
117215 SrcList *pSrc = p->pRef;
117216 int nSrc = pSrc ? pSrc->nSrc : 0;
117218 if( pExpr->iTable==pSrc->a[i].iCursor ){
117219 pWalker->eCode |= 1;
117223 for(i=0; i<p->nExclude && p->aiExclude[i]!=pExpr->iTable; i++){}
117224 if( i>=p->nExclude ){
117225 pWalker->eCode |= 2;
117240 ** -1 pExpr only references no tables at all, or it only
117243 ** As currently used, pExpr is always an aggregate function call. That
117249 assert( pParse->db!=0 );
117256 x.db = pParse->db;
117258 assert( pExpr->op==TK_AGG_FUNCTION );
117260 sqlite3WalkExprList(&w, pExpr->x.pList);
117261 if( pExpr->pLeft ){
117262 assert( pExpr->pLeft->op==TK_ORDER );
117263 assert( ExprUseXList(pExpr->pLeft) );
117264 assert( pExpr->pLeft->x.pList!=0 );
117265 sqlite3WalkExprList(&w, pExpr->pLeft->x.pList);
117269 sqlite3WalkExpr(&w, pExpr->y.pWin->pFilter);
117272 if( x.aiExclude ) sqlite3DbNNFreeNN(pParse->db, x.aiExclude);
117278 return -1;
117295 && pExpr->pAggInfo!=0
117297 AggInfo *pAggInfo = pExpr->pAggInfo;
117298 int iAgg = pExpr->iAgg;
117299 Parse *pParse = pWalker->pParse;
117300 sqlite3 *db = pParse->db;
117302 if( pExpr->op!=TK_AGG_FUNCTION ){
117303 if( iAgg<pAggInfo->nColumn
117304 && pAggInfo->aCol[iAgg].pCExpr==pExpr
117308 pAggInfo->aCol[iAgg].pCExpr = pExpr;
117312 assert( pExpr->op==TK_AGG_FUNCTION );
117313 if( ALWAYS(iAgg<pAggInfo->nFunc)
117314 && pAggInfo->aFunc[iAgg].pFExpr==pExpr
117318 pAggInfo->aFunc[iAgg].pFExpr = pExpr;
117332 pWalker->pParse = pParse;
117333 pWalker->xExprCallback = agginfoPersistExprCb;
117334 pWalker->xSelectCallback = sqlite3SelectWalkNoop;
117338 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
117343 pInfo->aCol = sqlite3ArrayAllocate(
117345 pInfo->aCol,
117346 sizeof(pInfo->aCol[0]),
117347 &pInfo->nColumn,
117354 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
117359 pInfo->aFunc = sqlite3ArrayAllocate(
117361 pInfo->aFunc,
117362 sizeof(pInfo->aFunc[0]),
117363 &pInfo->nFunc,
117370 ** Search the AggInfo object for an aCol[] entry that has iTable and iColumn.
117373 ** If no prior entry is found, create a new one and return -1. The
117374 ** new column will have an index of pAggInfo->nColumn-1.
117383 int mxTerm = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
117386 assert( pAggInfo->iFirstReg==0 );
117387 pCol = pAggInfo->aCol;
117388 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
117389 if( pCol->pCExpr==pExpr ) return;
117390 if( pCol->iTable==pExpr->iTable
117391 && pCol->iColumn==pExpr->iColumn
117392 && pExpr->op!=TK_IF_NULL_ROW
117397 k = addAggInfoColumn(pParse->db, pAggInfo);
117400 assert( pParse->db->mallocFailed );
117407 pCol = &pAggInfo->aCol[k];
117409 pCol->pTab = pExpr->y.pTab;
117410 pCol->iTable = pExpr->iTable;
117411 pCol->iColumn = pExpr->iColumn;
117412 pCol->iSorterColumn = -1;
117413 pCol->pCExpr = pExpr;
117414 if( pAggInfo->pGroupBy && pExpr->op!=TK_IF_NULL_ROW ){
117416 ExprList *pGB = pAggInfo->pGroupBy;
117417 struct ExprList_item *pTerm = pGB->a;
117418 n = pGB->nExpr;
117420 Expr *pE = pTerm->pExpr;
117421 if( pE->op==TK_COLUMN
117422 && pE->iTable==pExpr->iTable
117423 && pE->iColumn==pExpr->iColumn
117425 pCol->iSorterColumn = j;
117430 if( pCol->iSorterColumn<0 ){
117431 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
117435 assert( pExpr->pAggInfo==0 || pExpr->pAggInfo==pAggInfo );
117436 pExpr->pAggInfo = pAggInfo;
117437 if( pExpr->op==TK_COLUMN ){
117438 pExpr->op = TK_AGG_COLUMN;
117440 assert( k <= SMXV(pExpr->iAgg) );
117441 pExpr->iAgg = (i16)k;
117451 NameContext *pNC = pWalker->u.pNC;
117452 Parse *pParse = pNC->pParse;
117453 SrcList *pSrcList = pNC->pSrcList;
117454 AggInfo *pAggInfo = pNC->uNC.pAggInfo;
117456 assert( pNC->ncFlags & NC_UAggInfo );
117457 assert( pAggInfo->iFirstReg==0 );
117458 switch( pExpr->op ){
117462 assert( pParse->iSelfTab==0 );
117463 if( (pNC->ncFlags & NC_InAggFunc)==0 ) break;
117464 if( pParse->pIdxEpr==0 ) break;
117465 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
117466 int iDataCur = pIEpr->iDataCur;
117468 if( sqlite3ExprCompare(0, pExpr, pIEpr->pExpr, iDataCur)==0 ) break;
117472 for(i=0; i<pSrcList->nSrc; i++){
117473 if( pSrcList->a[0].iCursor==pIEpr->iDataCur ) break;
117475 if( i>=pSrcList->nSrc ) break;
117476 if( NEVER(pExpr->pAggInfo!=0) ) break; /* Resolved by outer context */
117477 if( pParse->nErr ){ return WRC_Abort; }
117480 ** translated into a reference to an index column as described by
117485 tmp.iTable = pIEpr->iIdxCur;
117486 tmp.iColumn = pIEpr->iIdxCol;
117488 if( pParse->nErr ){ return WRC_Abort; }
117489 assert( pAggInfo->aCol!=0 );
117490 assert( tmp.iAgg<pAggInfo->nColumn );
117491 pAggInfo->aCol[tmp.iAgg].pCExpr = pExpr;
117492 pExpr->pAggInfo = pAggInfo;
117493 pExpr->iAgg = tmp.iAgg;
117499 testcase( pExpr->op==TK_AGG_COLUMN );
117500 testcase( pExpr->op==TK_COLUMN );
117501 testcase( pExpr->op==TK_IF_NULL_ROW );
117505 SrcItem *pItem = pSrcList->a;
117506 for(i=0; i<pSrcList->nSrc; i++, pItem++){
117508 if( pExpr->iTable==pItem->iCursor ){
117511 } /* endif pExpr->iTable==pItem->iCursor */
117517 if( (pNC->ncFlags & NC_InAggFunc)==0
117518 && pWalker->walkerDepth==pExpr->op2
117519 && pExpr->pAggInfo==0
117524 struct AggInfo_func *pItem = pAggInfo->aFunc;
117525 int mxTerm = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
117527 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
117528 if( NEVER(pItem->pFExpr==pExpr) ) break;
117529 if( sqlite3ExprCompare(0, pItem->pFExpr, pExpr, -1)==0 ){
117536 assert( i<pAggInfo->nFunc );
117537 }else if( i>=pAggInfo->nFunc ){
117538 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
117540 u8 enc = ENC(pParse->db);
117541 i = addAggInfoFunc(pParse->db, pAggInfo);
117545 pItem = &pAggInfo->aFunc[i];
117546 pItem->pFExpr = pExpr;
117548 nArg = pExpr->x.pList ? pExpr->x.pList->nExpr : 0;
117549 pItem->pFunc = sqlite3FindFunction(pParse->db,
117550 pExpr->u.zToken, nArg, enc, 0);
117551 assert( pItem->bOBUnique==0 );
117552 if( pExpr->pLeft
117553 && (pItem->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)==0
117559 assert( pExpr->pLeft->op==TK_ORDER );
117560 assert( ExprUseXList(pExpr->pLeft) );
117561 pItem->iOBTab = pParse->nTab++;
117562 pOBList = pExpr->pLeft->x.pList;
117563 assert( pOBList->nExpr>0 );
117564 assert( pItem->bOBUnique==0 );
117565 if( pOBList->nExpr==1
117567 && sqlite3ExprCompare(0,pOBList->a[0].pExpr,
117568 pExpr->x.pList->a[0].pExpr,0)==0
117570 pItem->bOBPayload = 0;
117571 pItem->bOBUnique = ExprHasProperty(pExpr, EP_Distinct);
117573 pItem->bOBPayload = 1;
117575 pItem->bUseSubtype =
117576 (pItem->pFunc->funcFlags & SQLITE_SUBTYPE)!=0;
117578 pItem->iOBTab = -1;
117580 if( ExprHasProperty(pExpr, EP_Distinct) && !pItem->bOBUnique ){
117581 pItem->iDistinct = pParse->nTab++;
117583 pItem->iDistinct = -1;
117587 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
117591 assert( i <= SMXV(pExpr->iAgg) );
117592 pExpr->iAgg = (i16)i;
117593 pExpr->pAggInfo = pAggInfo;
117605 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
117620 assert( pNC->pSrcList!=0 );
117625 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
117628 ** If an error is found, the analysis is cut short.
117634 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
117635 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
117644 if( pParse->nTempReg==0 ){
117645 return ++pParse->nMem;
117647 return pParse->aTempReg[--pParse->nTempReg];
117657 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
117658 pParse->aTempReg[pParse->nTempReg++] = iReg;
117669 i = pParse->iRangeReg;
117670 n = pParse->nRangeReg;
117672 pParse->iRangeReg += nReg;
117673 pParse->nRangeReg -= nReg;
117675 i = pParse->nMem+1;
117676 pParse->nMem += nReg;
117686 if( nReg>pParse->nRangeReg ){
117687 pParse->nRangeReg = nReg;
117688 pParse->iRangeReg = iReg;
117695 ** Always invoke this procedure after coding a subroutine or co-routine
117697 ** the sub/co-routine does not use registers in common with the code that
117698 ** invokes the sub/co-routine.
117701 pParse->nTempReg = 0;
117702 pParse->nRangeReg = 0;
117710 if( pParse->nMem<iReg ) pParse->nMem = iReg;
117721 const ExprList *pList = pParse->pConstExpr;
117724 for(i=0; i<pList->nExpr; i++){
117725 if( pList->a[i].u.iConstExprReg>=iMin ){
117726 iMin = pList->a[i].u.iConstExprReg + 1;
117730 pParse->nTempReg = 0;
117731 pParse->nRangeReg = 0;
117744 if( pParse->nRangeReg>0
117745 && pParse->iRangeReg+pParse->nRangeReg > iFirst
117746 && pParse->iRangeReg <= iLast
117750 for(i=0; i<pParse->nTempReg; i++){
117751 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
117755 if( pParse->pConstExpr ){
117756 ExprList *pList = pParse->pConstExpr;
117757 for(i=0; i<pList->nExpr; i++){
117758 int iReg = pList->a[i].u.iConstExprReg;
117794 ** If the table is a system table, this function leaves an error message
117795 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
117800 if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
117802 || (pTab->tabFlags & TF_Eponymous)!=0
117803 || ( (pTab->tabFlags & TF_Shadow)!=0
117804 && sqlite3ReadOnlyShadowTables(pParse->db)
117808 sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
117817 ** called at the end of the generation of an ALTER TABLE ... RENAME ...
117828 pParse->colNamesSet = 1;
117852 ** Generate VM code to replace any double-quoted strings (but not double-quoted
117854 ** database zDb with their single-quoted equivalents. If argument bTemp is
117880 Vdbe *v = pParse->pVdbe;
117883 sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, iDb, 0, p5);
117884 if( iDb!=1 ) sqlite3VdbeAddParseSchemaOp(pParse->pVdbe, 1, 0, p5);
117900 char *zName = 0; /* NULL-terminated version of pName */
117901 sqlite3 *db = pParse->db; /* Database connection */
117902 int nTabName; /* Number of UTF-8 characters in zTabName */
117905 VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
117907 if( NEVER(db->mallocFailed) ) goto exit_rename_table;
117908 assert( pSrc->nSrc==1 );
117909 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
117911 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
117913 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
117914 zDb = db->aDb[iDb].zDbSName;
117921 ** in database iDb. If so, this is an error.
117944 sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
117951 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
117962 if( pVTab->pVtab->pModule->xRename==0 ){
117971 ** nested SQL may raise an exception. */
117978 /* figure out how many UTF-8 characters are in zName */
117979 zTabName = pTab->zName;
117980 nTabName = sqlite3Utf8CharLen(zTabName, -1);
118017 zDb, zName, pTab->zName);
118038 ** of any resources used by the v-table implementation (including other
118043 int i = ++pParse->nMem;
118058 ** Write code that will raise an error if the table described by
118074 ** This function is called after an "ALTER TABLE ... ADD" statement
118078 ** The Table structure pParse->pNewTable was extended to include
118082 Table *pNew; /* Copy of pParse->pNewTable */
118087 char *zCol; /* Null-terminated column definition */
118094 db = pParse->db;
118095 assert( db->pParse==pParse );
118096 if( pParse->nErr ) return;
118097 assert( db->mallocFailed==0 );
118098 pNew = pParse->pNewTable;
118102 iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
118103 zDb = db->aDb[iDb].zDbSName;
118104 zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
118105 pCol = &pNew->aCol[pNew->nCol-1];
118112 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
118122 if( pCol->colFlags & COLFLAG_PRIMKEY ){
118126 if( pNew->pIndex ){
118131 if( (pCol->colFlags & COLFLAG_GENERATED)==0 ){
118134 ** for an SQL NULL default below.
118136 assert( pDflt==0 || pDflt->op==TK_SPAN );
118137 if( pDflt && pDflt->pLeft->op==TK_NULL ){
118141 if( (db->flags&SQLITE_ForeignKeys) && pNew->u.tab.pFKey && pDflt ){
118143 "Cannot add a REFERENCES column with non-NULL default value");
118145 if( pCol->notNull && !pDflt ){
118160 assert( db->mallocFailed == 1 );
118165 "Cannot add a column with non-constant default");
118169 }else if( pCol->colFlags & COLFLAG_STORED ){
118175 zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
118177 char *zEnd = &zCol[pColDef->n-1];
118179 *zEnd-- = '\0';
118190 zDb, pNew->u.tab.addColOffset, zCol, pNew->u.tab.addColOffset,
118205 sqlite3VdbeAddOp2(v, OP_AddImm, r1, -2);
118215 if( pNew->pCheck!=0
118216 || (pCol->notNull && (pCol->colFlags & COLFLAG_GENERATED)!=0)
118217 || (pTab->tabFlags & TF_Strict)!=0
118222 " WHEN quick_check GLOB 'non-* value in*'"
118229 " OR quick_check GLOB 'non-* value in*'",
118237 ** This function is called by the parser after the table-name in
118238 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
118239 ** pSrc is the full-name of the table being altered.
118257 sqlite3 *db = pParse->db;
118260 assert( pParse->pNewTable==0 );
118262 if( db->mallocFailed ) goto exit_begin_add_column;
118263 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
118273 /* Make sure this is not an attempt to ALTER a view. */
118284 assert( pTab->u.tab.addColOffset>0 );
118285 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
118289 ** the name by adding an "sqlite_altertab_" prefix. By adding this
118290 ** prefix, we insure that the name will not collide with an existing
118296 pParse->pNewTable = pNew;
118297 pNew->nTabRef = 1;
118298 pNew->nCol = pTab->nCol;
118299 assert( pNew->nCol>0 );
118300 nAlloc = (((pNew->nCol-1)/8)*8)+8;
118301 assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
118302 pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*(u32)nAlloc);
118303 pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
118304 if( !pNew->aCol || !pNew->zName ){
118305 assert( db->mallocFailed );
118308 memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*(size_t)pNew->nCol);
118309 for(i=0; i<pNew->nCol; i++){
118310 Column *pCol = &pNew->aCol[i];
118311 pCol->zCnName = sqlite3DbStrDup(db, pCol->zCnName);
118312 pCol->hName = sqlite3StrIHash(pCol->zCnName);
118315 pNew->u.tab.pDfltList = sqlite3ExprListDup(db, pTab->u.tab.pDfltList, 0);
118316 pNew->pSchema = db->aDb[iDb].pSchema;
118317 pNew->u.tab.addColOffset = pTab->u.tab.addColOffset;
118318 assert( pNew->nTabRef==1 );
118326 ** Parameter pTab is the subject of an ALTER TABLE ... RENAME COLUMN
118329 ** it loads an error message into pParse and returns non-zero.
118349 zType, pTab->zName
118366 SrcList *pSrc, /* Table being altered. pSrc->nSrc==1 */
118370 sqlite3 *db = pParse->db; /* Database connection */
118380 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
118388 iSchema = sqlite3SchemaToIndex(db, pTab->pSchema);
118390 zDb = db->aDb[iSchema].zDbSName;
118394 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
118409 /* Ensure the schema contains no double-quoted strings */
118420 assert( pNew->n>0 );
118421 bQuote = sqlite3Isquote(pNew->z[0]);
118428 zDb, pTab->zName, iCol, zNew, bQuote, iSchema==1,
118429 pTab->zName
118436 zDb, pTab->zName, iCol, zNew, bQuote
118451 ** Each RenameToken object maps an element of the parse tree into
118455 ** * A pointer to an Expr that represents an ID
118474 ** The context of an ALTER TABLE RENAME COLUMN operation that gets passed
118491 ** rename-token list.
118493 ** 2. Dereferences each pointer in the rename-token list.
118496 ** address-sanitizer or similar. If any of these pointers no longer
118497 ** point to valid objects, an exception is raised by the memory-checking
118511 assert( pParse==pParse->db->pParse );
118512 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
118513 if( pParse->nErr==0 ){
118516 for(p=pParse->pRename; p; p=p->pNext){
118517 if( p->p ){
118518 assert( p->p!=pPtr );
118519 i += *(u8*)(p->p) | 1;
118535 ** in pParse->pRename.
118547 assert( pPtr || pParse->db->mallocFailed );
118549 if( ALWAYS(pParse->eParseMode!=PARSE_MODE_UNMAP) ){
118550 pNew = sqlite3DbMallocZero(pParse->db, sizeof(RenameToken));
118552 pNew->p = pPtr;
118553 pNew->t = *pToken;
118554 pNew->pNext = pParse->pRename;
118555 pParse->pRename = pNew;
118570 for(p=pParse->pRename; p; p=p->pNext){
118571 if( p->p==pFrom ){
118572 p->p = pTo;
118582 Parse *pParse = pWalker->pParse;
118585 sqlite3RenameTokenRemap(pParse, 0, (const void*)&pExpr->y.pTab);
118595 With *pWith = pSelect->pWith;
118597 Parse *pParse = pWalker->pParse;
118600 assert( pWith->nCte>0 );
118601 if( (pWith->a[0].pSelect->selFlags & SF_Expanded)==0 ){
118602 /* Push a copy of the With object onto the with-stack. We use a copy
118604 ** and SF_Resolved) below. And the parser code that uses the with-stack
118607 pCopy = sqlite3WithDup(pParse->db, pWith);
118610 for(i=0; i<pWith->nCte; i++){
118611 Select *p = pWith->a[i].pSelect;
118616 if( sNC.pParse->db->mallocFailed ) return;
118618 sqlite3RenameExprlistUnmap(pParse, pWith->a[i].pCols);
118620 if( pCopy && pParse->pWith==pCopy ){
118621 pParse->pWith = pCopy->pOuter;
118635 for(ii=0; ii<pIdList->nId; ii++){
118636 sqlite3RenameTokenRemap(pParse, 0, (const void*)pIdList->a[ii].zName);
118644 Parse *pParse = pWalker->pParse;
118646 if( pParse->nErr ) return WRC_Abort;
118647 testcase( p->selFlags & SF_View );
118648 testcase( p->selFlags & SF_CopyCte );
118649 if( p->selFlags & (SF_View|SF_CopyCte) ){
118652 if( ALWAYS(p->pEList) ){
118653 ExprList *pList = p->pEList;
118654 for(i=0; i<pList->nExpr; i++){
118655 if( pList->a[i].zEName && pList->a[i].fg.eEName==ENAME_NAME ){
118656 sqlite3RenameTokenRemap(pParse, 0, (void*)pList->a[i].zEName);
118660 if( ALWAYS(p->pSrc) ){ /* Every Select as a SrcList, even if it is empty */
118661 SrcList *pSrc = p->pSrc;
118662 for(i=0; i<pSrc->nSrc; i++){
118663 sqlite3RenameTokenRemap(pParse, 0, (void*)pSrc->a[i].zName);
118664 if( pSrc->a[i].fg.isUsing==0 ){
118665 sqlite3WalkExpr(pWalker, pSrc->a[i].u3.pOn);
118667 unmapColumnIdlistNames(pParse, pSrc->a[i].u3.pUsing);
118680 u8 eMode = pParse->eParseMode;
118686 pParse->eParseMode = PARSE_MODE_UNMAP;
118688 pParse->eParseMode = eMode;
118692 ** Remove all nodes that are part of expression-list pEList from the
118703 for(i=0; i<pEList->nExpr; i++){
118704 if( ALWAYS(pEList->a[i].fg.eEName==ENAME_NAME) ){
118705 sqlite3RenameTokenRemap(pParse, 0, (void*)pEList->a[i].zEName);
118718 pNext = p->pNext;
118741 for(pp=&pParse->pRename; (*pp); pp=&(*pp)->pNext){
118742 if( (*pp)->p==pPtr ){
118745 *pp = pToken->pNext;
118746 pToken->pNext = pCtx->pList;
118747 pCtx->pList = pToken;
118748 pCtx->nList++;
118759 ** descend into sub-select statements.
118762 if( p->selFlags & (SF_View|SF_CopyCte) ){
118763 testcase( p->selFlags & SF_View );
118764 testcase( p->selFlags & SF_CopyCte );
118775 ** if the column being references is the column being renamed by an
118778 ** constructed in RenameCtx object at pWalker->u.pRename.
118781 RenameCtx *p = pWalker->u.pRename;
118782 if( pExpr->op==TK_TRIGGER
118783 && pExpr->iColumn==p->iCol
118784 && pWalker->pParse->pTriggerTab==p->pTab
118786 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
118787 }else if( pExpr->op==TK_COLUMN
118788 && pExpr->iColumn==p->iCol
118790 && p->pTab==pExpr->y.pTab
118792 renameTokenFind(pWalker->pParse, p, (void*)pExpr);
118799 ** is being renamed by an ALTER TABLE statement. Return the "last"
118807 RenameToken *pBest = pCtx->pList;
118811 for(pToken=pBest->pNext; pToken; pToken=pToken->pNext){
118812 if( pToken->t.z>pBest->t.z ) pBest = pToken;
118814 for(pp=&pCtx->pList; *pp!=pBest; pp=&(*pp)->pNext);
118815 *pp = pBest->pNext;
118821 ** An error occurred while parsing or otherwise processing a database
118822 ** object (either pParse->pNewTable, pNewIndex or pNewTrigger) as part of an
118824 ** sub-routine is currently stored in pParse->zErrMsg. This function
118838 zErr = sqlite3MPrintf(pParse->db, "error in %s %s%s%s: %s",
118840 pParse->zErrMsg
118842 sqlite3_result_error(pCtx, zErr, -1);
118843 sqlite3DbFree(pParse->db, zErr);
118847 ** For each name in the the expression-list pEList (i.e. each
118848 ** pEList->a[i].zName) that matches the string in zOld, extract the
118849 ** corresponding rename-token from Parse object pParse and add it
118860 for(i=0; i<pEList->nExpr; i++){
118861 const char *zName = pEList->a[i].zEName;
118862 if( ALWAYS(pEList->a[i].fg.eEName==ENAME_NAME)
118873 ** For each name in the the id-list pIdList (i.e. each pIdList->a[i].zName)
118874 ** that matches the string in zOld, extract the corresponding rename-token
118885 for(i=0; i<pIdList->nId; i++){
118886 const char *zName = pIdList->a[i].zName;
118917 db->init.iDb = 1;
118921 db->init.iDb = (u8)iDb;
118923 p->eParseMode = PARSE_MODE_RENAME;
118924 p->db = db;
118925 p->nQueryLoop = 1;
118926 flags = db->flags;
118927 testcase( (db->flags & SQLITE_Comments)==0 && strstr(zSql," /* ")!=0 );
118928 db->flags |= SQLITE_Comments;
118930 db->flags = flags;
118931 if( db->mallocFailed ) rc = SQLITE_NOMEM;
118933 && NEVER(p->pNewTable==0 && p->pNewIndex==0 && p->pNewTrigger==0)
118944 for(pToken=p->pRename; pToken; pToken=pToken->pNext){
118945 assert( pToken->t.z>=zSql && &pToken->t.z[pToken->t.n]<=&zSql[nSql] );
118950 db->init.iDb = 0;
118960 ** Or, if an error occurs (i.e. an OOM condition), an error is left in
118961 ** pCtx and an SQLite error code returned.
118990 nQuot = sqlite3Strlen30(zQuot)-1;
118994 zOut = sqlite3DbMallocZero(db, (u64)nSql + pRename->nList*(u64)nQuot + 1);
119004 /* At this point pRename->pList contains a list of RenameToken objects
119006 ** with the new column name, or with single-quoted versions of themselves.
119012 while( pRename->pList ){
119019 if( bQuote==0 && sqlite3IsIdChar(*(u8*)pBest->t.z) ){
119025 if( pBest->t.z[pBest->t.n]=='"' ) nReplace++;
119028 /* Dequote the double-quoted token. Then requote it again, this time
119031 ** add another space after the new, single-quoted version of the
119034 memcpy(zBuf1, pBest->t.z, pBest->t.n);
119035 zBuf1[pBest->t.n] = 0;
119039 pBest->t.z[pBest->t.n]=='\'' ? " " : ""
119045 iOff = (int)(pBest->t.z - zSql);
119046 if( pBest->t.n!=nReplace ){
119047 memmove(&zOut[iOff + nReplace], &zOut[iOff + pBest->t.n],
119048 nOut - (iOff + pBest->t.n)
119050 nOut += nReplace - pBest->t.n;
119057 sqlite3_result_text(pCtx, zOut, -1, SQLITE_TRANSIENT);
119068 ** Set all pEList->a[].fg.eEName fields in the expression-list to val.
119074 for(i=0; i<pEList->nExpr; i++){
119075 assert( val==ENAME_NAME || pEList->a[i].fg.eEName==ENAME_NAME );
119076 pEList->a[i].fg.eEName = val&0x3;
119082 ** Resolve all symbols in the trigger at pParse->pNewTrigger, assuming
119084 ** successful. Otherwise, return an SQLite error code and leave an error
119088 sqlite3 *db = pParse->db;
119089 Trigger *pNew = pParse->pNewTrigger;
119096 assert( pNew->pTabSchema );
119097 pParse->pTriggerTab = sqlite3FindTable(db, pNew->table,
119098 db->aDb[sqlite3SchemaToIndex(db, pNew->pTabSchema)].zDbSName
119100 pParse->eTriggerOp = pNew->op;
119103 if( ALWAYS(pParse->pTriggerTab) ){
119104 rc = sqlite3ViewGetColumnNames(pParse, pParse->pTriggerTab)!=0;
119108 if( rc==SQLITE_OK && pNew->pWhen ){
119109 rc = sqlite3ResolveExprNames(&sNC, pNew->pWhen);
119112 for(pStep=pNew->step_list; rc==SQLITE_OK && pStep; pStep=pStep->pNext){
119113 if( pStep->pSelect ){
119114 sqlite3SelectPrep(pParse, pStep->pSelect, &sNC);
119115 if( pParse->nErr ) rc = pParse->rc;
119117 if( rc==SQLITE_OK && pStep->zTarget ){
119121 pParse, pStep->pExprList, pSrc, 0, 0, 0, 0, 0, 0
119124 pStep->pExprList = 0;
119128 /* pStep->pExprList contains an expression-list used for an UPDATE
119132 ** pStep->pExprList to ENAME_SPAN (from their current value of
119136 renameSetENames(pStep->pExprList, ENAME_SPAN);
119138 renameSetENames(pStep->pExprList, ENAME_NAME);
119139 rc = pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
119140 assert( pStep->pExprList==0 || pStep->pExprList==pSel->pEList );
119141 assert( pSrc==pSel->pSrc );
119142 if( pStep->pExprList ) pSel->pEList = 0;
119143 pSel->pSrc = 0;
119146 if( pStep->pFrom ){
119148 for(i=0; i<pStep->pFrom->nSrc && rc==SQLITE_OK; i++){
119149 SrcItem *p = &pStep->pFrom->a[i];
119150 if( p->fg.isSubquery ){
119151 assert( p->u4.pSubq!=0 );
119152 sqlite3SelectPrep(pParse, p->u4.pSubq->pSelect, 0);
119157 if( db->mallocFailed ){
119161 if( rc==SQLITE_OK && pStep->pWhere ){
119162 rc = sqlite3ResolveExprNames(&sNC, pStep->pWhere);
119165 rc = sqlite3ResolveExprListNames(&sNC, pStep->pExprList);
119167 assert( !pStep->pUpsert || (!pStep->pWhere && !pStep->pExprList) );
119168 if( pStep->pUpsert && rc==SQLITE_OK ){
119169 Upsert *pUpsert = pStep->pUpsert;
119170 pUpsert->pUpsertSrc = pSrc;
119173 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
119175 ExprList *pUpsertSet = pUpsert->pUpsertSet;
119179 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertWhere);
119182 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
119204 sqlite3WalkExpr(pWalker, pTrigger->pWhen);
119207 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
119208 sqlite3WalkSelect(pWalker, pStep->pSelect);
119209 sqlite3WalkExpr(pWalker, pStep->pWhere);
119210 sqlite3WalkExprList(pWalker, pStep->pExprList);
119211 if( pStep->pUpsert ){
119212 Upsert *pUpsert = pStep->pUpsert;
119213 sqlite3WalkExprList(pWalker, pUpsert->pUpsertTarget);
119214 sqlite3WalkExprList(pWalker, pUpsert->pUpsertSet);
119215 sqlite3WalkExpr(pWalker, pUpsert->pUpsertWhere);
119216 sqlite3WalkExpr(pWalker, pUpsert->pUpsertTargetWhere);
119218 if( pStep->pFrom ){
119220 SrcList *pFrom = pStep->pFrom;
119221 for(i=0; i<pFrom->nSrc; i++){
119222 if( pFrom->a[i].fg.isSubquery ){
119223 assert( pFrom->a[i].u4.pSubq!=0 );
119224 sqlite3WalkSelect(pWalker, pFrom->a[i].u4.pSubq->pSelect);
119236 sqlite3 *db = pParse->db;
119238 if( pParse->pVdbe ){
119239 sqlite3VdbeFinalize(pParse->pVdbe);
119241 sqlite3DeleteTable(db, pParse->pNewTable);
119242 while( (pIdx = pParse->pNewIndex)!=0 ){
119243 pParse->pNewIndex = pIdx->pNext;
119246 sqlite3DeleteTrigger(db, pParse->pNewTrigger);
119247 sqlite3DbFree(db, pParse->zErrMsg);
119248 renameTokenFree(db, pParse->pRename);
119264 ** 7. bQuote: Non-zero if the new column name should be quoted.
119268 ** The iCol-th column (left-most is 0) of table zTable is renamed from zCol
119298 sqlite3_xauth xAuth = db->xAuth;
119308 if( pTab==0 || iCol>=pTab->nCol ){
119312 zOld = pTab->aCol[iCol].zCnName;
119314 sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol);
119317 db->xAuth = 0;
119332 Select *pSelect = sParse.pNewTable->u.view.pSelect;
119333 pSelect->selFlags &= ~(u32)SF_View;
119336 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
119343 int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName);
119347 if( iCol<sParse.pNewTable->nCol ){
119349 &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zCnName
119353 renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey);
119355 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
119356 for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){
119357 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
119359 for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){
119360 sqlite3WalkExprList(&sWalker, pIdx->aColExpr);
119363 for(i=0; i<sParse.pNewTable->nCol; i++){
119365 &sParse.pNewTable->aCol[i]);
119372 for(pFKey=sParse.pNewTable->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
119373 for(i=0; i<pFKey->nCol; i++){
119374 if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){
119375 renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]);
119377 if( 0==sqlite3_stricmp(pFKey->zTo, zTable)
119378 && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld)
119380 renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol);
119386 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
119387 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
119394 for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){
119395 if( pStep->zTarget ){
119396 Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb);
119398 if( pStep->pUpsert ){
119399 ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet;
119402 renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld);
119403 renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld);
119411 renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld);
119435 db->xAuth = xAuth;
119444 RenameCtx *p = pWalker->u.pRename;
119445 if( pExpr->op==TK_COLUMN
119447 && p->pTab==pExpr->y.pTab
119449 renameTokenFind(pWalker->pParse, p, (void*)&pExpr->y.pTab);
119459 RenameCtx *p = pWalker->u.pRename;
119460 SrcList *pSrc = pSelect->pSrc;
119461 if( pSelect->selFlags & (SF_View|SF_CopyCte) ){
119462 testcase( pSelect->selFlags & SF_View );
119463 testcase( pSelect->selFlags & SF_CopyCte );
119467 assert( pWalker->pParse->db->mallocFailed );
119470 for(i=0; i<pSrc->nSrc; i++){
119471 SrcItem *pItem = &pSrc->a[i];
119472 if( pItem->pSTab==p->pTab ){
119473 renameTokenFind(pWalker->pParse, p, pItem->zName);
119483 ** This C function implements an SQL user function that is used by SQL code
119499 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
119522 sqlite3_xauth xAuth = db->xAuth;
119523 db->xAuth = 0;
119539 int isLegacy = (db->flags & SQLITE_LegacyAlter);
119545 Select *pSelect = pTab->u.view.pSelect;
119550 assert( pSelect->selFlags & SF_View );
119551 pSelect->selFlags &= ~(u32)SF_View;
119552 sqlite3SelectPrep(&sParse, pTab->u.view.pSelect, &sNC);
119556 sqlite3WalkSelect(&sWalker, pTab->u.view.pSelect);
119562 if( (isLegacy==0 || (db->flags & SQLITE_ForeignKeys))
119567 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
119568 if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){
119569 renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo);
119578 if( sqlite3_stricmp(zOld, pTab->zName)==0 ){
119581 sqlite3WalkExprList(&sWalker, pTab->pCheck);
119583 renameTokenFind(&sParse, &sCtx, pTab->zName);
119589 renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName);
119591 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
119599 if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld)
119600 && sCtx.pTab->pSchema==pTrigger->pTabSchema
119602 renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table);
119609 for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){
119610 if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){
119611 renameTokenFind(&sParse, &sCtx, pStep->zTarget);
119613 if( pStep->pFrom ){
119615 for(i=0; i<pStep->pFrom->nSrc; i++){
119616 SrcItem *pItem = &pStep->pFrom->a[i];
119617 if( 0==sqlite3_stricmp(pItem->zName, zOld) ){
119618 renameTokenFind(&sParse, &sCtx, pItem->zName);
119646 db->xAuth = xAuth;
119654 if( pExpr->op==TK_STRING && (pExpr->flags & EP_DblQuoted) ){
119655 renameTokenFind(pWalker->pParse, pWalker->u.pRename, (const void*)pExpr);
119663 ** double-quotes use single quotes instead.
119683 ** If there is a error in the input SQL, then raise an error, except
119685 ** unmodified following an error.
119697 sqlite3_xauth xAuth = db->xAuth;
119698 db->xAuth = 0;
119723 Select *pSelect = sParse.pNewTable->u.view.pSelect;
119724 pSelect->selFlags &= ~(u32)SF_View;
119727 rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc);
119733 sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck);
119735 for(i=0; i<sParse.pNewTable->nCol; i++){
119738 &sParse.pNewTable->aCol[i]));
119743 sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr);
119744 sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere);
119770 db->xAuth = xAuth;
119778 ** An SQL user function that checks that there are no parse or symbol
119780 ** After an ALTER TABLE .. RENAME operation is performed and the schema
119794 ** A. If an error is seen and not in PRAGMA writable_schema=ON mode,
119809 int isLegacy = (db->flags & SQLITE_LegacyAlter);
119814 sqlite3_xauth xAuth = db->xAuth;
119815 db->xAuth = 0;
119823 u64 flags = db->flags;
119824 if( bNoDQS ) db->flags &= ~(SQLITE_DqsDML|SQLITE_DqsDDL);
119826 db->flags = flags;
119832 sqlite3SelectPrep(&sParse, sParse.pNewTable->u.view.pSelect, &sNC);
119841 int i1 = sqlite3SchemaToIndex(db, sParse.pNewTrigger->pTabSchema);
119859 db->xAuth = xAuth;
119868 ** argv[0]: An integer - the index of the schema containing the table
119870 ** argv[2]: An integer - the index of the column to remove.
119884 const char *zDb = db->aDb[iSchema].zDbSName;
119893 sqlite3_xauth xAuth = db->xAuth;
119894 db->xAuth = 0;
119901 if( pTab==0 || pTab->nCol==1 || iCol>=pTab->nCol ){
119907 pCol = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol].zCnName);
119908 if( iCol<pTab->nCol-1 ){
119910 pEnd = renameTokenFind(&sParse, 0, (void*)pTab->aCol[iCol+1].zCnName);
119911 zEnd = (const char*)pEnd->t.z;
119914 zEnd = (const char*)&zSql[pTab->u.tab.addColOffset];
119915 while( ALWAYS(pCol->t.z[0]!=0) && pCol->t.z[0]!=',' ) pCol->t.z--;
119918 zNew = sqlite3MPrintf(db, "%.*s%s", pCol->t.z-zSql, zSql, zEnd);
119919 sqlite3_result_text(context, zNew, -1, SQLITE_TRANSIENT);
119925 db->xAuth = xAuth;
119933 ** This function is called by the parser upon parsing an
119941 sqlite3 *db = pParse->db; /* Database handle */
119946 int iCol; /* Index of column zCol in pTab->aCol[] */
119949 assert( pParse->pNewTable==0 );
119951 if( NEVER(db->mallocFailed) ) goto exit_drop_column;
119952 pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
119955 /* Make sure this is not an attempt to ALTER a view, virtual table or
119963 assert( db->mallocFailed );
119974 if( pTab->aCol[iCol].colFlags & (COLFLAG_PRIMKEY|COLFLAG_UNIQUE) ){
119976 (pTab->aCol[iCol].colFlags&COLFLAG_PRIMKEY) ? "PRIMARY KEY" : "UNIQUE",
119983 if( pTab->nCol<=1 ){
119989 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
119991 zDb = db->aDb[iDb].zDbSName;
119994 if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, zCol) ){
120004 , zDb, iDb, iCol, pTab->zName
120012 if( pParse->nErr==0 && (pTab->aCol[iCol].colFlags & COLFLAG_VIRTUAL)==0 ){
120018 int nField = 0; /* Number of non-virtual columns after drop */
120021 iCur = pParse->nTab++;
120024 reg = ++pParse->nMem;
120027 pParse->nMem += pTab->nCol;
120030 pParse->nMem += pPk->nColumn;
120031 for(i=0; i<pPk->nKeyCol; i++){
120034 nField = pPk->nKeyCol;
120036 regRec = ++pParse->nMem;
120037 for(i=0; i<pTab->nCol; i++){
120038 if( i!=iCol && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
120043 if( iPos<pPk->nKeyCol ) continue;
120044 regOut = reg+1+iPos-(iPos>iColPos);
120048 if( i==pTab->iPKey ){
120051 char aff = pTab->aCol[i].affinity;
120053 pTab->aCol[i].affinity = SQLITE_AFF_NUMERIC;
120056 pTab->aCol[i].affinity = aff;
120063 pParse->nMem++;
120069 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iCur, regRec, reg+1, pPk->nKeyCol);
120085 ** Register built-in functions used to help implement ALTER TABLE
120102 ** 2005-07-08
120133 ** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only
120152 ** columns. The N-th integer (for N>1) is the average number of rows in
120153 ** the index which have the same value for the first N-1 columns. For
120154 ** a K-column index, there will be K+1 integers in the stat column. If
120172 ** about the distribution of keys within an index. The index is identified by
120177 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
120178 ** inclusive are samples of the left-most key value in the index taken at
120185 ** For i between 0 and S-1. Conceptually, the index space is divided into
120212 ** of entries in the index whose left-most column exactly matches
120213 ** the left-most column of the sample. The second integer in nEq
120219 ** left-most column is less than the left-most column of the sample.
120220 ** The K-th integer in the nLt entry is the number of index entries
120226 ** There can be an arbitrary number of sqlite_stat4 entries per index.
120235 ** looks at the left-most column of the index. The sqlite_stat3.sample
120236 ** column contains the actual value of the left-most column instead
120257 ** appropriate compile-time options are provided.
120286 sqlite3 *db = pParse->db;
120300 pDb = &db->aDb[iDb];
120309 if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
120312 ** side-effect of the CREATE TABLE statement is to leave the rootpage
120313 ** of the new table in register pParse->regRoot. This is important
120316 "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
120318 assert( pParse->isCreate || pParse->nErr );
120319 aRoot[i] = (u32)pParse->u1.cr.regRoot;
120326 aRoot[i] = pStat->tnum;
120331 pDb->zDbSName, zTab, zWhereType, zWhere
120334 }else if( db->xPreUpdateCallback ){
120335 sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
120361 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
120362 ** share an instance of the following structure to hold their state
120386 int nLimit; /* Analysis row-scan limit */
120389 u8 nSkipAhead; /* Number of times of skip-ahead */
120394 u32 iPrn; /* Pseudo-random number used for sampling */
120409 if( p->nRowid ){
120410 sqlite3DbFree(db, p->u.aRowid);
120411 p->nRowid = 0;
120421 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
120422 p->u.aRowid = sqlite3DbMallocRawNN(db, n);
120423 if( p->u.aRowid ){
120424 p->nRowid = n;
120425 memcpy(p->u.aRowid, pData, n);
120427 p->nRowid = 0;
120437 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
120438 p->nRowid = 0;
120439 p->u.iRowid = iRowid;
120449 pTo->isPSample = pFrom->isPSample;
120450 pTo->iCol = pFrom->iCol;
120451 pTo->iHash = pFrom->iHash;
120452 memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
120453 memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
120454 memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
120455 if( pFrom->nRowid ){
120456 sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
120458 sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
120469 if( p->mxSample ){
120471 for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
120472 for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
120473 sampleClear(p->db, &p->current);
120476 sqlite3DbFree(p->db, p);
120485 ** L: A limit on the number of rows to scan, or 0 for no-limit
120543 p->db = db;
120544 p->nEst = sqlite3_value_int64(argv[2]);
120545 p->nRow = 0;
120546 p->nLimit = sqlite3_value_int(argv[3]);
120547 p->nCol = nCol;
120548 p->nKeyCol = nKeyCol;
120549 p->nSkipAhead = 0;
120550 p->current.anDLt = (tRowcnt*)&p[1];
120553 p->current.anEq = &p->current.anDLt[nColUp];
120554 p->mxSample = p->nLimit==0 ? mxSample : 0;
120557 int i; /* Used to iterate through p->aSample[] */
120559 p->iGet = -1;
120560 p->nPSample = (tRowcnt)(p->nEst/(mxSample/3+1) + 1);
120561 p->current.anLt = &p->current.anEq[nColUp];
120562 p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
120565 p->a = (struct StatSample*)&p->current.anLt[nColUp];
120566 p->aBest = &p->a[mxSample];
120567 pSpace = (u8*)(&p->a[mxSample+nCol]);
120569 p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
120570 p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
120571 p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
120573 assert( (pSpace - (u8*)p)==n );
120576 p->aBest[i].iCol = i;
120601 ** pNew and pOld are both candidate non-periodic samples selected for
120602 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
120609 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
120616 int nCol = pAccum->nCol;
120618 assert( pNew->iCol==pOld->iCol );
120619 for(i=pNew->iCol+1; i<nCol; i++){
120620 if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
120621 if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
120623 if( pNew->iHash>pOld->iHash ) return 1;
120633 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
120640 tRowcnt nEqNew = pNew->anEq[pNew->iCol];
120641 tRowcnt nEqOld = pOld->anEq[pOld->iCol];
120643 assert( pOld->isPSample==0 && pNew->isPSample==0 );
120644 assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
120648 if( pNew->iCol<pOld->iCol ) return 1;
120649 return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
120655 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
120656 ** remove the least desirable sample from p->a[] to make room.
120668 if( nEqZero>p->nMaxEqZero ){
120669 p->nMaxEqZero = nEqZero;
120671 if( pNew->isPSample==0 ){
120673 assert( pNew->anEq[pNew->iCol]>0 );
120680 for(i=p->nSample-1; i>=0; i--){
120681 StatSample *pOld = &p->a[i];
120682 if( pOld->anEq[pNew->iCol]==0 ){
120683 if( pOld->isPSample ) return;
120684 assert( pOld->iCol>pNew->iCol );
120692 pUpgrade->iCol = pNew->iCol;
120693 pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
120699 if( p->nSample>=p->mxSample ){
120700 StatSample *pMin = &p->a[p->iMin];
120701 tRowcnt *anEq = pMin->anEq;
120702 tRowcnt *anLt = pMin->anLt;
120703 tRowcnt *anDLt = pMin->anDLt;
120704 sampleClear(p->db, pMin);
120705 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
120706 pSample = &p->a[p->nSample-1];
120707 pSample->nRowid = 0;
120708 pSample->anEq = anEq;
120709 pSample->anDLt = anDLt;
120710 pSample->anLt = anLt;
120711 p->nSample = p->mxSample-1;
120714 /* The "rows less-than" for the rowid column must be greater than that
120715 ** for the last sample in the p->a[] array. Otherwise, the samples would
120717 assert( p->nSample==0
120718 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
120721 pSample = &p->a[p->nSample];
120723 p->nSample++;
120726 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
120729 if( p->nSample>=p->mxSample ){
120730 int iMin = -1;
120731 for(i=0; i<p->mxSample; i++){
120732 if( p->a[i].isPSample ) continue;
120733 if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
120738 p->iMin = iMin;
120746 ** p->current contains a sample that reflects the previous row of the
120755 for(i=(p->nCol-2); i>=iChng; i--){
120756 StatSample *pBest = &p->aBest[i];
120757 pBest->anEq[i] = p->current.anEq[i];
120758 if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
120763 /* Check that no sample contains an anEq[] entry with an index of
120764 ** p->nMaxEqZero or greater set to zero. */
120765 for(i=p->nSample-1; i>=0; i--){
120767 for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
120771 if( iChng<p->nMaxEqZero ){
120772 for(i=p->nSample-1; i>=0; i--){
120774 for(j=iChng; j<p->nCol; j++){
120775 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
120778 p->nMaxEqZero = iChng;
120788 ** C Index of left-most column to differ from previous row
120797 ** This SQL function usually returns NULL, but might return an integer
120798 ** if it wants the byte-code to do special processing.
120815 assert( p->nCol>0 );
120816 assert( iChng<p->nCol );
120818 if( p->nRow==0 ){
120821 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
120826 if( p->mxSample ) samplePushPrevious(p, iChng);
120833 p->current.anEq[i]++;
120836 for(i=iChng; i<p->nCol; i++){
120837 p->current.anDLt[i]++;
120839 if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i];
120840 p->current.anEq[i] = 1;
120845 p->nRow++;
120847 if( p->mxSample ){
120850 sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
120852 sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
120855 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
120857 nLt = p->current.anLt[p->nCol-1];
120859 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
120860 p->current.isPSample = 1;
120861 p->current.iCol = 0;
120862 sampleInsert(p, &p->current, p->nCol-1);
120863 p->current.isPSample = 0;
120867 for(i=0; i<(p->nCol-1); i++){
120868 p->current.iCol = i;
120869 if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
120870 sampleCopy(p, &p->aBest[i], &p->current);
120875 if( p->nLimit && p->nRow>(tRowcnt)p->nLimit*(p->nSkipAhead+1) ){
120876 p->nSkipAhead++;
120877 sqlite3_result_int(context, p->current.anDLt[0]>0);
120915 ** a one-parameter function, stat_get(P), that always returns the
120932 assert( eCall==STAT_GET_STAT1 || p->mxSample );
120944 ** for each indexed column. This additional integer is an estimate of
120957 ** I = (K+D-1)/D
120967 sqlite3StrAccumInit(&sStat, 0, 0, 0, (p->nKeyCol+1)*100);
120969 p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow);
120970 for(i=0; i<p->nKeyCol; i++){
120971 u64 nDistinct = p->current.anDLt[i] + 1;
120972 u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
120973 if( iVal==2 && p->nRow*10 <= nDistinct*11 ) iVal = 1;
120976 assert( p->current.anEq[i] || p->nRow==0 );
120983 if( p->iGet<0 ){
120985 p->iGet = 0;
120987 if( p->iGet<p->nSample ){
120988 StatSample *pS = p->a + p->iGet;
120989 if( pS->nRowid==0 ){
120990 sqlite3_result_int64(context, pS->u.iRowid);
120992 sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
121001 assert( p->iGet<p->nSample );
121003 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
121004 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
121006 aCnt = p->a[p->iGet].anDLt;
121007 p->iGet++;
121011 sqlite3StrAccumInit(&sStat, 0, 0, 0, p->nCol*100);
121012 for(i=0; i<p->nCol; i++){
121015 if( sStat.nChar ) sStat.nChar--;
121037 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat+1);
121050 ** of the k-th column of the pIdx index.
121058 assert( k>=0 && k<pIdx->nColumn );
121059 i = pIdx->aiColumn[k];
121061 VdbeComment((v,"%s.rowid",pIdx->zName));
121063 assert( pIdx->bHasExpr );
121064 VdbeComment((v,"%s.expr(%d)",pIdx->zName, k));
121066 VdbeComment((v,"%s.%s", pIdx->zName, pIdx->pTable->aCol[i].zCnName));
121074 ** Generate code to do an analysis of all indices associated with
121085 sqlite3 *db = pParse->db; /* Database handle */
121086 Index *pIdx; /* An index to being analyzed */
121091 int jZeroRows = -1; /* Jump from here if number of rows is zero */
121105 int doOnce = 1; /* Flag for a one-time computation */
121121 if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
121126 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
121130 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
121131 db->aDb[iDb].zDbSName ) ){
121137 if( db->xPreUpdateCallback ){
121140 pStat1->zName = (char*)&pStat1[1];
121141 memcpy(pStat1->zName, "sqlite_stat1", 13);
121142 pStat1->nCol = 3;
121143 pStat1->iPKey = -1;
121144 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNAMIC);
121148 /* Establish a read-lock on the table at the shared-cache level.
121149 ** Open a read-only cursor on the table. Also allocate a cursor number
121152 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
121155 pParse->nTab = MAX(pParse->nTab, iTab);
121157 sqlite3VdbeLoadString(v, regTabname, pTab->zName);
121159 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
121167 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
121169 nCol = pIdx->nKeyCol;
121170 zIdxName = pTab->zName;
121171 nColTest = nCol - 1;
121173 nCol = pIdx->nColumn;
121174 zIdxName = pIdx->zName;
121175 nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
121180 VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
121183 ** Pseudo-code for loop that calls stat_push():
121225 /* Open a read-only cursor on the index being analyzed. */
121226 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
121227 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
121229 VdbeComment((v, "%s", pIdx->zName));
121244 sqlite3VdbeAddOp2(v, OP_Integer, db->nAnalysisLimit, regTemp2);
121253 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regRowid);
121282 if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
121283 /* For a single-column UNIQUE index, once we have found a non-NULL
121290 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
121310 sqlite3VdbeJumpHere(v, addrNextRow-1);
121333 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
121335 regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
121336 for(j=0; j<pPk->nKeyCol; j++){
121337 k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
121338 assert( k>=0 && k<pIdx->nColumn );
121342 sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
121343 sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
121351 if( db->nAnalysisLimit ){
121367 if( pIdx->pPartIdxWhere ){
121368 /* Partial indexes might get a zero-entry in sqlite_stat1. But
121369 ** an empty table is omitted from sqlite_stat1. */
121379 sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
121385 if( OptimizationEnabled(db, SQLITE_Stat4) && db->nAnalysisLimit==0 ){
121408 for(pX=pTab->pIndex; pX; pX=pX->pNext){
121411 nColX = pX->nKeyCol;
121413 nColX = pX->nColumn;
121424 ** https://sqlite.org/forum/forumpost/83cb4a95a0 (2023-03-25)
121428 sqlite3ClearTempRegCache(pParse); /* tag-20230325-1 */
121449 sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
121463 VdbeComment((v, "%s", pTab->zName));
121473 sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
121492 ** Generate code that will do an analysis of an entire database
121495 sqlite3 *db = pParse->db;
121496 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
121503 iStatCur = pParse->nTab;
121504 pParse->nTab += 3;
121506 iMem = pParse->nMem+1;
121507 iTab = pParse->nTab;
121509 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
121522 ** Generate code that will do an analysis of a single table in
121531 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
121532 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
121534 iStatCur = pParse->nTab;
121535 pParse->nTab += 3;
121537 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
121539 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
121541 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
121547 ** when it recognizes an ANALYZE command.
121549 ** ANALYZE -- 1
121550 ** ANALYZE <database> -- 2
121551 ** ANALYZE ?<database>.?<tablename> -- 3
121558 sqlite3 *db = pParse->db;
121567 /* Read the database schema. If an error occurs, leave an error message
121569 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
121577 for(i=0; i<db->nDb; i++){
121581 }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
121585 /* Form 3: Analyze the table or index named as an argument */
121588 zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
121592 analyzeTable(pParse, pIdx->pTable, pIdx);
121600 if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
121616 ** The first argument points to a nul-terminated string containing a
121640 v = v*10 + c - '0';
121659 pIndex->bUnordered = 0;
121660 pIndex->noSkipScan = 0;
121663 pIndex->bUnordered = 1;
121664 }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
121667 pIndex->szIdxRow = sqlite3LogEst(sz);
121669 pIndex->noSkipScan = 1;
121672 else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
121673 pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
121688 ** argv[2] = results of analysis - on integer for each column
121705 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
121714 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
121720 int nCol = pIndex->nKeyCol+1;
121725 if( pIndex->aiRowEst==0 ){
121726 pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
121727 if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
121729 aiRowEst = pIndex->aiRowEst;
121731 pIndex->bUnordered = 0;
121732 decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
121733 pIndex->hasStat1 = 1;
121734 if( pIndex->pPartIdxWhere==0 ){
121735 pTable->nRowLogEst = pIndex->aiRowLogEst[0];
121736 pTable->tabFlags |= TF_HasStat1;
121740 fakeIdx.szIdxRow = pTable->szTabRow;
121744 decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
121745 pTable->szTabRow = fakeIdx.szIdxRow;
121746 pTable->tabFlags |= TF_HasStat1;
121760 if( pIdx->aSample ){
121762 for(j=0; j<pIdx->nSample; j++){
121763 IndexSample *p = &pIdx->aSample[j];
121764 sqlite3DbFree(db, p->p);
121766 sqlite3DbFree(db, pIdx->aSample);
121768 if( db->pnBytesFreed==0 ){
121769 pIdx->nSample = 0;
121770 pIdx->aSample = 0;
121780 ** Populate the pIdx->aAvgEq[] array based on the samples currently
121781 ** stored in pIdx->aSample[].
121785 IndexSample *aSample = pIdx->aSample;
121786 IndexSample *pFinal = &aSample[pIdx->nSample-1];
121789 if( pIdx->nSampleCol>1 ){
121794 nCol = pIdx->nSampleCol-1;
121795 pIdx->aAvgEq[nCol] = 1;
121798 int nSample = pIdx->nSample;
121806 if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
121807 nRow = pFinal->anLt[iCol];
121808 nDist100 = (i64)100 * pFinal->anDLt[iCol];
121809 nSample--;
121811 nRow = pIdx->aiRowEst[0];
121812 nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
121814 pIdx->nRowEst0 = nRow;
121821 if( i==(pIdx->nSample-1)
121830 avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
121833 pIdx->aAvgEq[iCol] = avgEq;
121839 ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
121874 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
121877 IndexSample *pSample; /* A slot in pIdx->aSample[] */
121879 assert( db->lookaside.bDisable );
121884 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
121903 assert( pIdx==0 || pIdx->nSample==0 );
121905 if( pIdx->aSample!=0 ){
121909 assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
121910 if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
121911 nIdxCol = pIdx->nKeyCol;
121913 nIdxCol = pIdx->nColumn;
121915 pIdx->nSampleCol = nIdxCol;
121916 pIdx->mxSample = nSample;
121921 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
121922 if( pIdx->aSample==0 ){
121926 pPtr = (u8*)pIdx->aSample;
121927 pPtr += ROUND8(nSample*sizeof(pIdx->aSample[0]));
121930 pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
121931 pIdx->pTable->tabFlags |= TF_HasStat4;
121933 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
121934 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
121935 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
121937 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
121946 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
121959 if( pIdx->nSample>=pIdx->mxSample ){
121966 nCol = pIdx->nSampleCol;
121971 pSample = &pIdx->aSample[pIdx->nSample];
121972 decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
121973 decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
121974 decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
121983 pSample->n = sqlite3_column_bytes(pStmt, 4);
121984 pSample->p = sqlite3DbMallocZero(db, pSample->n + 8);
121985 if( pSample->p==0 ){
121989 if( pSample->n ){
121990 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
121992 pIdx->nSample++;
122007 assert( db->lookaside.bDisable );
122038 ** If an OOM error occurs, this function always sets db->mallocFailed.
122047 Schema *pSchema = db->aDb[iDb].pSchema;
122050 assert( iDb>=0 && iDb<db->nDb );
122051 assert( db->aDb[iDb].pBt!=0 );
122055 for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
122057 pTab->tabFlags &= ~TF_HasStat1;
122059 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
122061 pIdx->hasStat1 = 0;
122064 pIdx->aSample = 0;
122070 sInfo.zDatabase = db->aDb[iDb].zDbSName;
122086 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
122088 if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
122098 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
122100 sqlite3_free(pIdx->aiRowEst);
122101 pIdx->aiRowEst = 0;
122133 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
122154 if( pExpr->op!=TK_ID ){
122157 pExpr->op = TK_STRING;
122169 sqlite3StrICmp(db->aDb[iDb].zDbSName, zName)==0
122175 ** An SQL user-function registered to do the work of an ATTACH statement. The
122176 ** three arguments to the function come directly from an attach statement:
122182 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
122185 ** If the db->init.reopenMemdb flags is set, then instead of attaching a
122186 ** new database, close the database on db->init.iDb and reopen it as an
122214 # define REOPEN_AS_MEMDB(db) (db->init.reopenMemdb)
122221 ** from sqlite3_deserialize() to close database db->init.iDb and
122233 pNew = &db->aDb[db->init.iDb];
122234 if( ALWAYS(pNew->pBt) ) sqlite3BtreeClose(pNew->pBt);
122235 pNew->pBt = pNewBt;
122236 pNew->pSchema = pNewSchema;
122252 if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
122253 zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
122254 db->aLimit[SQLITE_LIMIT_ATTACHED]
122258 for(i=0; i<db->nDb; i++){
122266 /* Allocate the new entry in the db->aDb[] array and initialize the schema
122269 if( db->aDb==db->aDbStatic ){
122270 aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
122272 memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
122274 aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(1+(i64)db->nDb));
122277 db->aDb = aNew;
122278 pNew = &db->aDb[db->nDb];
122285 flags = db->openFlags;
122286 rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
122289 sqlite3_result_error(context, zErr, -1);
122293 if( (db->flags & SQLITE_AttachWrite)==0 ){
122296 }else if( (db->flags & SQLITE_AttachCreate)==0 ){
122301 rc = sqlite3BtreeOpen(pVfs, zPath, db, &pNew->pBt, 0, flags);
122302 db->nDb++;
122303 pNew->zDbSName = sqlite3DbStrDup(db, zName);
122305 db->noSharedCache = 0;
122311 pNew->pSchema = sqlite3SchemaGet(db, pNew->pBt);
122312 if( !pNew->pSchema ){
122314 }else if( pNew->pSchema->file_format && pNew->pSchema->enc!=ENC(db) ){
122319 sqlite3BtreeEnter(pNew->pBt);
122320 pPager = sqlite3BtreePager(pNew->pBt);
122321 sqlite3PagerLockingMode(pPager, db->dfltLockMode);
122322 sqlite3BtreeSecureDelete(pNew->pBt,
122323 sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
122325 sqlite3BtreeSetPagerFlags(pNew->pBt,
122326 PAGER_SYNCHRONOUS_FULL | (db->flags & PAGER_FLAGS_MASK));
122328 sqlite3BtreeLeave(pNew->pBt);
122330 pNew->safety_level = SQLITE_DEFAULT_SYNCHRONOUS+1;
122331 if( rc==SQLITE_OK && pNew->zDbSName==0 ){
122338 ** remove the entry from the db->aDb[] array. i.e. put everything back the
122343 db->init.iDb = 0;
122344 db->mDbFlags &= ~(DBFLAG_SchemaKnownOk);
122346 if( db->setlkFlags & SQLITE_SETLK_BLOCK_ON_CONNECT ){
122348 sqlite3_file *fd = sqlite3PagerFile(sqlite3BtreePager(pNew->pBt));
122360 int iDb = db->nDb - 1;
122362 if( db->aDb[iDb].pBt ){
122363 sqlite3BtreeClose(db->aDb[iDb].pBt);
122364 db->aDb[iDb].pBt = 0;
122365 db->aDb[iDb].pSchema = 0;
122368 db->nDb = iDb;
122383 /* Return an error if we get here */
122385 sqlite3_result_error(context, zErrDyn, -1);
122392 ** An SQL user-function registered to do the work of an DETACH statement. The
122414 for(i=0; i<db->nDb; i++){
122415 pDb = &db->aDb[i];
122416 if( pDb->pBt==0 ) continue;
122420 if( i>=db->nDb ){
122428 if( sqlite3BtreeTxnState(pDb->pBt)!=SQLITE_TXN_NONE
122429 || sqlite3BtreeIsInBackup(pDb->pBt)
122437 assert( db->aDb[1].pSchema );
122438 pEntry = sqliteHashFirst(&db->aDb[1].pSchema->trigHash);
122441 if( pTrig->pTabSchema==pDb->pSchema ){
122442 pTrig->pTabSchema = pTrig->pSchema;
122447 sqlite3BtreeClose(pDb->pBt);
122448 pDb->pBt = 0;
122449 pDb->pSchema = 0;
122454 sqlite3_result_error(context, zErr, -1);
122473 sqlite3* db = pParse->db;
122478 if( pParse->nErr ) goto attach_end;
122493 if( pAuthArg->op==TK_STRING ){
122495 zAuthArg = pAuthArg->u.zToken;
122513 assert( v || db->mallocFailed );
122515 sqlite3VdbeAddFunctionCall(pParse, 0, regArgs+3-pFunc->nArg, regArgs+3,
122516 pFunc->nArg, pFunc, 0);
122517 /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
122551 ** Called by the parser to compile an ATTACH statement.
122575 DbFixer *pFix = p->u.pFix;
122576 if( !pFix->bTemp ) ExprSetProperty(pExpr, EP_FromDDL);
122577 if( pExpr->op==TK_VARIABLE ){
122578 if( pFix->pParse->db->init.busy ){
122579 pExpr->op = TK_NULL;
122581 sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
122592 DbFixer *pFix = p->u.pFix;
122595 sqlite3 *db = pFix->pParse->db;
122596 int iDb = sqlite3FindDbName(db, pFix->zDb);
122597 SrcList *pList = pSelect->pSrc;
122600 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
122601 if( pFix->bTemp==0 && pItem->fg.isSubquery==0 ){
122602 if( pItem->fg.fixedSchema==0 && pItem->u4.zDatabase!=0 ){
122603 if( iDb!=sqlite3FindDbName(db, pItem->u4.zDatabase) ){
122604 sqlite3ErrorMsg(pFix->pParse,
122606 pFix->zType, pFix->pName, pItem->u4.zDatabase);
122609 sqlite3DbFree(db, pItem->u4.zDatabase);
122610 pItem->fg.notCte = 1;
122611 pItem->fg.hadSchema = 1;
122613 pItem->u4.pSchema = pFix->pSchema;
122614 pItem->fg.fromDDL = 1;
122615 pItem->fg.fixedSchema = 1;
122618 if( pList->a[i].fg.isUsing==0
122619 && sqlite3WalkExpr(&pFix->w, pList->a[i].u3.pOn)
122625 if( pSelect->pWith ){
122626 for(i=0; i<pSelect->pWith->nCte; i++){
122627 if( sqlite3WalkSelect(p, pSelect->pWith->a[i].pSelect) ){
122646 sqlite3 *db = pParse->db;
122647 assert( db->nDb>iDb );
122648 pFix->pParse = pParse;
122649 pFix->zDb = db->aDb[iDb].zDbSName;
122650 pFix->pSchema = db->aDb[iDb].pSchema;
122651 pFix->zType = zType;
122652 pFix->pName = pName;
122653 pFix->bTemp = (iDb==1);
122654 pFix->w.pParse = pParse;
122655 pFix->w.xExprCallback = fixExprCb;
122656 pFix->w.xSelectCallback = fixSelectCb;
122657 pFix->w.xSelectCallback2 = sqlite3WalkWinDefnDummyCallback;
122658 pFix->w.walkerDepth = 0;
122659 pFix->w.eCode = 0;
122660 pFix->w.u.pFix = pFix;
122669 ** These routines are used to make sure that an index, trigger, or
122673 ** to an object in a different database, an error message is added to
122674 ** pParse->zErrMsg and these routines return non-zero. If everything
122686 res = sqlite3WalkSelect(&pFix->w, &s);
122695 return sqlite3WalkSelect(&pFix->w, pSelect);
122701 return sqlite3WalkExpr(&pFix->w, pExpr);
122711 if( sqlite3WalkSelect(&pFix->w, pStep->pSelect)
122712 || sqlite3WalkExpr(&pFix->w, pStep->pWhere)
122713 || sqlite3WalkExprList(&pFix->w, pStep->pExprList)
122714 || sqlite3FixSrcList(pFix, pStep->pFrom)
122721 for(pUp=pStep->pUpsert; pUp; pUp=pUp->pNextUpsert){
122722 if( sqlite3WalkExprList(&pFix->w, pUp->pUpsertTarget)
122723 || sqlite3WalkExpr(&pFix->w, pUp->pUpsertTargetWhere)
122724 || sqlite3WalkExprList(&pFix->w, pUp->pUpsertSet)
122725 || sqlite3WalkExpr(&pFix->w, pUp->pUpsertWhere)
122732 pStep = pStep->pNext;
122753 ** API. This facility is an optional feature of the library. Embedded
122755 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
122802 ** means that the SQL statement will never-run - the sqlite3_exec() call
122803 ** will return with an error. SQLITE_IGNORE means that the SQL statement
122818 sqlite3_mutex_enter(db->mutex);
122819 db->xAuth = (sqlite3_xauth)xAuth;
122820 db->pAuthArg = pArg;
122821 if( db->xAuth ) sqlite3ExpirePreparedStatements(db, 1);
122822 sqlite3_mutex_leave(db->mutex);
122827 ** Write an error message into pParse->zErrMsg that explains that the
122828 ** user-supplied authorization function returned an illegal value.
122832 pParse->rc = SQLITE_ERROR;
122837 ** table zTab in database zDb. This function assumes that an authorization
122841 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
122842 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
122850 sqlite3 *db = pParse->db; /* Database handle */
122851 char *zDb = db->aDb[iDb].zDbSName; /* Schema name of attached database */
122854 if( db->init.busy ) return SQLITE_OK;
122855 rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
122858 if( db->nDb>2 || iDb!=0 ) z = sqlite3_mprintf("%s.%z", zDb, z);
122860 pParse->rc = SQLITE_AUTH;
122874 ** then generate an error.
122884 int iSrc; /* Index in pTabList->a[] of table being read */
122888 assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
122890 assert( pParse->db->xAuth!=0 );
122891 iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
122893 /* An attempt to read a column out of a subquery or other
122898 if( pExpr->op==TK_TRIGGER ){
122899 pTab = pParse->pTriggerTab;
122902 for(iSrc=0; iSrc<pTabList->nSrc; iSrc++){
122903 if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
122904 pTab = pTabList->a[iSrc].pSTab;
122909 iCol = pExpr->iColumn;
122913 assert( iCol<pTab->nCol );
122914 zCol = pTab->aCol[iCol].zCnName;
122915 }else if( pTab->iPKey>=0 ){
122916 assert( pTab->iPKey<pTab->nCol );
122917 zCol = pTab->aCol[pTab->iPKey].zCnName;
122921 assert( iDb>=0 && iDb<pParse->db->nDb );
122922 if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
122923 pExpr->op = TK_NULL;
122928 ** Do an authorization check using the code and arguments given. Return
122940 sqlite3 *db = pParse->db;
122946 assert( !IN_RENAME_OBJECT || db->xAuth==0 );
122947 if( db->xAuth==0 || db->init.busy || IN_SPECIAL_PARSE ){
122951 /* EVIDENCE-OF: R-43249-19882 The third through sixth parameters to the
122952 ** callback are either NULL pointers or zero-terminated strings that
122960 testcase( pParse->zAuthContext==0 );
122962 rc = db->xAuth(db->pAuthArg,code,zArg1,zArg2,zArg3,pParse->zAuthContext);
122965 pParse->rc = SQLITE_AUTH;
122974 ** Push an authorization context. After this routine is called, the
122976 ** popped. Or if pParse==0, this routine is a no-op.
122984 pContext->pParse = pParse;
122985 pContext->zAuthContext = pParse->zAuthContext;
122986 pParse->zAuthContext = zContext;
122990 ** Pop an authorization context that was previously pushed
122994 if( pContext->pParse ){
122995 pContext->pParse->zAuthContext = pContext->zAuthContext;
122996 pContext->pParse = 0;
123043 ** Record the fact that we want to lock a table at run-time.
123066 for(i=0; i<pToplevel->nTableLock; i++){
123067 p = &pToplevel->aTableLock[i];
123068 if( p->iDb==iDb && p->iTab==iTab ){
123069 p->isWriteLock = (p->isWriteLock || isWriteLock);
123074 assert( pToplevel->nTableLock < 0x7fff0000 );
123075 nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
123076 pToplevel->aTableLock =
123077 sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
123078 if( pToplevel->aTableLock ){
123079 p = &pToplevel->aTableLock[pToplevel->nTableLock++];
123080 p->iDb = iDb;
123081 p->iTab = iTab;
123082 p->isWriteLock = isWriteLock;
123083 p->zLockName = zName;
123085 pToplevel->nTableLock = 0;
123086 sqlite3OomFault(pToplevel->db);
123097 if( !sqlite3BtreeSharable(pParse->db->aDb[iDb].pBt) ) return;
123102 ** Code an OP_TableLock instruction for each table locked by the
123107 Vdbe *pVdbe = pParse->pVdbe;
123110 for(i=0; i<pParse->nTableLock; i++){
123111 TableLock *p = &pParse->aTableLock[i];
123112 int p1 = p->iDb;
123113 sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
123114 p->zLockName, P4_STATIC);
123122 ** Return TRUE if the given yDbMask object is empty - if it contains no
123141 ** Note that if an error occurred, it might be the case that
123149 assert( pParse->pToplevel==0 );
123150 db = pParse->db;
123151 assert( db->pParse==pParse );
123152 if( pParse->nested ) return;
123153 if( pParse->nErr ){
123154 if( db->mallocFailed ) pParse->rc = SQLITE_NOMEM;
123157 assert( db->mallocFailed==0 );
123162 v = pParse->pVdbe;
123164 if( db->init.busy ){
123165 pParse->rc = SQLITE_DONE;
123169 if( v==0 ) pParse->rc = SQLITE_ERROR;
123171 assert( !pParse->isMultiWrite
123172 || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
123174 if( pParse->bReturning ){
123179 assert( !pParse->isCreate );
123180 pReturning = pParse->u1.d.pReturning;
123181 if( pReturning->nRetCol ){
123184 sqlite3VdbeAddOp1(v, OP_Rewind, pReturning->iRetCur);
123186 reg = pReturning->iRetReg;
123187 for(i=0; i<pReturning->nRetCol; i++){
123188 sqlite3VdbeAddOp3(v, OP_Column, pReturning->iRetCur, i, reg+i);
123191 sqlite3VdbeAddOp2(v, OP_Next, pReturning->iRetCur, addrRewind+1);
123204 assert( pParse->nErr>0 || sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
123206 assert( db->nDb>0 );
123210 if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
123212 pSchema = db->aDb[iDb].pSchema;
123216 DbMaskTest(pParse->writeMask,iDb), /* P2 */
123217 pSchema->schema_cookie, /* P3 */
123218 pSchema->iGeneration /* P4 */
123220 if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
123222 "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
123223 }while( ++iDb<db->nDb );
123225 for(i=0; i<pParse->nVtabLock; i++){
123226 char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
123229 pParse->nVtabLock = 0;
123234 ** obtain the required table-locks. This is a no-op unless the
123235 ** shared-cache feature is enabled.
123237 if( pParse->nTableLock ) codeTableLocks(pParse);
123242 if( pParse->pAinc ) sqlite3AutoincrementBegin(pParse);
123246 if( pParse->pConstExpr ){
123247 ExprList *pEL = pParse->pConstExpr;
123248 pParse->okConstFactor = 0;
123249 for(i=0; i<pEL->nExpr; i++){
123250 assert( pEL->a[i].u.iConstExprReg>0 );
123251 sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
123255 if( pParse->bReturning ){
123257 assert( !pParse->isCreate );
123258 pRet = pParse->u1.d.pReturning;
123259 if( pRet->nRetCol ){
123260 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pRet->iRetCur, pRet->nRetCol);
123270 assert( v!=0 || pParse->nErr );
123271 assert( db->mallocFailed==0 || pParse->nErr );
123272 if( pParse->nErr==0 ){
123275 assert( pParse->pAinc==0 || pParse->nTab>0 );
123277 pParse->rc = SQLITE_DONE;
123279 pParse->rc = SQLITE_ERROR;
123292 ** * Built-in SQL functions always take precedence over application-defined
123294 ** built-in function.
123299 sqlite3 *db = pParse->db;
123300 u32 savedDbFlags = db->mDbFlags;
123303 if( pParse->nErr ) return;
123304 if( pParse->eParseMode ) return;
123305 assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
123310 /* This can result either from an OOM or because the formatted string
123312 ** an error */
123313 if( !db->mallocFailed ) pParse->rc = SQLITE_TOOBIG;
123314 pParse->nErr++;
123317 pParse->nested++;
123320 db->mDbFlags |= DBFLAG_PreferBuiltin;
123322 db->mDbFlags = savedDbFlags;
123325 pParse->nested--;
123329 ** Locate the in-memory structure that describes a particular database
123347 for(i=0; i<db->nDb; i++){
123348 if( sqlite3StrICmp(zDatabase, db->aDb[i].zDbSName)==0 ) break;
123350 if( i>=db->nDb ){
123359 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
123366 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
123371 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash,
123378 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash, zName);
123381 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, zName);
123384 for(i=2; i<db->nDb; i++){
123386 p = sqlite3HashFind(&db->aDb[i].pSchema->tblHash, zName);
123391 p = sqlite3HashFind(&db->aDb[0].pSchema->tblHash, LEGACY_SCHEMA_TABLE);
123393 p = sqlite3HashFind(&db->aDb[1].pSchema->tblHash,
123402 ** Locate the in-memory structure that describes a particular database
123404 ** database containing the table. Return NULL if not found. Also leave an
123405 ** error message in pParse->zErrMsg.
123408 ** routine leaves an error message in pParse->zErrMsg where
123418 sqlite3 *db = pParse->db;
123420 /* Read the database schema. If an error occurs, leave an error message
123422 if( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0
123432 ** CREATE, then check to see if it is the name of an virtual table that
123433 ** can be an eponymous virtual table. */
123434 if( (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)==0 && db->init.busy==0 ){
123435 Module *pMod = (Module*)sqlite3HashFind(&db->aModule, zName);
123440 testcase( pMod->pEpoTab==0 );
123441 return pMod->pEpoTab;
123446 pParse->checkSchema = 1;
123447 }else if( IsVirtual(p) && (pParse->prepFlags & SQLITE_PREPARE_NO_VTAB)!=0 ){
123459 assert( HasRowid(p) || p->iPKey<0 );
123470 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
123471 ** non-NULL if it is part of a view or trigger program definition. See
123480 if( p->fg.fixedSchema ){
123481 int iDb = sqlite3SchemaToIndex(pParse->db, p->u4.pSchema);
123482 zDb = pParse->db->aDb[iDb].zDbSName;
123484 assert( !p->fg.isSubquery );
123485 zDb = p->u4.zDatabase;
123487 return sqlite3LocateTable(pParse, flags, p->zName, zDb);
123507 ** Locate the in-memory structure that describes
123523 for(i=OMIT_TEMPDB; i<db->nDb; i++){
123525 Schema *pSchema = db->aDb[j].pSchema;
123529 p = sqlite3HashFind(&pSchema->idxHash, zName);
123536 ** Reclaim the memory used by an index
123542 sqlite3ExprDelete(db, p->pPartIdxWhere);
123543 sqlite3ExprListDelete(db, p->aColExpr);
123544 sqlite3DbFree(db, p->zColAff);
123545 if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
123547 sqlite3_free(p->aiRowEst);
123563 pHash = &db->aDb[iDb].pSchema->idxHash;
123566 if( pIndex->pTable->pIndex==pIndex ){
123567 pIndex->pTable->pIndex = pIndex->pNext;
123572 p = pIndex->pTable->pIndex;
123573 while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
123574 if( ALWAYS(p && p->pNext==pIndex) ){
123575 p->pNext = pIndex->pNext;
123580 db->mDbFlags |= DBFLAG_SchemaChange;
123584 ** Look through the list of open database files in db->aDb[] and if
123586 ** db->aDb[] structure to a smaller size, if possible.
123593 for(i=j=2; i<db->nDb; i++){
123594 struct Db *pDb = &db->aDb[i];
123595 if( pDb->pBt==0 ){
123596 sqlite3DbFree(db, pDb->zDbSName);
123597 pDb->zDbSName = 0;
123601 db->aDb[j] = db->aDb[i];
123605 db->nDb = j;
123606 if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
123607 memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
123608 sqlite3DbFree(db, db->aDb);
123609 db->aDb = db->aDbStatic;
123615 ** TEMP schema. The reset is deferred if db->nSchemaLock is not zero.
123620 assert( iDb<db->nDb );
123626 db->mDbFlags &= ~DBFLAG_SchemaKnownOk;
123629 if( db->nSchemaLock==0 ){
123630 for(i=0; i<db->nDb; i++){
123632 sqlite3SchemaClear(db->aDb[i].pSchema);
123645 for(i=0; i<db->nDb; i++){
123646 Db *pDb = &db->aDb[i];
123647 if( pDb->pSchema ){
123648 if( db->nSchemaLock==0 ){
123649 sqlite3SchemaClear(pDb->pSchema);
123655 db->mDbFlags &= ~(DBFLAG_SchemaChange|DBFLAG_SchemaKnownOk);
123658 if( db->nSchemaLock==0 ){
123667 db->mDbFlags &= ~DBFLAG_SchemaChange;
123683 pList = pTab->u.tab.pDfltList;
123684 if( pCol->iDflt==0
123686 || NEVER(pList->nExpr<pCol->iDflt)
123688 pCol->iDflt = pList==0 ? 1 : pList->nExpr+1;
123689 pTab->u.tab.pDfltList = sqlite3ExprListAppend(pParse, pList, pExpr);
123691 sqlite3ExprDelete(pParse->db, pList->a[pCol->iDflt-1].pExpr);
123692 pList->a[pCol->iDflt-1].pExpr = pExpr;
123702 if( pCol->iDflt==0 ) return 0;
123704 if( NEVER(pTab->u.tab.pDfltList==0) ) return 0;
123705 if( NEVER(pTab->u.tab.pDfltList->nExpr<pCol->iDflt) ) return 0;
123706 return pTab->u.tab.pDfltList->a[pCol->iDflt-1].pExpr;
123721 n = sqlite3Strlen30(pCol->zCnName) + 1;
123722 if( pCol->colFlags & COLFLAG_HASTYPE ){
123723 n += sqlite3Strlen30(pCol->zCnName+n) + 1;
123726 zNew = sqlite3DbRealloc(db, pCol->zCnName, nColl+n);
123728 pCol->zCnName = zNew;
123729 memcpy(pCol->zCnName + n, zColl, nColl);
123730 pCol->colFlags |= COLFLAG_HASCOLL;
123739 if( (pCol->colFlags & COLFLAG_HASCOLL)==0 ) return 0;
123740 z = pCol->zCnName;
123742 if( pCol->colFlags & COLFLAG_HASTYPE ){
123757 if( (pCol = pTable->aCol)!=0 ){
123758 for(i=0; i<pTable->nCol; i++, pCol++){
123759 assert( pCol->zCnName==0 || pCol->hName==sqlite3StrIHash(pCol->zCnName) );
123760 sqlite3DbFree(db, pCol->zCnName);
123762 sqlite3DbNNFreeNN(db, pTable->aCol);
123764 sqlite3ExprListDelete(db, pTable->u.tab.pDfltList);
123766 if( db->pnBytesFreed==0 ){
123767 pTable->aCol = 0;
123768 pTable->nCol = 0;
123770 pTable->u.tab.pDfltList = 0;
123788 ** db parameter can be used with db->pnBytesFreed to measure the memory
123804 if( !db->mallocFailed && (pTable->tabFlags & TF_Ephemeral)==0 ){
123810 for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
123811 pNext = pIndex->pNext;
123812 assert( pIndex->pSchema==pTable->pSchema
123813 || (IsVirtual(pTable) && pIndex->idxType!=SQLITE_IDXTYPE_APPDEF) );
123814 if( db->pnBytesFreed==0 && !IsVirtual(pTable) ){
123815 char *zName = pIndex->zName;
123817 &pIndex->pSchema->idxHash, zName, 0
123819 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
123835 sqlite3SelectDelete(db, pTable->u.view.pSelect);
123841 sqlite3DbFree(db, pTable->zName);
123842 sqlite3DbFree(db, pTable->zColAff);
123843 sqlite3ExprListDelete(db, pTable->pCheck);
123853 if( db->pnBytesFreed==0 && (--pTable->nTabRef)>0 ) return;
123870 assert( iDb>=0 && iDb<db->nDb );
123873 testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
123874 pDb = &db->aDb[iDb];
123875 p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
123877 db->mDbFlags |= DBFLAG_SchemaChange;
123896 zName = sqlite3DbStrNDup(db, (const char*)pName->z, pName->n);
123912 if( p->nTab==0 ){
123913 p->nTab = 1;
123918 ** Parameter zName points to a nul-terminated buffer containing the name
123919 ** of a database ("main", "temp" or the name of an attached db). This
123920 ** function returns the index of the named database in db->aDb[], or
123921 ** -1 if the named db cannot be found.
123924 int i = -1; /* Database number */
123927 for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
123928 if( 0==sqlite3_stricmp(pDb->zDbSName, zName) ) break;
123929 /* "main" is always an acceptable alias for the primary database
123939 ** "temp" or the name of an attached db). This routine returns the
123940 ** index of the named database in db->aDb[], or -1 if the named db
123975 sqlite3 *db = pParse->db;
123978 if( pName2->n>0 ){
123979 if( db->init.busy ) {
123981 return -1;
123987 return -1;
123990 assert( db->init.iDb==0 || db->init.busy || IN_SPECIAL_PARSE
123991 || (db->mDbFlags & DBFLAG_Vacuum)!=0);
123992 iDb = db->init.iDb;
124002 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==0 );
124003 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
124005 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
124007 testcase( (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==
124009 return (db->flags&(SQLITE_WriteSchema|SQLITE_Defensive))==SQLITE_WriteSchema;
124013 ** This routine is used to check if the UTF-8 string zName is a legal
124029 sqlite3 *db = pParse->db;
124031 || db->init.imposterTable
124037 if( db->init.busy ){
124038 if( sqlite3_stricmp(zType, db->init.azInit[0])
124039 || sqlite3_stricmp(zName, db->init.azInit[1])
124040 || sqlite3_stricmp(zTblName, db->init.azInit[2])
124046 if( (pParse->nested==0 && 0==sqlite3StrNICmp(zName, "sqlite_", 7))
124063 for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
124068 ** Convert an table column number into a index column number. That is,
124070 ** find the (first) offset of that column in index pIdx. Or return -1
124076 assert( iCol>=(-1) && iCol<=SQLITE_MAX_COLUMN );
124077 assert( pIdx->nColumn<=SQLITE_MAX_COLUMN+1 );
124079 for(i=0; i<pIdx->nColumn; i++){
124080 if( iCol16==pIdx->aiColumn[i] ){
124084 return -1;
124097 ** If SQLITE_OMIT_GENERATED_COLUMNS, this routine is a no-op macro.
124100 if( pTab->tabFlags & TF_HasVirtual ){
124103 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) iCol++;
124115 ** the N-th virtual column (zero-based) then the storage number is
124116 ** the number of non-virtual columns in the table plus N.
124132 ** -- 0 1 2 3 4 5 6 7 8
124143 ** this routine is a no-op macro. If the pTab does not have any virtual
124144 ** columns, then this routine is no-op that always return iCol. If iCol
124150 assert( iCol<pTab->nCol );
124151 if( (pTab->tabFlags & TF_HasVirtual)==0 || iCol<0 ) return iCol;
124153 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) n++;
124155 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ){
124157 return pTab->nNVCol + i - n;
124171 ** is a read-only no-op.
124174 int iReg = ++pParse->nMem;
124192 ** The new table record is initialized and put in pParse->pNewTable.
124209 sqlite3 *db = pParse->db;
124214 if( db->init.busy && db->init.newTnum==1 ){
124216 iDb = db->init.iDb;
124223 if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
124235 pParse->sNameToken = *pName;
124240 if( db->init.iDb==1 ) isTemp = 1;
124251 char *zDb = db->aDb[iDb].zDbSName;
124262 /* Make sure the new table name does not collide with an existing
124263 ** index or table name in the same database. Issue an error message if
124265 ** to an sqlite3_declare_vtab() call. In that case only the column names
124270 char *zDb = db->aDb[iDb].zDbSName;
124280 assert( !db->init.busy || CORRUPT_DB );
124287 sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
124294 assert( db->mallocFailed );
124295 pParse->rc = SQLITE_NOMEM_BKPT;
124296 pParse->nErr++;
124299 pTable->zName = zName;
124300 pTable->iPKey = -1;
124301 pTable->pSchema = db->aDb[iDb].pSchema;
124302 pTable->nTabRef = 1;
124304 pTable->nRowLogEst = sqlite3LogEst(SQLITE_DEFAULT_ROWEST);
124306 pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
124308 assert( pParse->pNewTable==0 );
124309 pParse->pNewTable = pTable;
124319 if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
124323 /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
124336 assert( pParse->isCreate );
124337 reg1 = pParse->u1.cr.regRowid = ++pParse->nMem;
124338 reg2 = pParse->u1.cr.regRoot = ++pParse->nMem;
124339 reg3 = ++pParse->nMem;
124343 fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
124349 /* This just creates a place-holder record in the sqlite_schema table.
124353 ** The rowid for the new entry is left in register pParse->u1.cr.regRowid.
124354 ** The root page of the new table is left in reg pParse->u1.cr.regRoot.
124364 assert( !pParse->bReturning );
124365 pParse->u1.cr.addrCrTab =
124376 /* Normal (non-error) return. */
124379 /* If an error occurs, we jump here */
124381 pParse->checkSchema = 1;
124391 if( sqlite3_strnicmp(pCol->zCnName, "__hidden__", 10)==0 ){
124392 pCol->colFlags |= COLFLAG_HIDDEN;
124393 if( pTab ) pTab->tabFlags |= TF_HasHidden;
124394 }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
124395 pTab->tabFlags |= TF_OOOHidden;
124406 pHash = &(db->aDb[1].pSchema->trigHash);
124407 sqlite3HashInsert(pHash, pRet->zName, 0);
124408 sqlite3ExprListDelete(db, pRet->pReturnEL);
124418 ** The trigger has the Trigger.bReturning flag and an opcode of
124431 sqlite3 *db = pParse->db;
124432 if( pParse->pNewTrigger ){
124435 assert( pParse->bReturning==0 || pParse->ifNotExists );
124437 pParse->bReturning = 1;
124443 assert( !pParse->isCreate );
124444 pParse->u1.d.pReturning = pRet;
124445 pRet->pParse = pParse;
124446 pRet->pReturnEL = pList;
124448 testcase( pParse->earlyCleanup );
124449 if( db->mallocFailed ) return;
124450 sqlite3_snprintf(sizeof(pRet->zName), pRet->zName,
124452 pRet->retTrig.zName = pRet->zName;
124453 pRet->retTrig.op = TK_RETURNING;
124454 pRet->retTrig.tr_tm = TRIGGER_AFTER;
124455 pRet->retTrig.bReturning = 1;
124456 pRet->retTrig.pSchema = db->aDb[1].pSchema;
124457 pRet->retTrig.pTabSchema = db->aDb[1].pSchema;
124458 pRet->retTrig.step_list = &pRet->retTStep;
124459 pRet->retTStep.op = TK_RETURNING;
124460 pRet->retTStep.pTrig = &pRet->retTrig;
124461 pRet->retTStep.pExprList = pList;
124462 pHash = &(db->aDb[1].pSchema->trigHash);
124463 assert( sqlite3HashFind(pHash, pRet->zName)==0
124464 || pParse->nErr || pParse->ifNotExists );
124465 if( sqlite3HashInsert(pHash, pRet->zName, &pRet->retTrig)
124466 ==&pRet->retTrig ){
124485 sqlite3 *db = pParse->db;
124491 if( (p = pParse->pNewTable)==0 ) return;
124492 if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
124493 sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
124503 && sqlite3_strnicmp(sType.z+(sType.n-6),"always",6)==0
124505 sType.n -= 6;
124506 while( ALWAYS(sType.n>0) && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
124508 && sqlite3_strnicmp(sType.z+(sType.n-9),"generated",9)==0
124510 sType.n -= 9;
124511 while( sType.n>0 && sqlite3Isspace(sType.z[sType.n-1]) ) sType.n--;
124539 if( p->nCol && sqlite3ColumnIndex(p, z)>=0 ){
124544 aNew = sqlite3DbRealloc(db,p->aCol,((i64)p->nCol+1)*sizeof(p->aCol[0]));
124549 p->aCol = aNew;
124550 pCol = &p->aCol[p->nCol];
124551 memset(pCol, 0, sizeof(p->aCol[0]));
124552 pCol->zCnName = z;
124553 pCol->hName = sqlite3StrIHash(z);
124559 pCol->affinity = affinity;
124560 pCol->eCType = eType;
124561 pCol->szEst = szEst;
124565 pCol->colFlags |= COLFLAG_SORTERREF;
124574 pCol->affinity = sqlite3AffinityType(zType, pCol);
124575 pCol->colFlags |= COLFLAG_HASTYPE;
124577 if( p->nCol<=0xff ){
124578 u8 h = pCol->hName % sizeof(p->aHx);
124579 p->aHx[h] = p->nCol;
124581 p->nCol++;
124582 p->nNVCol++;
124583 assert( pParse->isCreate );
124584 pParse->u1.cr.constraintName.n = 0;
124596 p = pParse->pNewTable;
124597 if( p==0 || NEVER(p->nCol<1) ) return;
124598 pCol = &p->aCol[p->nCol-1];
124599 pCol->notNull = (u8)onError;
124600 p->tabFlags |= TF_HasNotNull;
124604 if( pCol->colFlags & COLFLAG_UNIQUE ){
124606 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
124607 assert( pIdx->nKeyCol==1 && pIdx->onError!=OE_None );
124608 if( pIdx->aiColumn[0]==p->nCol-1 ){
124609 pIdx->uniqNotNull = 1;
124619 ** This routine does a case-independent search of zType for the
124627 ** --------------------------------
124678 /* If pCol is not NULL, store an estimate of the field size. The
124679 ** estimate is scaled so that the size of an integer is 1. */
124686 /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
124693 v = 16; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
124698 pCol->colFlags |= COLFLAG_SORTERREF;
124703 pCol->szEst = v;
124712 ** Default value expressions must be constant. Raise an exception if this
124726 sqlite3 *db = pParse->db;
124727 p = pParse->pNewTable;
124729 int isInit = db->init.busy && db->init.iDb!=1;
124730 pCol = &(p->aCol[p->nCol-1]);
124733 pCol->zCnName);
124735 }else if( pCol->colFlags & COLFLAG_GENERATED ){
124736 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
124737 testcase( pCol->colFlags & COLFLAG_STORED );
124773 ** if the expression is just a TK_STRING with an optional COLLATE clause.
124778 if( p->op==TK_STRING ){
124779 p->op = TK_ID;
124780 }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
124781 p->pLeft->op = TK_ID;
124789 pCol->colFlags |= COLFLAG_PRIMKEY;
124791 if( pCol->colFlags & COLFLAG_GENERATED ){
124792 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
124793 testcase( pCol->colFlags & COLFLAG_STORED );
124806 ** a primary key (and this is the second primary key) then create an
124812 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
124815 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
124825 Table *pTab = pParse->pNewTable;
124827 int iCol = -1, i;
124830 if( pTab->tabFlags & TF_HasPrimaryKey ){
124832 "table \"%s\" has more than one primary key", pTab->zName);
124835 pTab->tabFlags |= TF_HasPrimaryKey;
124837 iCol = pTab->nCol - 1;
124838 pCol = &pTab->aCol[iCol];
124842 nTerm = pList->nExpr;
124844 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
124847 if( pCExpr->op==TK_ID ){
124849 iCol = sqlite3ColumnIndex(pTab, pCExpr->u.zToken);
124851 pCol = &pTab->aCol[iCol];
124859 && pCol->eCType==COLTYPE_INTEGER
124863 Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[0].pExpr);
124864 sqlite3RenameTokenRemap(pParse, &pTab->iPKey, pCExpr);
124866 pTab->iPKey = iCol;
124867 pTab->keyConf = (u8)onError;
124869 pTab->tabFlags |= autoInc*TF_Autoincrement;
124870 if( pList ) pParse->iPkSortOrder = pList->a[0].fg.sortFlags;
124874 sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
124884 sqlite3ExprListDelete(pParse->db, pList);
124898 Table *pTab = pParse->pNewTable;
124899 sqlite3 *db = pParse->db;
124901 && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
124903 pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
124904 assert( pParse->isCreate );
124905 if( pParse->u1.cr.constraintName.n ){
124906 sqlite3ExprListSetName(pParse, pTab->pCheck,
124907 &pParse->u1.cr.constraintName, 1);
124911 while( sqlite3Isspace(zEnd[-1]) ){ zEnd--; }
124913 t.n = (int)(zEnd - t.z);
124914 sqlite3ExprListSetName(pParse, pTab->pCheck, &t, 1);
124919 sqlite3ExprDelete(pParse->db, pCheckExpr);
124933 if( (p = pParse->pNewTable)==0 || IN_RENAME_OBJECT ) return;
124934 i = p->nCol-1;
124935 db = pParse->db;
124941 sqlite3ColumnSetColl(db, &p->aCol[i], zColl);
124944 ** then an index may have been created on this column before the
124947 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
124948 assert( pIdx->nKeyCol==1 );
124949 if( pIdx->aiColumn[0]==i ){
124950 pIdx->azColl[0] = sqlite3ColumnColl(&p->aCol[i]);
124963 Table *pTab = pParse->pNewTable;
124966 /* generated column in an CREATE TABLE IF NOT EXISTS that already exists */
124969 pCol = &(pTab->aCol[pTab->nCol-1]);
124974 if( pCol->iDflt>0 ) goto generated_error;
124976 if( pType->n==7 && sqlite3StrNICmp("virtual",pType->z,7)==0 ){
124977 /* no-op */
124978 }else if( pType->n==6 && sqlite3StrNICmp("stored",pType->z,6)==0 ){
124984 if( eType==COLFLAG_VIRTUAL ) pTab->nNVCol--;
124985 pCol->colFlags |= eType;
124988 pTab->tabFlags |= eType;
124989 if( pCol->colFlags & COLFLAG_PRIMKEY ){
124992 if( ALWAYS(pExpr) && pExpr->op==TK_ID ){
124995 ** optimizations to work correctly. So if the value is not an expression,
124999 if( pExpr && pExpr->op!=TK_RAISE ) pExpr->affExpr = pCol->affinity;
125006 pCol->zCnName);
125008 sqlite3ExprDelete(pParse->db, pExpr);
125011 ** SQLITE_OMIT_GENERATED_COLUMNS compile-time option is used. */
125013 sqlite3ExprDelete(pParse->db, pExpr);
125027 ** This plan is not completely bullet-proof. It is possible for
125033 ** IMPLEMENTATION-OF: R-34230-56049 SQLite automatically increments
125034 ** the schema-version whenever the schema changes.
125037 sqlite3 *db = pParse->db;
125038 Vdbe *v = pParse->pVdbe;
125041 (int)(1+(unsigned)db->aDb[iDb].pSchema->schema_cookie));
125061 ** The first parameter is a pointer to an output buffer. The second
125062 ** parameter is a pointer to an integer that contains the offset at
125064 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
125069 ** characters, does not begin with a digit and is not an SQL keyword,
125071 ** it is quoted using double-quotes.
125108 for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
125109 n += identLength(pCol->zCnName) + 5;
125111 n += identLength(p->zName);
125121 n += 35 + 6*p->nCol;
125130 identPut(zStmt, &k, p->zName);
125132 for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
125148 identPut(zStmt, &k, pCol->zCnName);
125150 assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
125151 assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
125152 testcase( pCol->affinity==SQLITE_AFF_BLOB );
125153 testcase( pCol->affinity==SQLITE_AFF_TEXT );
125154 testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
125155 testcase( pCol->affinity==SQLITE_AFF_INTEGER );
125156 testcase( pCol->affinity==SQLITE_AFF_REAL );
125157 testcase( pCol->affinity==SQLITE_AFF_FLEXNUM );
125159 zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
125161 assert( pCol->affinity==SQLITE_AFF_BLOB
125162 || pCol->affinity==SQLITE_AFF_FLEXNUM
125163 || pCol->affinity==sqlite3AffinityType(zType, 0) );
125176 ** Resize an Index object to hold N columns total. Return SQLITE_OK
125177 ** on success and SQLITE_NOMEM on an OOM error.
125183 if( pIdx->nColumn>=N ) return SQLITE_OK;
125184 db = pParse->db;
125186 assert( N <= SQLITE_MAX_COLUMN*2 /* tag-20250221-1 */ );
125187 testcase( N==2*pParse->db->aLimit[SQLITE_LIMIT_COLUMN] );
125188 assert( pIdx->isResized==0 );
125192 memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
125193 pIdx->azColl = (const char**)zExtra;
125195 memcpy(zExtra, pIdx->aiRowLogEst, sizeof(LogEst)*(pIdx->nKeyCol+1));
125196 pIdx->aiRowLogEst = (LogEst*)zExtra;
125198 memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
125199 pIdx->aiColumn = (i16*)zExtra;
125201 memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
125202 pIdx->aSortOrder = (u8*)zExtra;
125203 pIdx->nColumn = (u16)N; /* See tag-20250221-1 above for proof of safety */
125204 pIdx->isResized = 1;
125215 for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
125216 wTable += pTabCol->szEst;
125218 if( pTab->iPKey<0 ) wTable++;
125219 pTab->szTabRow = sqlite3LogEst(wTable*4);
125223 ** Estimate the average size of a row for an index.
125228 const Column *aCol = pIdx->pTable->aCol;
125229 for(i=0; i<pIdx->nColumn; i++){
125230 i16 x = pIdx->aiColumn[i];
125231 assert( x<pIdx->pTable->nCol );
125234 pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
125239 ** first nCol entries of an index.
125242 while( nCol-- > 0 ){
125252 ** match the iCol-th entry of pPk. pPk is always a WITHOUT ROWID
125253 ** PRIMARY KEY index. pIdx is an index on the same table. pIdx may
125265 assert( nKey<=pIdx->nColumn );
125266 assert( iCol<MAX(pPk->nColumn,pPk->nKeyCol) );
125267 assert( pPk->idxType==SQLITE_IDXTYPE_PRIMARYKEY );
125268 assert( pPk->pTable->tabFlags & TF_WithoutRowid );
125269 assert( pPk->pTable==pIdx->pTable );
125271 j = pPk->aiColumn[iCol];
125274 assert( pIdx->aiColumn[i]>=0 || j>=0 );
125275 if( pIdx->aiColumn[i]==j
125276 && sqlite3StrICmp(pIdx->azColl[i], pPk->azColl[iCol])==0
125289 ** high-order bit of colNotIdxed is always 1. All unindexed columns
125292 ** 2019-10-24: For the purpose of this computation, virtual columns are
125300 ** The colNotIdxed mask is AND-ed with the SrcList.a[].colUsed mask
125306 Table *pTab = pIdx->pTable;
125307 for(j=pIdx->nColumn-1; j>=0; j--){
125308 int x = pIdx->aiColumn[j];
125309 if( x>=0 && (pTab->aCol[x].colFlags & COLFLAG_VIRTUAL)==0 ){
125310 testcase( x==BMS-1 );
125311 testcase( x==BMS-2 );
125312 if( x<BMS-1 ) m |= MASKBIT(x);
125315 pIdx->colNotIdxed = ~m;
125316 assert( (pIdx->colNotIdxed>>63)==1 ); /* See note-20221022-a */
125349 sqlite3 *db = pParse->db;
125350 Vdbe *v = pParse->pVdbe;
125354 if( !db->init.imposterTable ){
125355 for(i=0; i<pTab->nCol; i++){
125356 if( (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
125357 && (pTab->aCol[i].notNull==OE_None)
125359 pTab->aCol[i].notNull = OE_Abort;
125362 pTab->tabFlags |= TF_HasNotNull;
125368 assert( !pParse->bReturning );
125369 if( pParse->u1.cr.addrCrTab ){
125371 sqlite3VdbeChangeP3(v, pParse->u1.cr.addrCrTab, BTREE_BLOBKEY);
125375 ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
125377 if( pTab->iPKey>=0 ){
125380 sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zCnName);
125384 pTab->tabFlags &= ~TF_WithoutRowid;
125388 sqlite3RenameTokenRemap(pParse, pList->a[0].pExpr, &pTab->iPKey);
125390 pList->a[0].fg.sortFlags = pParse->iPkSortOrder;
125391 assert( pParse->pNewTable==pTab );
125392 pTab->iPKey = -1;
125393 sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0,
125395 if( pParse->nErr ){
125396 pTab->tabFlags &= ~TF_WithoutRowid;
125399 assert( db->mallocFailed==0 );
125401 assert( pPk->nKeyCol==1 );
125411 for(i=j=1; i<pPk->nKeyCol; i++){
125413 pPk->nColumn--;
125415 testcase( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) );
125416 pPk->azColl[j] = pPk->azColl[i];
125417 pPk->aSortOrder[j] = pPk->aSortOrder[i];
125418 pPk->aiColumn[j++] = pPk->aiColumn[i];
125421 pPk->nKeyCol = j;
125424 pPk->isCovering = 1;
125425 if( !db->init.imposterTable ) pPk->uniqNotNull = 1;
125426 nPk = pPk->nColumn = pPk->nKeyCol;
125432 if( v && pPk->tnum>0 ){
125433 assert( db->init.busy==0 );
125434 sqlite3VdbeChangeOpcode(v, (int)pPk->tnum, OP_Goto);
125438 pPk->tnum = pTab->tnum;
125440 /* Update the in-memory representation of all UNIQUE indices by converting
125443 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
125447 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
125448 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
125454 pIdx->nColumn = pIdx->nKeyCol;
125457 if( resizeIndexObject(pParse, pIdx, pIdx->nKeyCol+n) ) return;
125458 for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
125459 if( !isDupColumn(pIdx, pIdx->nKeyCol, pPk, i) ){
125460 testcase( hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) );
125461 pIdx->aiColumn[j] = pPk->aiColumn[i];
125462 pIdx->azColl[j] = pPk->azColl[i];
125463 if( pPk->aSortOrder[i] ){
125465 pIdx->bAscKeyBug = 1;
125470 assert( pIdx->nColumn>=pIdx->nKeyCol+n );
125471 assert( pIdx->nColumn>=j );
125477 for(i=0; i<pTab->nCol; i++){
125478 if( !hasColumn(pPk->aiColumn, nPk, i)
125479 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ) nExtra++;
125482 for(i=0, j=nPk; i<pTab->nCol; i++){
125483 if( !hasColumn(pPk->aiColumn, j, i)
125484 && (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0
125486 assert( j<pPk->nColumn );
125487 pPk->aiColumn[j] = i;
125488 pPk->azColl[j] = sqlite3StrBINARY;
125492 assert( pPk->nColumn==j );
125493 assert( pTab->nNVCol<=j );
125508 nName = sqlite3Strlen30(pTab->zName);
125509 if( sqlite3_strnicmp(zName, pTab->zName, nName)!=0 ) return 0;
125511 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
125513 if( pMod->pModule->iVersion<3 ) return 0;
125514 if( pMod->pModule->xShadowName==0 ) return 0;
125515 return pMod->pModule->xShadowName(zName+nName+1);
125522 ** exists and has an xShadowName method, then loop over all other ordinary
125527 int nName; /* Length of pTab->zName */
125532 pMod = (Module*)sqlite3HashFind(&db->aModule, pTab->u.vtab.azArg[0]);
125534 if( NEVER(pMod->pModule==0) ) return;
125535 if( pMod->pModule->iVersion<3 ) return;
125536 if( pMod->pModule->xShadowName==0 ) return;
125537 assert( pTab->zName!=0 );
125538 nName = sqlite3Strlen30(pTab->zName);
125539 for(k=sqliteHashFirst(&pTab->pSchema->tblHash); k; k=sqliteHashNext(k)){
125541 assert( pOther->zName!=0 );
125543 if( pOther->tabFlags & TF_Shadow ) continue;
125544 if( sqlite3StrNICmp(pOther->zName, pTab->zName, nName)==0
125545 && pOther->zName[nName]=='_'
125546 && pMod->pModule->xShadowName(pOther->zName+nName+1)
125548 pOther->tabFlags |= TF_Shadow;
125579 ** Mark all nodes of an expression as EP_Immutable, indicating that
125600 #define markExprListImmutable(X) /* no-op */
125612 ** An entry for the table is made in the schema table on disk, unless
125613 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
125632 sqlite3 *db = pParse->db; /* The database connection */
125634 Index *pIdx; /* An implied index of the table */
125639 p = pParse->pNewTable;
125642 if( pSelect==0 && sqlite3ShadowTableName(db, p->zName) ){
125643 p->tabFlags |= TF_Shadow;
125646 /* If the db->init.busy is 1 it means we are reading the SQL off the
125649 ** for the table from the db->init.newTnum field. (The page number
125653 ** table itself. So mark it read-only.
125655 if( db->init.busy ){
125656 if( pSelect || (!IsOrdinaryTable(p) && db->init.newTnum) ){
125660 p->tnum = db->init.newTnum;
125661 if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
125675 p->tabFlags |= TF_Strict;
125676 for(ii=0; ii<p->nCol; ii++){
125677 Column *pCol = &p->aCol[ii];
125678 if( pCol->eCType==COLTYPE_CUSTOM ){
125679 if( pCol->colFlags & COLFLAG_HASTYPE ){
125682 p->zName, pCol->zCnName, sqlite3ColumnType(pCol, "")
125686 p->zName, pCol->zCnName);
125689 }else if( pCol->eCType==COLTYPE_ANY ){
125690 pCol->affinity = SQLITE_AFF_BLOB;
125692 if( (pCol->colFlags & COLFLAG_PRIMKEY)!=0
125693 && p->iPKey!=ii
125694 && pCol->notNull == OE_None
125696 pCol->notNull = OE_Abort;
125697 p->tabFlags |= TF_HasNotNull;
125702 assert( (p->tabFlags & TF_HasPrimaryKey)==0
125703 || p->iPKey>=0 || sqlite3PrimaryKeyIndex(p)!=0 );
125704 assert( (p->tabFlags & TF_HasPrimaryKey)!=0
125705 || (p->iPKey<0 && sqlite3PrimaryKeyIndex(p)==0) );
125709 if( (p->tabFlags & TF_Autoincrement) ){
125714 if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
125715 sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
125718 p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
125721 iDb = sqlite3SchemaToIndex(db, p->pSchema);
125726 if( p->pCheck ){
125727 sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
125728 if( pParse->nErr ){
125731 sqlite3ExprListDelete(db, p->pCheck);
125732 p->pCheck = 0;
125734 markExprListImmutable(p->pCheck);
125739 if( p->tabFlags & TF_HasGenerated ){
125741 testcase( p->tabFlags & TF_HasVirtual );
125742 testcase( p->tabFlags & TF_HasStored );
125743 for(ii=0; ii<p->nCol; ii++){
125744 u32 colFlags = p->aCol[ii].colFlags;
125746 Expr *pX = sqlite3ColumnExpr(p, &p->aCol[ii]);
125756 sqlite3ColumnSetExpr(pParse, p, &p->aCol[ii],
125764 sqlite3ErrorMsg(pParse, "must have at least one non-generated column");
125772 for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
125782 if( !db->init.busy ){
125810 ** statement to populate the new table. The root-page number for the
125811 ** new table is in register pParse->u1.cr.regRoot.
125817 ** A shared-cache write-lock is not required to write to the new table,
125818 ** as a schema-lock must have already been obtained to create it. Since
125819 ** a schema-lock excludes all other database users, the write-lock would
125824 int regYield; /* Register holding co-routine entry-point */
125825 int addrTop; /* Top of the co-routine */
125833 pParse->rc = SQLITE_ERROR;
125834 pParse->nErr++;
125837 iCsr = pParse->nTab++;
125838 regYield = ++pParse->nMem;
125839 regRec = ++pParse->nMem;
125840 regRowid = ++pParse->nMem;
125842 assert( pParse->isCreate );
125843 sqlite3VdbeAddOp3(v, OP_OpenWrite, iCsr, pParse->u1.cr.regRoot, iDb);
125847 if( pParse->nErr ) return;
125850 assert( p->aCol==0 );
125851 p->nCol = p->nNVCol = pSelTab->nCol;
125852 p->aCol = pSelTab->aCol;
125853 pSelTab->nCol = 0;
125854 pSelTab->aCol = 0;
125858 if( pParse->nErr ) return;
125860 sqlite3VdbeJumpHere(v, addrTop - 1);
125876 Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
125877 n = (int)(pEnd2->z - pParse->sNameToken.z);
125878 if( pEnd2->z[0]!=';' ) n += pEnd2->n;
125880 "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
125888 assert( pParse->isCreate );
125893 db->aDb[iDb].zDbSName,
125895 p->zName,
125896 p->zName,
125897 pParse->u1.cr.regRoot,
125899 pParse->u1.cr.regRowid
125905 /* Check to see if we need to create an sqlite_sequence table for
125908 if( (p->tabFlags & TF_Autoincrement)!=0 && !IN_SPECIAL_PARSE ){
125909 Db *pDb = &db->aDb[iDb];
125911 if( pDb->pSchema->pSeqTab==0 ){
125914 pDb->zDbSName
125922 sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName),0);
125926 if( p->tabFlags & TF_HasGenerated ){
125929 db->aDb[iDb].zDbSName, p->zName), P4_DYNAMIC);
125933 /* Add the table to the in-memory representation of the database.
125935 if( db->init.busy ){
125937 Schema *pSchema = p->pSchema;
125939 assert( HasRowid(p) || p->iPKey<0 );
125940 pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
125946 pParse->pNewTable = 0;
125947 db->mDbFlags |= DBFLAG_SchemaChange;
125952 assert( !pParse->nested );
125954 if( strcmp(p->zName, "sqlite_sequence")==0 ){
125956 p->pSchema->pSeqTab = p;
125964 if( pCons->z==0 ){
125967 p->u.tab.addColOffset = 13 + (int)(pCons->z - pParse->sNameToken.z);
125993 sqlite3 *db = pParse->db;
125995 if( pParse->nVar>0 ){
126000 p = pParse->pNewTable;
126001 if( p==0 || pParse->nErr ) goto create_view_fail;
126006 ** with -DSQLITE_ALLOW_ROWID_IN_VIEW in case there are legacy apps that
126010 p->tabFlags |= sqlite3Config.mNoVisibleRowid; /* Optional. Allow by default */
126012 p->tabFlags |= TF_NoVisibleRowid; /* Never allow rowid in view */
126016 iDb = sqlite3SchemaToIndex(db, p->pSchema);
126022 ** allocated rather than point to the input string - which means that
126025 pSelect->selFlags |= SF_View;
126027 p->u.view.pSelect = pSelect;
126030 p->u.view.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
126032 p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
126033 p->eTabType = TABTYP_VIEW;
126034 if( db->mallocFailed ) goto create_view_fail;
126039 sEnd = pParse->sLastToken;
126045 n = (int)(sEnd.z - pBegin->z);
126047 z = pBegin->z;
126048 while( sqlite3Isspace(z[n-1]) ){ n--; }
126049 sEnd.z = &z[n-1];
126068 ** the columns of the view in the pTable structure. Return non-zero if
126069 ** there are errors. If an error is seen an error message is left
126070 ** in pParse->zErrMsg.
126076 sqlite3 *db = pParse->db; /* Database connection for malloc errors */
126088 db->nSchemaLock++;
126090 db->nSchemaLock--;
126100 assert( pTable->nCol<=0 );
126117 if( pTable->nCol<0 ){
126118 sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
126121 assert( pTable->nCol>=0 );
126131 pSel = sqlite3SelectDup(db, pTable->u.view.pSelect, 0);
126133 u8 eParseMode = pParse->eParseMode;
126134 int nTab = pParse->nTab;
126135 int nSelect = pParse->nSelect;
126136 pParse->eParseMode = PARSE_MODE_NORMAL;
126137 sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
126138 pTable->nCol = -1;
126141 xAuth = db->xAuth;
126142 db->xAuth = 0;
126144 db->xAuth = xAuth;
126148 pParse->nTab = nTab;
126149 pParse->nSelect = nSelect;
126151 pTable->nCol = 0;
126153 }else if( pTable->pCheck ){
126156 ** arglist which is stored in pTable->pCheck. The pCheck field
126157 ** normally holds CHECK constraints on an ordinary table, but for
126160 sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
126161 &pTable->nCol, &pTable->aCol);
126162 if( pParse->nErr==0
126163 && pTable->nCol==pSel->pEList->nExpr
126165 assert( db->mallocFailed==0 );
126169 /* CREATE VIEW name AS... without an argument list. Construct
126172 assert( pTable->aCol==0 );
126173 pTable->nCol = pSelTab->nCol;
126174 pTable->aCol = pSelTab->aCol;
126175 pTable->tabFlags |= (pSelTab->tabFlags & COLFLAG_NOINSERT);
126176 pSelTab->nCol = 0;
126177 pSelTab->aCol = 0;
126178 assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
126180 pTable->nNVCol = pTable->nCol;
126184 pParse->eParseMode = eParseMode;
126188 pTable->pSchema->schemaFlags |= DB_UnresetViews;
126189 if( db->mallocFailed ){
126193 return nErr + pParse->nErr;
126197 if( !IsVirtual(pTable) && pTable->nCol>0 ) return 0;
126210 for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
126225 ** root-page of a table or index in database iDb has changed from iFrom
126246 pDb = &db->aDb[iDb];
126247 pHash = &pDb->pSchema->tblHash;
126250 if( pTab->tnum==iFrom ){
126251 pTab->tnum = iTo;
126254 pHash = &pDb->pSchema->idxHash;
126257 if( pIdx->tnum==iFrom ){
126258 pIdx->tnum = iTo;
126265 ** Write code to erase the table with root-page iTable from database iDb.
126267 ** if a root-page of another table is moved by the btree-layer whilst
126268 ** erasing iTable (this can happen with an auto-vacuum database).
126277 /* OP_Destroy stores an in integer r1. If this integer
126278 ** is non-zero, then it is the root page number of a table moved to
126289 pParse->db->aDb[iDb].zDbSName, iTable, r1, r1);
126297 ** in case a root-page belonging to another table is moved by the btree layer
126298 ** is also added (this can happen with an auto-vacuum database).
126301 /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
126303 ** table and index root-pages in order, starting with the numerically
126304 ** largest root-page number. This guarantees that none of the root-pages
126305 ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
126312 ** and root page 5 happened to be the largest root-page number in the
126315 ** a free-list page.
126317 Pgno iTab = pTab->tnum;
126327 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
126328 Pgno iIdx = pIdx->tnum;
126329 assert( pIdx->pSchema==pTab->pSchema );
126337 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
126338 assert( iDb>=0 && iDb<pParse->db->nDb );
126356 const char *zDbName = pParse->db->aDb[iDb].zDbSName;
126360 if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
126374 sqlite3 *db = pParse->db;
126376 Db *pDb = &db->aDb[iDb];
126394 assert( pTrigger->pSchema==pTab->pSchema ||
126395 pTrigger->pSchema==db->aDb[1].pSchema );
126397 pTrigger = pTrigger->pNext;
126404 ** move as a result of the drop (can happen in auto-vacuum mode).
126406 if( pTab->tabFlags & TF_Autoincrement ){
126409 pDb->zDbSName, pTab->zName
126424 pDb->zDbSName, pTab->zName);
126433 sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
126436 sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
126442 ** Return TRUE if shadow tables should be read-only in the current
126447 if( (db->flags & SQLITE_Defensive)!=0
126448 && db->pVtabCtx==0
126449 && db->nVdbeExec==0
126462 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
126463 if( sqlite3StrNICmp(pTab->zName+7, "stat", 4)==0 ) return 0;
126464 if( sqlite3StrNICmp(pTab->zName+7, "parameters", 10)==0 ) return 0;
126467 if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
126470 if( pTab->tabFlags & TF_Eponymous ){
126483 sqlite3 *db = pParse->db;
126486 if( db->mallocFailed ){
126489 assert( pParse->nErr==0 );
126490 assert( pName->nSrc==1 );
126491 assert( pName->a[0].fg.fixedSchema==0 );
126492 assert( pName->a[0].fg.isSubquery==0 );
126494 if( noErr ) db->suppressErr++;
126496 pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
126497 if( noErr ) db->suppressErr--;
126501 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].u4.zDatabase);
126506 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
126507 assert( iDb>=0 && iDb<db->nDb );
126519 const char *zDb = db->aDb[iDb].zDbSName;
126533 zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
126542 if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
126545 if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
126551 sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
126560 sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
126564 sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
126576 sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
126596 ** An FKey structure is created and added to the table currently
126597 ** under construction in the pParse->pNewTable field.
126609 sqlite3 *db = pParse->db;
126613 Table *p = pParse->pNewTable;
126622 int iCol = p->nCol-1;
126624 if( pToCol && pToCol->nExpr!=1 ){
126627 p->aCol[iCol].zCnName, pTo);
126631 }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
126637 nCol = pFromCol->nExpr;
126639 nByte = SZ_FKEY(nCol) + pTo->n + 1;
126641 for(i=0; i<pToCol->nExpr; i++){
126642 nByte += sqlite3Strlen30(pToCol->a[i].zEName) + 1;
126649 pFKey->pFrom = p;
126651 pFKey->pNextFrom = p->u.tab.pFKey;
126652 z = (char*)&pFKey->aCol[nCol];
126653 pFKey->zTo = z;
126657 memcpy(z, pTo->z, pTo->n);
126658 z[pTo->n] = 0;
126660 z += pTo->n+1;
126661 pFKey->nCol = nCol;
126663 pFKey->aCol[0].iFrom = p->nCol-1;
126667 for(j=0; j<p->nCol; j++){
126668 if( sqlite3StrICmp(p->aCol[j].zCnName, pFromCol->a[i].zEName)==0 ){
126669 pFKey->aCol[i].iFrom = j;
126673 if( j>=p->nCol ){
126676 pFromCol->a[i].zEName);
126680 sqlite3RenameTokenRemap(pParse, &pFKey->aCol[i], pFromCol->a[i].zEName);
126686 int n = sqlite3Strlen30(pToCol->a[i].zEName);
126687 pFKey->aCol[i].zCol = z;
126689 sqlite3RenameTokenRemap(pParse, z, pToCol->a[i].zEName);
126691 memcpy(z, pToCol->a[i].zEName, n);
126696 pFKey->isDeferred = 0;
126697 pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
126698 pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
126700 assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
126701 pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
126702 pFKey->zTo, (void *)pFKey
126709 assert( pNextTo->pPrevTo==0 );
126710 pFKey->pNextTo = pNextTo;
126711 pNextTo->pPrevTo = pFKey;
126717 p->u.tab.pFKey = pFKey;
126728 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
126738 if( (pTab = pParse->pNewTable)==0 ) return;
126740 if( (pFKey = pTab->u.tab.pFKey)==0 ) return;
126741 assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
126742 pFKey->isDeferred = (u8)isDeferred;
126749 ** content of an index in response to a REINDEX command.
126755 ** the root page number of the index is taken from pIndex->tnum.
126758 Table *pTab = pIndex->pTable; /* The table that is indexed */
126759 int iTab = pParse->nTab++; /* Btree cursor used for pTab */
126760 int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
126769 sqlite3 *db = pParse->db; /* The database connection */
126770 int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
126773 if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
126774 db->aDb[iDb].zDbSName ) ){
126779 /* Require a write-lock on the table to perform this operation */
126780 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
126787 tnum = pIndex->tnum;
126790 assert( pKey!=0 || pParse->nErr );
126793 iSorter = pParse->nTab++;
126794 sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
126820 pIndex->nKeyCol); VdbeCoverage(v);
126826 ** user function that throws an exception when it is evaluated. But the
126835 if( !pIndex->bAscKeyBug ){
126857 ** Allocate heap space to hold an Index object with nCol columns.
126859 ** Increase the allocation size to provide an extra nExtra bytes
126860 ** of 8-byte aligned space after the Index object and return a
126872 assert( nCol <= 2*db->aLimit[SQLITE_LIMIT_COLUMN] );
126881 p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
126882 p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
126883 p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
126884 p->aSortOrder = (u8*)pExtra;
126886 p->nColumn = (u16)nCol;
126887 p->nKeyCol = (u16)(nCol - 1);
126894 ** If expression list pList contains an expression that was parsed with
126895 ** an explicit "NULLS FIRST" or "NULLS LAST" clause, leave an error in
126896 ** pParse and return non-zero. Otherwise, return zero.
126901 for(i=0; i<pList->nExpr; i++){
126902 if( pList->a[i].fg.bNulls ){
126903 u8 sf = pList->a[i].fg.sortFlags;
126915 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
126917 ** be NULL for a primary key or an index that is created to satisfy a
126918 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
126919 ** as the table to be indexed. pParse->pNewTable is a table that is
126923 ** is a primary key or unique-constraint on the most recent column added
126930 SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
126946 sqlite3 *db = pParse->db;
126956 assert( db->pParse==pParse );
126957 if( pParse->nErr ){
126960 assert( db->mallocFailed==0 );
126976 /* Use the two-part index name to determine the database
126983 assert( pName && pName->z );
126990 if( !db->init.busy ){
126992 if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
127004 pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
127005 assert( db->mallocFailed==0 || pTab==0 );
127007 if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
127009 "cannot create a TEMP index on non-TEMP table \"%s\"",
127010 pTab->zName);
127017 pTab = pParse->pNewTable;
127019 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
127021 pDb = &db->aDb[iDb];
127024 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
127025 && db->init.busy==0
127028 sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
127060 assert( pName->z!=0 );
127061 if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName,"index",pTab->zName) ){
127065 if( !db->init.busy ){
127066 if( sqlite3FindTable(db, zName, pDb->zDbSName)!=0 ){
127071 if( sqlite3FindIndex(db, zName, pDb->zDbSName)!=0 ){
127075 assert( !db->init.busy );
127085 for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
127086 zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
127099 /* Check for authorization to create an index.
127103 const char *zDb = pDb->zDbSName;
127109 if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
127121 Column *pCol = &pTab->aCol[pTab->nCol-1];
127122 pCol->colFlags |= COLFLAG_UNIQUE;
127123 sqlite3TokenInit(&prevCol, pCol->zCnName);
127127 assert( pList->nExpr==1 );
127131 if( pParse->nErr ) goto exit_create_index;
127137 for(i=0; i<pList->nExpr; i++){
127138 Expr *pExpr = pList->a[i].pExpr;
127140 if( pExpr->op==TK_COLLATE ){
127142 nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
127150 nExtraCol = pPk ? pPk->nKeyCol : 1;
127151 assert( pList->nExpr + nExtraCol <= 32767 /* Fits in i16 */ );
127152 pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
127154 if( db->mallocFailed ){
127157 assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
127158 assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
127159 pIndex->zName = zExtra;
127161 memcpy(pIndex->zName, zName, nName+1);
127162 pIndex->pTable = pTab;
127163 pIndex->onError = (u8)onError;
127164 pIndex->uniqNotNull = onError!=OE_None;
127165 pIndex->idxType = idxType;
127166 pIndex->pSchema = db->aDb[iDb].pSchema;
127167 pIndex->nKeyCol = pList->nExpr;
127170 pIndex->pPartIdxWhere = pPIWhere;
127177 if( pDb->pSchema->file_format>=4 ){
127178 sortOrderMask = -1; /* Honor DESC */
127186 ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
127192 pListItem = pList->a;
127194 pIndex->aColExpr = pList;
127197 for(i=0; i<pIndex->nKeyCol; i++, pListItem++){
127198 Expr *pCExpr; /* The i-th index expression */
127199 int requestedSortOrder; /* ASC or DESC on the i-th expression */
127202 sqlite3StringToId(pListItem->pExpr);
127203 sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
127204 if( pParse->nErr ) goto exit_create_index;
127205 pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
127206 if( pCExpr->op!=TK_COLUMN ){
127207 if( pTab==pParse->pNewTable ){
127212 if( pIndex->aColExpr==0 ){
127213 pIndex->aColExpr = pList;
127217 pIndex->aiColumn[i] = XN_EXPR;
127218 pIndex->uniqNotNull = 0;
127219 pIndex->bHasExpr = 1;
127221 j = pCExpr->iColumn;
127224 j = pTab->iPKey;
127226 if( pTab->aCol[j].notNull==0 ){
127227 pIndex->uniqNotNull = 0;
127229 if( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL ){
127230 pIndex->bHasVCol = 1;
127231 pIndex->bHasExpr = 1;
127234 pIndex->aiColumn[i] = (i16)j;
127237 if( pListItem->pExpr->op==TK_COLLATE ){
127239 assert( !ExprHasProperty(pListItem->pExpr, EP_IntValue) );
127240 zColl = pListItem->pExpr->u.zToken;
127246 nExtra -= nColl;
127248 zColl = sqlite3ColumnColl(&pTab->aCol[j]);
127251 if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
127254 pIndex->azColl[i] = zColl;
127255 requestedSortOrder = pListItem->fg.sortFlags & sortOrderMask;
127256 pIndex->aSortOrder[i] = (u8)requestedSortOrder;
127264 for(j=0; j<pPk->nKeyCol; j++){
127265 int x = pPk->aiColumn[j];
127267 if( isDupColumn(pIndex, pIndex->nKeyCol, pPk, j) ){
127268 pIndex->nColumn--;
127270 testcase( hasColumn(pIndex->aiColumn,pIndex->nKeyCol,x) );
127271 pIndex->aiColumn[i] = x;
127272 pIndex->azColl[i] = pPk->azColl[j];
127273 pIndex->aSortOrder[i] = pPk->aSortOrder[j];
127277 assert( i==pIndex->nColumn );
127279 pIndex->aiColumn[i] = XN_ROWID;
127280 pIndex->azColl[i] = sqlite3StrBINARY;
127283 if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
127288 || pTab->iPKey<0 || sqlite3TableColumnToIndex(pIndex, pTab->iPKey)>=0 );
127290 if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
127291 pIndex->isCovering = 1;
127292 for(j=0; j<pTab->nCol; j++){
127293 if( j==pTab->iPKey ) continue;
127295 pIndex->isCovering = 0;
127300 if( pTab==pParse->pNewTable ){
127301 /* This routine has been called to create an automatic index as a
127309 ** Either way, check to see if the table already has such an index. If
127323 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
127326 assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
127329 if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
127330 for(k=0; k<pIdx->nKeyCol; k++){
127333 assert( pIdx->aiColumn[k]>=0 );
127334 if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
127335 z1 = pIdx->azColl[k];
127336 z2 = pIndex->azColl[k];
127339 if( k==pIdx->nKeyCol ){
127340 if( pIdx->onError!=pIndex->onError ){
127345 ** ON CONFLICT clauses this is an error. Otherwise, use the
127348 if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
127352 if( pIdx->onError==OE_Default ){
127353 pIdx->onError = pIndex->onError;
127356 if( idxType==SQLITE_IDXTYPE_PRIMARYKEY ) pIdx->idxType = idxType;
127358 pIndex->pNext = pParse->pNewIndex;
127359 pParse->pNewIndex = pIndex;
127370 ** in-memory database structures.
127372 assert( pParse->nErr==0 );
127373 if( db->init.busy ){
127376 assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
127378 pIndex->tnum = db->init.newTnum;
127381 pParse->rc = SQLITE_CORRUPT_BKPT;
127385 p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
127386 pIndex->zName, pIndex);
127392 db->mDbFlags |= DBFLAG_SchemaChange;
127396 ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
127397 ** emit code to allocate the index rootpage on disk and make an entry for
127403 ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
127411 int iMem = ++pParse->nMem;
127424 pIndex->tnum = (Pgno)sqlite3VdbeAddOp0(v, OP_Noop);
127432 int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
127433 if( pName->z[n-1]==';' ) n--;
127434 /* A named index with an explicit CREATE INDEX statement */
127436 onError==OE_None ? "" : " UNIQUE", n, pName->z);
127438 /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
127443 /* Add an entry in sqlite_schema for this index
127447 db->aDb[iDb].zDbSName,
127448 pIndex->zName,
127449 pTab->zName,
127455 /* Fill the index with data and reparse the schema. Code an OP_Expire
127456 ** to invalidate all pre-compiled statements.
127462 sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName), 0);
127466 sqlite3VdbeJumpHere(v, (int)pIndex->tnum);
127469 if( db->init.busy || pTblName==0 ){
127470 pIndex->pNext = pTab->pIndex;
127471 pTab->pIndex = pIndex;
127475 assert( pParse->pNewIndex==0 );
127476 pParse->pNewIndex = pIndex;
127490 for(ppFrom=&pTab->pIndex; (pThis = *ppFrom)!=0; ppFrom=&pThis->pNext){
127492 if( pThis->onError!=OE_Replace ) continue;
127493 while( (pNext = pThis->pNext)!=0 && pNext->onError!=OE_Replace ){
127495 pThis->pNext = pNext->pNext;
127496 pNext->pNext = pThis;
127497 ppFrom = &pNext->pNext;
127505 for(pThis = pTab->pIndex; pThis; pThis=pThis->pNext){
127506 assert( pThis->onError!=OE_Replace
127507 || pThis->pNext==0
127508 || pThis->pNext->onError==OE_Replace );
127519 ** Fill the Index.aiRowEst[] array with default information - information
127523 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
127525 ** first column of the index. aiRowEst[2] is an estimate of the number
127529 ** aiRowEst[N]<=aiRowEst[N-1]
127539 LogEst *a = pIdx->aiRowLogEst;
127541 int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
127545 assert( !pIdx->hasStat1 );
127551 ** 2020-05-27: If some of the stat data is coming from the sqlite_stat1
127557 x = pIdx->pTable->nRowLogEst;
127560 pIdx->pTable->nRowLogEst = x = 99;
127562 if( pIdx->pPartIdxWhere!=0 ){ x -= 10; assert( 10==sqlite3LogEst(2) ); }
127568 for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
127573 if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
127577 ** This routine will drop an existing named index. This routine
127583 sqlite3 *db = pParse->db;
127586 if( db->mallocFailed ){
127589 assert( pParse->nErr==0 ); /* Never called with prior non-OOM errors */
127590 assert( pName->nSrc==1 );
127591 assert( pName->a[0].fg.fixedSchema==0 );
127592 assert( pName->a[0].fg.isSubquery==0 );
127596 pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].u4.zDatabase);
127599 sqlite3ErrorMsg(pParse, "no such index: %S", pName->a);
127601 sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].u4.zDatabase);
127604 pParse->checkSchema = 1;
127607 if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
127612 iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
127616 Table *pTab = pIndex->pTable;
127617 const char *zDb = db->aDb[iDb].zDbSName;
127623 if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
127635 db->aDb[iDb].zDbSName, pIndex->zName
127637 sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
127639 destroyRootPage(pParse, pIndex->tnum, iDb);
127640 sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
127648 ** pArray is a pointer to an array of objects. Each object in the
127653 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
127661 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
127673 if( (n & (n-1))==0 ){
127677 *pIdx = -1;
127695 sqlite3 *db = pParse->db;
127702 pNew = sqlite3DbRealloc(db, pList, SZ_IDLIST(pList->nId+1));
127709 i = pList->nId++;
127710 pList->a[i].zName = sqlite3NameFromToken(db, pToken);
127711 if( IN_RENAME_OBJECT && pList->a[i].zName ){
127712 sqlite3RenameTokenMap(pParse, (void*)pList->a[i].zName, pToken);
127718 ** Delete an IdList.
127724 for(i=0; i<pList->nId; i++){
127725 sqlite3DbFree(db, pList->a[i].zName);
127731 ** Return the index in pList of the identifier named zId. Return -1
127737 for(i=0; i<pList->nId; i++){
127738 if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
127740 return -1;
127749 ** appropriate for small and memory-limited applications.
127772 ** the original SrcList unchanged, return NULL, and leave an error message
127778 int nExtra, /* Number of new slots to add to pSrc->a[] */
127779 int iStart /* Index in pSrc->a[] of first new slot */
127787 assert( iStart<=pSrc->nSrc );
127790 if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
127792 sqlite3_int64 nAlloc = 2*(sqlite3_int64)pSrc->nSrc+nExtra;
127793 sqlite3 *db = pParse->db;
127795 if( pSrc->nSrc+nExtra>=SQLITE_MAX_SRCLIST ){
127803 assert( db->mallocFailed );
127807 pSrc->nAlloc = nAlloc;
127812 for(i=pSrc->nSrc-1; i>=iStart; i--){
127813 pSrc->a[i+nExtra] = pSrc->a[i];
127815 pSrc->nSrc += nExtra;
127818 memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
127820 pSrc->a[i].iCursor = -1;
127832 ** A SrcList is returned, or NULL if there is an OOM error or if the
127835 ** a new one. If an OOM error does occurs, then the prior value of pList
127838 ** If pDatabase is not null, it means that the table has an optional
127873 assert( pParse->db!=0 );
127874 db = pParse->db;
127876 pList = sqlite3DbMallocRawNN(pParse->db, SZ_SRCLIST(1));
127878 pList->nAlloc = 1;
127879 pList->nSrc = 1;
127880 memset(&pList->a[0], 0, sizeof(pList->a[0]));
127881 pList->a[0].iCursor = -1;
127883 SrcList *pNew = sqlite3SrcListEnlarge(pParse, pList, 1, pList->nSrc);
127891 pItem = &pList->a[pList->nSrc-1];
127892 if( pDatabase && pDatabase->z==0 ){
127895 assert( pItem->fg.fixedSchema==0 );
127896 assert( pItem->fg.isSubquery==0 );
127898 pItem->zName = sqlite3NameFromToken(db, pDatabase);
127899 pItem->u4.zDatabase = sqlite3NameFromToken(db, pTable);
127901 pItem->zName = sqlite3NameFromToken(db, pTable);
127902 pItem->u4.zDatabase = 0;
127913 assert( pList || pParse->db->mallocFailed );
127915 for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
127916 if( pItem->iCursor>=0 ) continue;
127917 pItem->iCursor = pParse->nTab++;
127918 if( pItem->fg.isSubquery ){
127919 assert( pItem->u4.pSubq!=0 );
127920 assert( pItem->u4.pSubq->pSelect!=0 );
127921 assert( pItem->u4.pSubq->pSelect->pSrc!=0 );
127922 sqlite3SrcListAssignCursors(pParse, pItem->u4.pSubq->pSelect->pSrc);
127932 assert( pSubq!=0 && pSubq->pSelect!=0 );
127933 sqlite3SelectDelete(db, pSubq->pSelect);
127944 assert( pItem->fg.isSubquery );
127945 pSel = pItem->u4.pSubq->pSelect;
127946 sqlite3DbFree(db, pItem->u4.pSubq);
127947 pItem->u4.pSubq = 0;
127948 pItem->fg.isSubquery = 0;
127953 ** Delete an entire SrcList including all its substructure.
127960 for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
127963 assert( !pItem->fg.isIndexedBy || !pItem->fg.isTabFunc );
127964 assert( !pItem->fg.isCte || !pItem->fg.isIndexedBy );
127965 assert( !pItem->fg.fixedSchema || !pItem->fg.isSubquery );
127966 assert( !pItem->fg.isSubquery || (pItem->u4.pSubq!=0 &&
127967 pItem->u4.pSubq->pSelect!=0) );
127969 if( pItem->zName ) sqlite3DbNNFreeNN(db, pItem->zName);
127970 if( pItem->zAlias ) sqlite3DbNNFreeNN(db, pItem->zAlias);
127971 if( pItem->fg.isSubquery ){
127972 sqlite3SubqueryDelete(db, pItem->u4.pSubq);
127973 }else if( pItem->fg.fixedSchema==0 && pItem->u4.zDatabase!=0 ){
127974 sqlite3DbNNFreeNN(db, pItem->u4.zDatabase);
127976 if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
127977 if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
127978 sqlite3DeleteTable(db, pItem->pSTab);
127979 if( pItem->fg.isUsing ){
127980 sqlite3IdListDelete(db, pItem->u3.pUsing);
127981 }else if( pItem->u3.pOn ){
127982 sqlite3ExprDelete(db, pItem->u3.pOn);
127989 ** Attach a Subquery object to pItem->uv.pSubq. Set the
127999 ** away if there is an OOM error. Beware.
128001 ** Return non-zero on success. Return zero on an OOM error.
128006 Select *pSelect, /* The subquery SELECT. Must be non-NULL */
128011 assert( pItem->fg.isSubquery==0 );
128012 if( pItem->fg.fixedSchema ){
128013 pItem->u4.pSchema = 0;
128014 pItem->fg.fixedSchema = 0;
128015 }else if( pItem->u4.zDatabase!=0 ){
128016 sqlite3DbFree(pParse->db, pItem->u4.zDatabase);
128017 pItem->u4.zDatabase = 0;
128020 pSelect = sqlite3SelectDup(pParse->db, pSelect, 0);
128023 p = pItem->u4.pSubq = sqlite3DbMallocRawNN(pParse->db, sizeof(Subquery));
128025 sqlite3SelectDelete(pParse->db, pSelect);
128028 pItem->fg.isSubquery = 1;
128029 p->pSelect = pSelect;
128031 memset(((char*)p)+sizeof(p->pSelect), 0, sizeof(*p)-sizeof(p->pSelect));
128042 ** pDatabase is NULL if the database name qualifier is missing - the
128043 ** usual case. If the term has an alias, then pAlias points to the
128057 Token *pAlias, /* The right-hand side of the AS subexpression */
128062 sqlite3 *db = pParse->db;
128063 if( !p && pOnUsing!=0 && (pOnUsing->pOn || pOnUsing->pUsing) ){
128065 (pOnUsing->pOn ? "ON" : "USING")
128073 assert( p->nSrc>0 );
128074 pItem = &p->a[p->nSrc-1];
128076 assert( pItem->zName==0 || pDatabase!=0 );
128077 if( IN_RENAME_OBJECT && pItem->zName ){
128078 Token *pToken = (ALWAYS(pDatabase) && pDatabase->z) ? pDatabase : pTable;
128079 sqlite3RenameTokenMap(pParse, pItem->zName, pToken);
128082 if( pAlias->n ){
128083 pItem->zAlias = sqlite3NameFromToken(db, pAlias);
128088 if( pSubquery->selFlags & SF_NestedFrom ){
128089 pItem->fg.isNestedFrom = 1;
128093 assert( pOnUsing==0 || pOnUsing->pOn==0 || pOnUsing->pUsing==0 );
128094 assert( pItem->fg.isUsing==0 );
128096 pItem->u3.pOn = 0;
128097 }else if( pOnUsing->pUsing ){
128098 pItem->fg.isUsing = 1;
128099 pItem->u3.pUsing = pOnUsing->pUsing;
128101 pItem->u3.pOn = pOnUsing->pOn;
128113 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
128114 ** element of the source-list passed as the second argument.
128118 if( p && pIndexedBy->n>0 ){
128120 assert( p->nSrc>0 );
128121 pItem = &p->a[p->nSrc-1];
128122 assert( pItem->fg.notIndexed==0 );
128123 assert( pItem->fg.isIndexedBy==0 );
128124 assert( pItem->fg.isTabFunc==0 );
128125 if( pIndexedBy->n==1 && !pIndexedBy->z ){
128128 pItem->fg.notIndexed = 1;
128130 pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
128131 pItem->fg.isIndexedBy = 1;
128132 assert( pItem->fg.isCte==0 ); /* No collision on union u2 */
128139 ** SrcList. Or, if an error occurs, return NULL. In all cases, p1 and p2
128143 assert( p1 && p1->nSrc==1 );
128145 SrcList *pNew = sqlite3SrcListEnlarge(pParse, p1, p2->nSrc, 1);
128147 sqlite3SrcListDelete(pParse->db, p2);
128150 memcpy(&p1->a[1], p2->a, p2->nSrc*sizeof(SrcItem));
128151 sqlite3DbFree(pParse->db, p2);
128152 p1->a[0].fg.jointype |= (JT_LTORJ & p1->a[1].fg.jointype);
128160 ** table-valued-function.
128164 SrcItem *pItem = &p->a[p->nSrc-1];
128165 assert( pItem->fg.notIndexed==0 );
128166 assert( pItem->fg.isIndexedBy==0 );
128167 assert( pItem->fg.isTabFunc==0 );
128168 pItem->u1.pFuncArg = pList;
128169 pItem->fg.isTabFunc = 1;
128171 sqlite3ExprListDelete(pParse->db, pList);
128179 ** Shifts all join operators from left to right for an entire FROM
128187 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
128192 ** * All tables to the left of the right-most RIGHT JOIN are tagged with
128199 if( p && p->nSrc>1 ){
128200 int i = p->nSrc-1;
128203 allFlags |= p->a[i].fg.jointype = p->a[i-1].fg.jointype;
128204 }while( (--i)>0 );
128205 p->a[0].fg.jointype = 0;
128210 for(i=p->nSrc-1; ALWAYS(i>0) && (p->a[i].fg.jointype&JT_RIGHT)==0; i--){}
128211 i--;
128214 p->a[i].fg.jointype |= JT_LTORJ;
128215 }while( (--i)>=0 );
128229 db = pParse->db;
128237 for(i=0; i<db->nDb; i++){
128239 Btree *pBt = db->aDb[i].pBt;
128264 assert( pParse->db!=0 );
128279 ** release or rollback an SQL savepoint.
128282 char *zName = sqlite3NameFromToken(pParse->db, pName);
128290 sqlite3DbFree(pParse->db, zName);
128302 sqlite3 *db = pParse->db;
128303 if( db->aDb[1].pBt==0 && !pParse->explain ){
128313 rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
128317 pParse->rc = rc;
128320 db->aDb[1].pBt = pBt;
128321 assert( db->aDb[1].pSchema );
128322 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, 0, 0) ){
128333 ** will occur at the end of the top-level VDBE and will be generated
128337 assert( iDb>=0 && iDb<pToplevel->db->nDb );
128338 assert( pToplevel->db->aDb[iDb].pBt!=0 || iDb==1 );
128340 assert( sqlite3SchemaMutexHeld(pToplevel->db, iDb, 0) );
128341 if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
128342 DbMaskSet(pToplevel->cookieMask, iDb);
128358 sqlite3 *db = pParse->db;
128360 for(i=0; i<db->nDb; i++){
128361 Db *pDb = &db->aDb[i];
128362 if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zDbSName)) ){
128369 ** Generate VDBE code that prepares for doing an operation that
128384 DbMaskSet(pToplevel->writeMask, iDb);
128385 pToplevel->isMultiWrite |= setStatement;
128392 ** If an abort occurs after some of these writes have completed, then it will
128397 pToplevel->isMultiWrite = 1;
128412 ** particular, it prevents us from writing an effective
128418 pToplevel->mayAbort = 1;
128422 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
128435 assert( pParse->pVdbe!=0 );
128437 assert( (errCode&0xff)==SQLITE_CONSTRAINT || pParse->nested );
128446 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
128456 Table *pTab = pIdx->pTable;
128458 sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0,
128459 pParse->db->aLimit[SQLITE_LIMIT_LENGTH]);
128460 if( pIdx->aColExpr ){
128461 sqlite3_str_appendf(&errMsg, "index '%q'", pIdx->zName);
128463 for(j=0; j<pIdx->nKeyCol; j++){
128465 assert( pIdx->aiColumn[j]>=0 );
128466 zCol = pTab->aCol[pIdx->aiColumn[j]].zCnName;
128468 sqlite3_str_appendall(&errMsg, pTab->zName);
128482 ** Code an OP_Halt due to non-unique rowid.
128487 Table *pTab /* The table with the non-unique rowid */
128491 if( pTab->iPKey>=0 ){
128492 zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
128493 pTab->aCol[pTab->iPKey].zCnName);
128496 zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
128511 for(i=0; i<pIndex->nColumn; i++){
128512 const char *z = pIndex->azColl[i];
128513 assert( z!=0 || pIndex->aiColumn[i]<0 );
128514 if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
128529 Index *pIndex; /* An index associated with pTab */
128531 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
128533 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
128535 sqlite3RefillIndex(pParse, pIndex, -1);
128551 sqlite3 *db = pParse->db; /* The database connection */
128556 for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
128558 for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
128569 ** REINDEX -- 1
128570 ** REINDEX <collation> -- 2
128571 ** REINDEX ?<database>.?<tablename> -- 3
128572 ** REINDEX ?<database>.?<indexname> -- 4
128585 Index *pIndex; /* An index associated with pTab */
128587 sqlite3 *db = pParse->db; /* The database connection */
128590 /* Read the database schema. If an error occurs, leave an error message
128599 }else if( NEVER(pName2==0) || pName2->z==0 ){
128601 assert( pName1->z );
128602 zColl = sqlite3NameFromToken(pParse->db, pName1);
128616 zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
128626 iDb = sqlite3SchemaToIndex(db, pIndex->pTable->pSchema);
128628 sqlite3RefillIndex(pParse, pIndex, -1);
128643 int nCol = pIdx->nColumn;
128644 int nKey = pIdx->nKeyCol;
128646 if( pParse->nErr ) return 0;
128647 if( pIdx->uniqNotNull ){
128648 pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
128650 pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
128655 const char *zColl = pIdx->azColl[i];
128656 pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
128658 pKey->aSortFlags[i] = pIdx->aSortOrder[i];
128659 assert( 0==(pKey->aSortFlags[i] & KEYINFO_ORDER_BIGNULL) );
128661 if( pParse->nErr ){
128662 assert( pParse->rc==SQLITE_ERROR_MISSING_COLLSEQ );
128663 if( pIdx->bNoQuery==0 ){
128664 /* Deactivate the index because it contains an unknown collating
128668 ** the missing index using the collation-needed callback. For
128671 pIdx->bNoQuery = 1;
128672 pParse->rc = SQLITE_ERROR_RETRY;
128687 Token *pName, /* Name of the common-table */
128693 sqlite3 *db = pParse->db;
128696 assert( pNew!=0 || db->mallocFailed );
128698 if( db->mallocFailed ){
128702 pNew->pSelect = pQuery;
128703 pNew->pCols = pArglist;
128704 pNew->zName = sqlite3NameFromToken(pParse->db, pName);
128705 pNew->eM10d = eM10d;
128716 sqlite3ExprListDelete(db, pCte->pCols);
128717 sqlite3SelectDelete(db, pCte->pSelect);
128718 sqlite3DbFree(db, pCte->zName);
128741 sqlite3 *db = pParse->db;
128750 ** not, store an error in the Parse structure. */
128751 zName = pCte->zName;
128754 for(i=0; i<pWith->nCte; i++){
128755 if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
128762 pNew = sqlite3DbRealloc(db, pWith, SZ_WITH(pWith->nCte+1));
128766 assert( (pNew!=0 && zName!=0) || db->mallocFailed );
128768 if( db->mallocFailed ){
128772 pNew->a[pNew->nCte++] = *pCte;
128785 for(i=0; i<pWith->nCte; i++){
128786 cteClear(db, &pWith->a[i]);
128821 assert( !db->xCollNeeded || !db->xCollNeeded16 );
128822 if( db->xCollNeeded ){
128825 db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
128829 if( db->xCollNeeded16 ){
128832 sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
128835 db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
128846 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
128851 char *z = pColl->zName;
128856 if( pColl2->xCmp!=0 ){
128858 pColl->xDel = 0; /* Do not copy the destructor */
128867 ** check that it is defined. An undefined collation sequence exists when
128873 ** an equivalent collating sequence that uses a text encoding different
128877 if( pColl && pColl->xCmp==0 ){
128878 const char *zName = pColl->zName;
128879 sqlite3 *db = pParse->db;
128892 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
128896 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
128898 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
128910 pColl = sqlite3HashFind(&db->aCollSeq, zName);
128924 pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
128942 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
128951 ** if necessary and generates an error message if the collating sequence
128967 if( pColl ) pColl += enc-1;
128969 pColl = db->pDfltColl;
128980 db->enc = enc;
128981 /* EVIDENCE-OF: R-08308-17224 The default collating function for all
128984 db->pDfltColl = sqlite3FindCollSeq(db, enc, sqlite3StrBINARY, 0);
128998 ** sequence can be found. If no collation is found, leave an error message.
129009 sqlite3 *db = pParse->db;
129015 if( !p || !p->xCmp ){
129022 if( p && !p->xCmp && synthCollSeq(db, p) ){
129025 assert( !p || p->xCmp );
129028 pParse->rc = SQLITE_ERROR_MISSING_COLLSEQ;
129044 ** another error occurs, NULL is returned and an error message written into
129049 ** and generates an error message.
129054 sqlite3 *db = pParse->db;
129056 u8 initbusy = db->init.busy;
129060 if( !initbusy && (!pColl || !pColl->xCmp) ){
129073 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
129074 ** is also -1. In other words, we are searching for a function that
129077 ** If nArg is -2 that means that we are searching for any function
129087 ** 4: UTF8/16 conversion required - argument count matches exactly
129088 ** 5: UTF16 byte order conversion required - argument count matches exactly
129091 ** If nArg==(-2) then any function with a non-null xSFunc is
129093 ** a non-match.
129098 int nArg, /* Desired number of arguments. (-1)==any */
129102 assert( p->nArg>=(-4) && p->nArg!=(-2) );
129103 assert( nArg>=(-2) );
129106 if( p->nArg!=nArg ){
129107 if( nArg==(-2) ) return p->xSFunc==0 ? 0 : FUNC_PERFECT_MATCH;
129108 if( p->nArg>=0 ) return 0;
129109 /* Special p->nArg values available to built-in functions only:
129110 ** -3 1 or more arguments required
129111 ** -4 2 or more arguments required
129113 if( p->nArg<(-2) && nArg<(-2-p->nArg) ) return 0;
129118 if( p->nArg==nArg ){
129125 if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
129127 }else if( (enc & p->funcFlags & 2)!=0 ){
129143 for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
129144 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
129145 if( sqlite3StrICmp(p->zName, zFunc)==0 ){
129168 assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
129169 aDef[i].pNext = pOther->pNext;
129170 pOther->pNext = &aDef[i];
129183 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
129191 ** If nArg is -2, then the first valid function found is returned. A
129192 ** function is valid if xSFunc is non-zero. The nArg==(-2)
129194 ** of arguments. If nArg is -2, then createFlag must be 0.
129201 sqlite3 *db, /* An open database */
129202 const char *zName, /* Name of the function. zero-terminated */
129203 int nArg, /* Number of arguments. -1 means any number */
129213 assert( nArg>=(-2) );
129214 assert( nArg>=(-1) || createFlag==0 );
129217 /* First search for a match amongst the application-defined functions.
129219 p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
129226 p = p->pNext;
129229 /* If no match is found, search the built-in functions.
129231 ** If the DBFLAG_PreferBuiltin flag is set, then search the built-in
129232 ** functions even if a prior app-defined function was found. And give
129233 ** priority to built-in functions.
129238 ** new function. But the FuncDefs for built-in functions are read-only.
129239 ** So we must not search for built-ins when creating a new function.
129241 if( !createFlag && (pBest==0 || (db->mDbFlags & DBFLAG_PreferBuiltin)!=0) ){
129251 p = p->pNext;
129255 /* If the createFlag parameter is true and the search did not reveal an
129263 pBest->zName = (const char*)&pBest[1];
129264 pBest->nArg = (u16)nArg;
129265 pBest->funcFlags = enc;
129267 for(z=(u8*)pBest->zName; *z; z++) *z = sqlite3UpperToLower[*z];
129268 pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
129274 pBest->pNext = pOther;
129278 if( pBest && (pBest->xSFunc || createFlag) ){
129300 temp1 = pSchema->tblHash;
129301 temp2 = pSchema->trigHash;
129302 sqlite3HashInit(&pSchema->trigHash);
129303 sqlite3HashClear(&pSchema->idxHash);
129308 sqlite3HashInit(&pSchema->tblHash);
129314 sqlite3HashClear(&pSchema->fkeyHash);
129315 pSchema->pSeqTab = 0;
129316 if( pSchema->schemaFlags & DB_SchemaLoaded ){
129317 pSchema->iGeneration++;
129319 pSchema->schemaFlags &= ~(DB_SchemaLoaded|DB_ResetWanted);
129335 }else if ( 0==p->file_format ){
129336 sqlite3HashInit(&p->tblHash);
129337 sqlite3HashInit(&p->idxHash);
129338 sqlite3HashInit(&p->trigHash);
129339 sqlite3HashInit(&p->fkeyHash);
129340 p->enc = SQLITE_UTF8;
129366 ** the name of a single table, as one might find in an INSERT, DELETE,
129368 ** return a pointer. Set an error message and return NULL if the table
129373 ** pSrc->a[0].spTab Pointer to the Table object
129374 ** pSrc->a[0].u2.pIBIndex Pointer to the INDEXED BY index, if there is one
129378 SrcItem *pItem = pSrc->a;
129380 assert( pItem && pSrc->nSrc>=1 );
129382 if( pItem->pSTab ) sqlite3DeleteTable(pParse->db, pItem->pSTab);
129383 pItem->pSTab = pTab;
129384 pItem->fg.notCte = 1;
129386 pTab->nTabRef++;
129387 if( pItem->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pItem) ){
129394 /* Generate byte-code that will report the number of rows modified
129404 /* Return true if table pTab is read-only.
129406 ** A table is read-only if any of the following are true:
129421 ** is for a top-level SQL statement.
129425 if( sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 ){
129432 ** * Only allow DELETE, INSERT, or UPDATE of non-SQLITE_VTAB_INNOCUOUS
129435 if( pParse->pToplevel!=0
129436 && pTab->u.vtab.p->eVtabRisk >
129437 ((pParse->db->flags & SQLITE_TrustedSchema)!=0)
129440 pTab->zName);
129449 if( (pTab->tabFlags & (TF_Readonly|TF_Shadow))==0 ) return 0;
129450 db = pParse->db;
129451 if( (pTab->tabFlags & TF_Readonly)!=0 ){
129452 return sqlite3WritableSchema(db)==0 && pParse->nested==0;
129454 assert( pTab->tabFlags & TF_Shadow );
129461 ** If pTab is not writable -> generate an error message and return 1.
129462 ** If pTab is writable but other errors have occurred -> return 1.
129463 ** If pTab is writable and no prior errors -> return 0;
129467 sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
129472 && (pTrigger==0 || (pTrigger->bReturning && pTrigger->pNext==0))
129474 sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
129484 ** Evaluate a view and store its result in an ephemeral table. The
129485 ** pWhere argument is an optional WHERE clause that restricts the
129499 sqlite3 *db = pParse->db;
129500 int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
129504 assert( pFrom->nSrc==1 );
129505 pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
129506 assert( pFrom->a[0].fg.fixedSchema==0 && pFrom->a[0].fg.isSubquery==0 );
129507 pFrom->a[0].u4.zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
129508 assert( pFrom->a[0].fg.isUsing==0 );
129509 assert( pFrom->a[0].u3.pOn==0 );
129521 ** Generate an expression tree to implement the WHERE, ORDER BY,
129530 SrcList *pSrc, /* the FROM clause -- which tables to scan */
129536 sqlite3 *db = pParse->db;
129544 /* Check that there isn't an ORDER BY without a LIMIT clause.
129548 sqlite3ExprDelete(pParse->db, pWhere);
129549 sqlite3ExprListDelete(pParse->db, pOrderBy);
129569 pTab = pSrc->a[0].pSTab;
129578 assert( pPk->nKeyCol>=1 );
129579 if( pPk->nKeyCol==1 ){
129581 assert( pPk->aiColumn[0]>=0 && pPk->aiColumn[0]<pTab->nCol );
129582 zName = pTab->aCol[pPk->aiColumn[0]].zCnName;
129587 for(i=0; i<pPk->nKeyCol; i++){
129589 assert( pPk->aiColumn[i]>=0 && pPk->aiColumn[i]<pTab->nCol );
129590 p = sqlite3Expr(db, TK_ID, pTab->aCol[pPk->aiColumn[i]].zCnName);
129595 pLhs->x.pList = sqlite3ExprListDup(db, pEList, 0);
129602 pSrc->a[0].pSTab = 0;
129604 pSrc->a[0].pSTab = pTab;
129605 if( pSrc->a[0].fg.isIndexedBy ){
129606 assert( pSrc->a[0].fg.isCte==0 );
129607 pSrc->a[0].u2.pIBIndex = 0;
129608 pSrc->a[0].fg.isIndexedBy = 0;
129609 sqlite3DbFree(db, pSrc->a[0].u1.zIndexedBy);
129610 }else if( pSrc->a[0].fg.isCte ){
129611 pSrc->a[0].u2.pCteUse->nUse++;
129678 db = pParse->db;
129679 assert( db->pParse==pParse );
129680 if( pParse->nErr ){
129683 assert( db->mallocFailed==0 );
129684 assert( pTabList->nSrc==1 );
129687 ** put in an SrcList structure because some of the subroutines we
129689 ** an SrcList* parameter instead of just a Table* parameter.
129713 sqlite3TreeViewDelete(pParse->pWith, pTabList, pWhere,
129737 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
129738 assert( iDb<db->nDb );
129739 rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0,
129740 db->aDb[iDb].zDbSName);
129749 assert( pTabList->nSrc==1 );
129750 iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
129751 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
129752 pParse->nTab++;
129758 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
129767 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
129771 ** an ephemeral table.
129796 if( (db->flags & SQLITE_CountRows)!=0
129797 && !pParse->nested
129798 && !pParse->pTriggerTab
129799 && !pParse->bReturning
129801 memCnt = ++pParse->nMem;
129812 ** IMPLEMENTATION-OF: R-17228-37124 If the action code is SQLITE_DELETE and
129822 && db->xPreUpdateCallback==0
129826 sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
129828 sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt ? memCnt : -1,
129829 pTab->zName, P4_STATIC);
129831 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
129832 assert( pIdx->pSchema==pTab->pSchema );
129834 sqlite3VdbeAddOp3(v, OP_Clear, pIdx->tnum, iDb, memCnt ? memCnt : -1);
129836 sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
129846 /* For a rowid table, initialize the RowSet to an empty set */
129849 iRowSet = ++pParse->nMem;
129852 /* For a WITHOUT ROWID table, create an ephemeral table used to
129856 nPk = pPk->nKeyCol;
129857 iPk = pParse->nMem+1;
129858 pParse->nMem += nPk;
129859 iEphCur = pParse->nTab++;
129868 ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
129869 ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
129870 ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
129891 assert( pPk->aiColumn[i]>=0 );
129893 pPk->aiColumn[i], iPk+i);
129897 iKey = ++pParse->nMem;
129898 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, -1, iKey);
129902 /* For ONEPASS, no need to store the rowid/primary-key. There is only
129905 nKey = nPk; /* OP_Found will use an unpacked key */
129913 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
129914 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
129920 iKey = ++pParse->nMem;
129923 sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
129953 /* Set up a loop over the rowids/primary-keys that were found in the
129954 ** where-clause loop above.
129957 assert( nKey==nPk ); /* OP_Found will use an unpacked key */
129958 if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
129987 pParse->isMultiWrite = 0;
129995 int count = (pParse->nested==0); /* True to count changes */
130000 /* End of the loop over all rowids/primary-keys. */
130011 } /* End non-truncate path */
130017 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
130057 ** 1. iDataCur is an open cursor on the btree that is the canonical data
130063 ** cursor number iIdxCur+i for the i-th index.
130086 ** then it identifies an index cursor (from within array of cursors
130099 u8 count, /* If non-zero, increment the row change counter */
130104 Vdbe *v = pParse->pVdbe; /* Vdbe */
130138 iOld = pParse->nMem+1;
130139 pParse->nMem += (1 + pTab->nCol);
130141 /* Populate the OLD.* pseudo-table register array. These values will be
130144 for(iCol=0; iCol<pTab->nCol; iCol++){
130172 iIdxNoSeek = -1;
130185 ** If variable 'count' is non-zero, then this OP_Delete instruction should
130186 ** invoke the update-hook. The pre-update-hook, on the other hand should
130188 ** the update-hook is not invoked for rows removed by REPLACE, but the
130189 ** pre-update-hook is.
130195 if( pParse->nested==0 || 0==sqlite3_stricmp(pTab->zName, "sqlite_stat1") ){
130239 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
130240 ** index is the 0-th index.)
130254 int r1 = -1; /* Register holding an index key */
130261 v = pParse->pVdbe;
130263 for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
130268 VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
130272 pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
130280 ** Generate code that will assemble an index key and stores it in register
130281 ** regOut. The key with be for index pIdx which is an index on pTab.
130296 ** will be set to zero which is an empty label that is ignored by
130301 ** a pointer to a different index for which an index key has just been
130306 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
130320 Vdbe *v = pParse->pVdbe;
130326 if( pIdx->pPartIdxWhere ){
130328 pParse->iSelfTab = iDataCur + 1;
130329 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
130331 pParse->iSelfTab = 0;
130332 pPrior = 0; /* Ticket a9efb42811fa41ee 2019-11-02;
130338 nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
130340 if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
130343 && pPrior->aiColumn[j]==pIdx->aiColumn[j]
130344 && pPrior->aiColumn[j]!=XN_EXPR
130350 if( pIdx->aiColumn[j]>=0 ){
130351 /* If the column affinity is REAL but the number is an integer, then it
130352 ** might be stored in the table as an integer (using a compact
130353 ** representation) then converted to REAL by an OP_RealAffinity opcode.
130354 ** But we are getting ready to store this value back into an index, where
130368 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
130374 sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
130391 ** This file contains the C-language implementations for many of the SQL
130408 assert( context->pVdbe!=0 );
130409 pOp = &context->pVdbe->aOp[context->iOp-1];
130410 assert( pOp->opcode==OP_CollSeq );
130411 assert( pOp->p4type==P4_COLLSEQ );
130412 return pOp->p4.pColl;
130420 assert( context->isError<=0 );
130421 context->isError = -1;
130422 context->skipFlag = 1;
130426 ** Implementation of the non-aggregate min() and max() functions
130439 mask = sqlite3_user_data(context)==0 ? 0 : -1;
130442 assert( mask==-1 || mask==0 );
130464 int i = sqlite3_value_type(argv[0]) - 1;
130472 /* EVIDENCE-OF: R-01470-60482 The sqlite3_value_type(V) interface returns
130476 sqlite3_result_text(context, azType[i], -1, SQLITE_STATIC);
130521 sqlite3_result_int(context, (int)(z-z0));
130548 i64 m = sqlite3_context_db_handle(context)->enc<=SQLITE_UTF8 ? 1 : 2;
130570 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
130581 /* IMP: R-31676-45509 If X is the integer -9223372036854775808
130582 ** then abs(X) throws an integer overflow error since there is no
130583 ** equivalent positive 64-bit two complement value. */
130584 sqlite3_result_error(context, "integer overflow", -1);
130587 iVal = -iVal;
130593 /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
130600 ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
130604 if( rVal<0 ) rVal = -rVal;
130671 nHaystack--;
130702 x.nArg = argc-1;
130705 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
130718 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
130719 ** of x. If x is text, then we actually count UTF-8 characters.
130759 p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
130764 ** as substr(X,1,N) - it returns the first N characters of X. This
130765 ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
130766 ** from 2009-02-02 for compatibility of applications that exploited the
130783 p1--;
130785 p2--;
130788 if( p2<-p1 ){
130791 p2 = -p2;
130793 p1 -= p2;
130799 p1--;
130801 for(z2=z; *z2 && p2; p2--){
130804 sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
130809 }else if( p2>len-p1 ){
130810 p2 = len-p1;
130834 /* If Y==0 and X will fit in a 64-bit int,
130838 if( r<-4503599627370496.0 || r>+4503599627370496.0 ){
130841 r = (double)((sqlite_int64)(r+(r<0?-0.5:+0.5)));
130860 ** raise an SQLITE_TOOBIG exception and return NULL.
130866 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
130867 testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
130868 if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
130930 #define noopFunc versionFunc /* Substitute function - never called */
130945 ** (or -9223372036854775808) since when you do abs() of that
130950 ** therefore be no less than -9223372036854775807.
130952 r = -(r & LARGEST_INT64);
130992 /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
131001 ** IMP: R-32760-32347 The changes() SQL function is a wrapper
131026 /* IMP: R-11217-42568 This function is a wrapper around the
131032 ** A structure defining how to do GLOB-style comparisons.
131055 /* The correct SQL-92 behavior is for the LIKE operator to ignore
131070 ** Compare two UTF-8 strings for equality where the first string is
131090 ** range of characters can be specified using '-'. Example:
131091 ** "[a-z]" matches any single lower-case letter. To match a '-', make
131114 u32 matchOne = pInfo->matchOne; /* "?" or "_" */
131115 u32 matchAll = pInfo->matchAll; /* "*" or "%" */
131116 u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
131133 if( pInfo->matchSet==0 ){
131138 ** recursive search in this case, but it is an unusual case. */
131139 assert( matchOther<0x80 ); /* '[' is a single-byte character */
131141 int bMatch = patternCompare(&zPattern[-1],zString,pInfo,matchOther);
131154 ** For a case-insensitive search, set variable cx to be the same as
131187 if( pInfo->matchSet==0 ){
131207 if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
131238 ** non-zero if there is no match.
131251 ** The sqlite3_strlike() interface. Return 0 on a match and non-zero for
131252 ** a miss - like strcmp().
131276 ** the built-in LIKE operator. The first argument to the function is the
131314 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
131315 testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
131316 if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
131317 sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
131321 /* The escape character string must consist of a single UTF-8 character.
131322 ** Otherwise, return an error.
131326 if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
131328 "ESCAPE expression must be a single character", -1);
131332 if( escape==pInfo->matchAll || escape==pInfo->matchOne ){
131335 if( escape==pInfo->matchAll ) pInfo->matchAll = 0;
131336 if( escape==pInfo->matchOne ) pInfo->matchOne = 0;
131339 escape = pInfo->matchSet;
131379 /* IMP: R-48699-48617 This function is an SQL wrapper around the
131380 ** sqlite3_libversion() C-interface. */
131381 sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
131395 /* IMP: R-24470-31136 This function is an SQL wrapper around the
131397 sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
131403 ** its side-effects.
131417 ** The result is an integer that identifies if the compiler option
131429 /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
131453 /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
131457 sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
131461 /* Array for converting from half-bytes (nybbles) into ASCII hex
131476 assert( pStr!=0 && pStr->nChar==0 );
131486 sqlite3AtoF(zVal, &r2, pStr->nChar, SQLITE_UTF8);
131503 if( pStr->accError==0 ){
131504 char *zText = pStr->zText;
131514 pStr->nChar = nBlob*2 + 3;
131550 ** This is intended to be a work-alike of the UNISTR() function in
131551 ** PostgreSQL. Quoting from the PG documentation (PostgreSQL 17 -
131552 ** scraped on 2025-02-22):
131585 n = nIn - i;
131590 n = z - &zIn[i];
131625 sqlite3_result_error(context, "invalid Unicode escape", -1);
131633 ** The quote(X) function returns the text of an SQL literal which is the
131634 ** value of its argument suitable for inclusion into an SQL statement.
131635 ** Strings are surrounded by single-quotes with escapes on interior quotes
131640 ** If sqlite3_user_data() is non-zero, then the UNISTR_QUOTE() function is
131649 sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
131660 ** The unicode() function. Return the integer unicode code-point value
131675 ** an integer. It constructs a string where each character of the string
131713 sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
131741 sqlite3_result_text64(context, zHex, (u64)(z-zHex),
131747 ** Buffer zStr contains nStr bytes of utf-8 encoded text. Return 1 if zStr
131766 ** If there is only a single argument, then it must consist only of an
131827 sqlite3_result_blob(pCtx, pBlob, (p - pBlob), sqlite3_free);
131837 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
131850 rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
131889 || sqlite3_context_db_handle(context)->mallocFailed );
131909 loopLimit = nStr - nPattern;
131916 nOut += nRep - nPattern;
131917 testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
131918 testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
131919 if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
131925 if( (cntExpand&(cntExpand-1))==0 ){
131930 zOut = sqlite3Realloc(zOut, (int)nOut + (nOut - nStr - 1));
131940 i += nPattern-1;
131943 assert( j+nStr-i+1<=nOut );
131944 memcpy(&zOut[j], &zStr[i], nStr-i);
131945 j += nStr - i;
132000 aLen[nChar] = (unsigned)(z - azChar[nChar]);
132015 nIn -= len;
132023 if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
132026 nIn -= len;
132039 ** Return a string value that is the concatenation of all non-null
132055 n += (argc-1)*(i64)nSep;
132083 ** concatentation of all non-null arguments.
132097 ** argument. Use the first argument (which must be non-NULL) as the
132108 concatFuncCore(context, argc-1, argv+1, nSep, zSep);
132115 ** any unrecognized function name when doing an EXPLAIN or EXPLAIN QUERY PLAN
132116 ** when the SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION compile-time option is used.
132117 ** When the "sqlite3" command-line shell is built using this functionality,
132118 ** that allows an EXPLAIN or EXPLAIN QUERY PLAN for complex queries
132119 ** involving application-defined functions to be examined in a generic
132127 /* no-op */
132135 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
132136 ** is only available if the SQLITE_SOUNDEX compile-time option is used
132143 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
132188 /* IMP: R-64894-50321 The string "?000" is returned if the argument
132197 ** A function that loads a shared-library extension then returns NULL.
132208 if( (db->flags & SQLITE_LoadExtFunc)==0 ){
132209 sqlite3_result_error(context, "not authorized", -1);
132219 sqlite3_result_error(context, zErrMsg, -1);
132227 ** An instance of the following structure holds the context of a
132233 double rErr; /* Error term for Kahan-Babushka-Neumaier summation */
132236 u8 approx; /* True if any non-integer value was input to the sum */
132241 ** Do one step of the Kahan-Babushka-Neumaier summation.
132252 volatile double s = pSum->rSum;
132255 pSum->rErr += (s - t) + r;
132257 pSum->rErr += (r - t) + s;
132259 pSum->rSum = t;
132266 if( iVal<=-4503599627370496LL || iVal>=+4503599627370496LL ){
132269 iBig = iVal - iSm;
132278 ** Initialize the Kahan-Babaska-Neumaier sum from a 64-bit integer
132284 if( iVal<=-4503599627370496LL || iVal>=+4503599627370496LL ){
132286 p->rSum = (double)(iVal - iSm);
132287 p->rErr = (double)iSm;
132289 p->rSum = (double)iVal;
132290 p->rErr = 0.0;
132300 ** SUM might return an integer if it never encounters a floating point
132301 ** value. TOTAL never fails, but SUM might throw an exception if
132302 ** it overflows an integer.
132312 p->cnt++;
132313 if( p->approx==0 ){
132315 kahanBabuskaNeumaierInit(p, p->iSum);
132316 p->approx = 1;
132319 i64 x = p->iSum;
132321 p->iSum = x;
132323 p->ovrfl = 1;
132324 kahanBabuskaNeumaierInit(p, p->iSum);
132325 p->approx = 1;
132333 p->ovrfl = 0;
132347 /* p is always non-NULL because sumStep() will have been called first
132350 assert( p->cnt>0 );
132351 p->cnt--;
132352 if( !p->approx ){
132353 if( sqlite3SubInt64(&p->iSum, sqlite3_value_int64(argv[0])) ){
132354 p->ovrfl = 1;
132355 p->approx = 1;
132360 kahanBabuskaNeumaierStepInt64(p, -iVal);
132366 kahanBabuskaNeumaierStep(p, -sqlite3_value_double(argv[0]));
132376 if( p && p->cnt>0 ){
132377 if( p->approx ){
132378 if( p->ovrfl ){
132379 sqlite3_result_error(context,"integer overflow",-1);
132380 }else if( !sqlite3IsOverflow(p->rErr) ){
132381 sqlite3_result_double(context, p->rSum+p->rErr);
132383 sqlite3_result_double(context, p->rSum);
132386 sqlite3_result_int64(context, p->iSum);
132393 if( p && p->cnt>0 ){
132395 if( p->approx ){
132396 r = p->rSum;
132397 if( !sqlite3IsOverflow(p->rErr) ) r += p->rErr;
132399 r = (double)(p->iSum);
132401 sqlite3_result_double(context, r/(double)p->cnt);
132409 if( p->approx ){
132410 r = p->rSum;
132411 if( !sqlite3IsOverflow(p->rErr) ) r += p->rErr;
132413 r = (double)(p->iSum);
132438 p->n++;
132445 ** expressed as a 32-bit integer. */
132446 assert( argc==1 || p==0 || p->n>0x7fffffff || p->bInverse
132447 || p->n==sqlite3_aggregate_count(context) );
132453 sqlite3_result_int64(context, p ? p->n : 0);
132459 /* p is always non-NULL since countStep() will have been called first */
132461 p->n--;
132463 p->bInverse = 1;
132487 if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
132488 }else if( pBest->flags ){
132495 ** sqlite3_user_data() function returns (void *)-1. For min() it
132508 pBest->db = sqlite3_context_db_handle(context);
132516 if( pRes->flags ){
132552 /* If pnSepLengths!=0, refs an array of inter-string separator lengths,
132554 ** (Hence, its slots in use number nAccum-1 between method calls.)
132575 int firstTerm = pGCC->str.mxAlloc==0;
132576 pGCC->str.mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
132579 sqlite3_str_appendchar(&pGCC->str, 1, ',');
132583 pGCC->nFirstSepLength = 1;
132590 sqlite3_str_append(&pGCC->str, zSep, nSep);
132596 if( nSep != pGCC->nFirstSepLength || pGCC->pnSepLengths != 0 ){
132597 int *pnsl = pGCC->pnSepLengths;
132600 pnsl = (int*)sqlite3_malloc64((pGCC->nAccum+1) * sizeof(int));
132602 int i = 0, nA = pGCC->nAccum-1;
132603 while( i<nA ) pnsl[i++] = pGCC->nFirstSepLength;
132606 pnsl = (int*)sqlite3_realloc64(pnsl, pGCC->nAccum * sizeof(int));
132609 if( ALWAYS(pGCC->nAccum>0) ){
132610 pnsl[pGCC->nAccum-1] = nSep;
132612 pGCC->pnSepLengths = pnsl;
132614 sqlite3StrAccumSetError(&pGCC->str, SQLITE_NOMEM);
132621 pGCC->nFirstSepLength = sqlite3_value_bytes(argv[1]);
132623 pGCC->nAccum += 1;
132627 if( zVal ) sqlite3_str_append(&pGCC->str, zVal, nVal);
132642 /* pGCC is always non-NULL since groupConcatStep() will have always
132650 pGCC->nAccum -= 1;
132651 if( pGCC->pnSepLengths!=0 ){
132652 assert(pGCC->nAccum >= 0);
132653 if( pGCC->nAccum>0 ){
132654 nVS += *pGCC->pnSepLengths;
132655 memmove(pGCC->pnSepLengths, pGCC->pnSepLengths+1,
132656 (pGCC->nAccum-1)*sizeof(int));
132659 /* If removing single accumulated string, harmlessly over-do. */
132660 nVS += pGCC->nFirstSepLength;
132662 if( nVS>=(int)pGCC->str.nChar ){
132663 pGCC->str.nChar = 0;
132665 pGCC->str.nChar -= nVS;
132666 memmove(pGCC->str.zText, &pGCC->str.zText[nVS], pGCC->str.nChar);
132668 if( pGCC->str.nChar==0 ){
132669 pGCC->str.mxAlloc = 0;
132670 sqlite3_free(pGCC->pnSepLengths);
132671 pGCC->pnSepLengths = 0;
132682 sqlite3ResultStrAccum(context, &pGCC->str);
132684 sqlite3_free(pGCC->pnSepLengths);
132693 StrAccum *pAccum = &pGCC->str;
132694 if( pAccum->accError==SQLITE_TOOBIG ){
132696 }else if( pAccum->accError==SQLITE_NOMEM ){
132698 }else if( pGCC->nAccum>0 && pAccum->nChar==0 ){
132702 sqlite3_result_text(context, zText, pAccum->nChar, SQLITE_TRANSIENT);
132711 ** This routine does per-connection function registration. Most
132712 ** of the built-in functions above are part of the global function set.
132724 ** Re-register the built-in LIKE functions. The caseSensitive
132744 pDef->funcFlags |= flags;
132745 pDef->funcFlags &= ~SQLITE_FUNC_UNSAFE;
132750 ** pExpr points to an expression which implements a function. If
132754 ** LIKE-style function then return FALSE.
132770 assert( pExpr->op==TK_FUNCTION );
132772 if( !pExpr->x.pList ){
132775 nExpr = pExpr->x.pList->nExpr;
132777 pDef = sqlite3FindFunction(db, pExpr->u.zToken, nExpr, SQLITE_UTF8, 0);
132781 if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
132789 memcpy(aWc, pDef->pUserData, 3);
132797 Expr *pEscape = pExpr->x.pList->a[2].pExpr;
132799 if( pEscape->op!=TK_STRING ) return 0;
132801 zEscape = pEscape->u.zToken;
132808 *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
132824 /* Extra math functions that require linking with -lm
132882 ** ln(X) - natural logarithm
132883 ** log(X) - log X base 10
132884 ** log10(X) - log X base 10
132885 ** log(B,X) - log X base B
132939 ** Implementation of 1-argument SQL math functions:
132941 ** exp(X) - Compute e to the X-th power
132961 ** Implementation of 2-argument SQL math functions:
132963 ** power(X,Y) - Compute X to the Y-th power
132986 ** Implementation of 0-argument pi() function.
133015 sqlite3_result_int(context, x<0.0 ? -1 : x>0.0 ? +1 : 0);
133028 ** in production builds. This function is not an API and is subject to
133052 sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
133072 ** in production builds. This function is not an API and is subject to
133092 zVfs = pVfs->zName;
133102 sqlite3_str_appendf(pResult, ", vfs=%Q", pVfs ? pVfs->zName: 0);
133125 sqlite3_result_text(ctx, sqlite3_str_finish(pResult), -1, sqlite3_free);
133134 ** to the global function hash table. This occurs at start-time (as
133145 ** FuncDef.pHash elements at start-time. The elements of this array
133146 ** are read-only after initialization is complete.
133182 FUNCTION(min, -3, 0, 1, minmaxFunc ),
133185 FUNCTION(max, -3, 1, 1, minmaxFunc ),
133194 FUNCTION(printf, -1, 0, 0, printfFunc ),
133195 FUNCTION(format, -1, 0, 0, printfFunc ),
133197 FUNCTION(char, -1, 0, 0, charFunc ),
133201 FUNCTION(parseuri, -1, 0, 0, parseuriFunc ),
133212 FUNCTION(concat, -3, 0, 0, concatFunc ),
133213 FUNCTION(concat_ws, -4, 0, 0, concatwsFunc ),
133257 FUNCTION(unknown, -1, 0, 0, unknownFunc ),
133296 INLINE_FUNC(coalesce, -4, INLINEFUNC_coalesce, 0 ),
133297 INLINE_FUNC(iif, -4, INLINEFUNC_iif, 0 ),
133298 INLINE_FUNC(if, -4, INLINEFUNC_iif, 0 ),
133308 #if 0 /* Enable to print out how the built-in functions are hashed */
133313 printf("FUNC-HASH %02d:", i);
133314 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
133315 int n = sqlite3Strlen30(p->zName);
133316 int h = p->zName[0] + n;
133317 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
133318 printf(" %s(%d)", p->zName, h);
133348 ** --------------------------
133351 ** If an immediate foreign key constraint is violated,
133362 ** time a statement is executed that removes an existing violation from
133401 ** An UPDATE command requires that all 4 steps above are taken, but only
133410 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
133419 ** and the statement transaction is rolled back. An exception is an INSERT
133421 ** instead of using a counter, an exception is thrown immediately if the
133423 ** an INSERT does not open a statement transaction.
133430 ** ---------------
133432 ** Before coding an UPDATE or DELETE row operation, the code-generator
133437 ** accessed). No information is required by the code-generator before
133438 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
133441 ** sqlite3FkRequired() - Test to see if FK processing is required.
133442 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
133446 ** --------------------------------------
133448 ** sqlite3FkCheck() - Check for foreign key violations.
133449 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
133450 ** sqlite3FkDelete() - Delete an FKey structure.
133455 ** -----------------------
133476 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
133482 ** Otherwise, it is set to point to an allocated array of size N, where
133485 ** constraint to the parent table column stored in the left-most column
133487 ** child table column that corresponds to the second left-most column of
133506 ** then non-zero is returned, and a "foreign key mismatch" error loaded
133507 ** into pParse. If an OOM error occurs, non-zero is returned and the
133508 ** pParse->db->mallocFailed flag is set.
133519 int nCol = pFKey->nCol; /* Number of columns in parent key */
133520 char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
133527 /* If this is a non-composite (single column) foreign key, check if it
133533 ** Non-composite foreign keys do not require the aiCol array.
133538 ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
133543 if( pParent->iPKey>=0 ){
133545 if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zCnName, zKey) ){
133551 aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
133556 for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
133557 if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) && pIdx->pPartIdxWhere==0 ){
133569 for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
133574 /* If zKey is non-NULL, then this foreign key was declared to
133575 ** map to an explicit list of columns in table pParent. Check if this
133580 i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
133589 zDfltColl = sqlite3ColumnColl(&pParent->aCol[iCol]);
133591 if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
133593 zIdxCol = pParent->aCol[iCol].zCnName;
133595 if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
133596 if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
133608 if( !pParse->disableTriggers ){
133610 "foreign key mismatch - \"%w\" referencing \"%w\"",
133611 pFKey->pFrom->zName, pFKey->zTo);
133613 sqlite3DbFree(pParse->db, aiCol);
133623 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
133625 ** affected - once to "delete" the old row, and then again to "insert" the
133635 ** --------------------------------------------------------------------------
133660 int iCur = pParse->nTab - 1; /* Cursor number to use */
133664 (!pFKey->isDeferred
133665 && !(pParse->db->flags & SQLITE_DeferFKs)
133666 && !pParse->pToplevel
133667 && !pParse->isMultiWrite) ? OE_Abort : OE_Ignore);
133677 sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
133680 for(i=0; i<pFKey->nCol; i++){
133681 int iReg = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i]) + regData + 1;
133692 /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
133698 sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[0])+1+regData, regTemp);
133703 ** to increment the constraint-counter (i.e. this is an INSERT operation),
133705 ** increment the constraint-counter. */
133706 if( pTab==pFKey->pFrom && nIncr==1 ){
133714 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
133718 int nCol = pFKey->nCol;
133721 sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
133725 sqlite3TableColumnToStorage(pFKey->pFrom, aiCol[i])+1+regData,
133730 ** to increment the constraint-counter (i.e. this is an INSERT operation),
133732 ** increment the constraint-counter.
133734 ** If any of the parent-key values are NULL, then the row cannot match
133736 ** of the parent-key values are NULL (at this point it is known that
133739 if( pTab==pFKey->pFrom && nIncr==1 ){
133742 int iChild = sqlite3TableColumnToStorage(pFKey->pFrom,aiCol[i])
133745 iParent += sqlite3TableColumnToStorage(pIdx->pTable,
133746 pIdx->aiColumn[i]);
133747 assert( pIdx->aiColumn[i]>=0 );
133748 assert( aiCol[i]!=pTab->iPKey );
133749 if( pIdx->aiColumn[i]==pTab->iPKey ){
133760 sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
133767 if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
133768 && !pParse->pToplevel
133769 && !pParse->isMultiWrite
133771 /* Special case: If this is an INSERT statement that will insert exactly
133779 if( nIncr>0 && pFKey->isDeferred==0 ){
133782 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
133791 ** Return an Expr object that refers to a memory register corresponding
133794 ** regBase is the first of an array of register that contains the data
133807 sqlite3 *db = pParse->db;
133811 if( iCol>=0 && iCol!=pTab->iPKey ){
133812 pCol = &pTab->aCol[iCol];
133813 pExpr->iTable = regBase + sqlite3TableColumnToStorage(pTab,iCol) + 1;
133814 pExpr->affExpr = pCol->affinity;
133816 if( zColl==0 ) zColl = db->pDfltColl->zName;
133819 pExpr->iTable = regBase;
133820 pExpr->affExpr = SQLITE_AFF_INTEGER;
133827 ** Return an Expr object that refers to column iCol of table pTab which
133839 pExpr->y.pTab = pTab;
133840 pExpr->iTable = iCursor;
133841 pExpr->iColumn = iCol;
133850 ** code for an SQL UPDATE operation, this function may be called twice -
133853 ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
133862 ** --------------------------------------------------------------------------
133884 sqlite3 *db = pParse->db; /* Database handle */
133892 assert( pIdx==0 || pIdx->pTable==pTab );
133893 assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
133894 assert( pIdx!=0 || pFKey->nCol==1 );
133898 iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
133902 /* Create an Expr object representing an SQL expression like:
133904 ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
133910 for(i=0; i<pFKey->nCol; i++){
133917 iCol = pIdx ? pIdx->aiColumn[i] : -1;
133919 iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
133921 zCol = pFKey->pFrom->aCol[iCol].zCnName;
133941 if( pTab==pFKey->pFrom && nIncr>0 ){
133946 pLeft = exprTableRegister(pParse, pTab, regData, -1);
133947 pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
133952 for(i=0; i<pIdx->nKeyCol; i++){
133953 i16 iCol = pIdx->aiColumn[i];
133956 pRight = sqlite3Expr(db, TK_ID, pTab->aCol[iCol].zCnName);
133974 if( pParse->nErr==0 ){
133976 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
133997 ** Calling this function with table "t1" as an argument returns a pointer
134004 return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
134010 ** and all of its sub-components.
134012 ** The Trigger structure or any of its sub-components may be allocated from
134017 TriggerStep *pStep = p->step_list;
134018 sqlite3ExprDelete(dbMem, pStep->pWhere);
134019 sqlite3ExprListDelete(dbMem, pStep->pExprList);
134020 sqlite3SelectDelete(dbMem, pStep->pSelect);
134021 sqlite3ExprDelete(dbMem, p->pWhen);
134033 Hash *pHash = &db->aDb[iDb].pSchema->tblHash;
134038 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
134039 fkTriggerDelete(db, pFKey->apTrigger[0]); pFKey->apTrigger[0] = 0;
134040 fkTriggerDelete(db, pFKey->apTrigger[1]); pFKey->apTrigger[1] = 0;
134063 sqlite3 *db = pParse->db;
134064 if( (db->flags&SQLITE_ForeignKeys) && IsOrdinaryTable(pTab) ){
134077 for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
134078 if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
134085 pParse->disableTriggers = 1;
134087 pParse->disableTriggers = 0;
134090 ** violations, halt the VDBE and return an error at this point, before
134098 if( (db->flags & SQLITE_DeferFKs)==0 ){
134114 ** The second argument points to an FKey object representing a foreign key
134115 ** for which pTab is the child table. An UPDATE statement against pTab
134119 ** is set to -1). If the rowid column is modified by the UPDATE statement
134120 ** the bChngRowid argument is non-zero.
134132 for(i=0; i<p->nCol; i++){
134133 int iChildKey = p->aCol[i].iFrom;
134135 if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
134141 ** The second argument points to an FKey object representing a foreign key
134142 ** for which pTab is the parent table. An UPDATE statement against pTab
134146 ** is set to -1). If the rowid column is modified by the UPDATE statement
134147 ** the bChngRowid argument is non-zero.
134159 for(i=0; i<p->nCol; i++){
134160 char *zKey = p->aCol[i].zCol;
134162 for(iKey=0; iKey<pTab->nCol; iKey++){
134163 if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
134164 Column *pCol = &pTab->aCol[iKey];
134166 if( 0==sqlite3StrICmp(pCol->zCnName, zKey) ) return 1;
134167 }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
134183 if( pTop->pTriggerPrg ){
134184 Trigger *p = pTop->pTriggerPrg->pTrigger;
134185 if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
134186 || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
134188 assert( (pTop->db->flags & SQLITE_FkNoAction)==0 );
134201 ** first register in an array of (pTab->nCol+1) registers containing the
134206 ** For an INSERT operation, regOld is passed zero and regNew is passed the
134207 ** first register of an array of (pTab->nCol+1) registers containing the new
134210 ** For an UPDATE operation, this function is called twice. Once before
134223 sqlite3 *db = pParse->db; /* Database handle */
134227 int isIgnoreErrors = pParse->disableTriggers;
134229 /* Exactly one of regOld and regNew should be non-zero. */
134232 /* If foreign-keys are disabled, this function is a no-op. */
134233 if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
134236 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
134237 zDb = db->aDb[iDb].zDbSName;
134241 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pFKey->pNextFrom){
134251 && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
134259 ** schema items cannot be located, set an error in pParse and return
134261 if( pParse->disableTriggers ){
134262 pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
134264 pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
134268 if( !isIgnoreErrors || db->mallocFailed ) return;
134273 ** If the parent table of an FK constraint on the current table is
134275 ** FK counter for each row of the current table with non-NULL keys.
134278 int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
134279 for(i=0; i<pFKey->nCol; i++){
134281 iFromCol = pFKey->aCol[i].iFrom;
134282 iReg = sqlite3TableColumnToStorage(pFKey->pFrom,iFromCol) + regOld+1;
134285 sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
134289 assert( pFKey->nCol==1 || (aiFree && pIdx) );
134294 iCol = pFKey->aCol[0].iFrom;
134297 for(i=0; i<pFKey->nCol; i++){
134298 if( aiCol[i]==pTab->iPKey ){
134299 aiCol[i] = -1;
134301 assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
134306 if( db->xAuth ){
134308 char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zCnName;
134309 rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
134315 /* Take a shared-cache advisory read-lock on the parent table. Allocate
134318 sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
134319 pParse->nTab++;
134323 ** If the parent does not exist, removing the child row resolves an
134325 fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
134335 ** this row to cause an FK violation. */
134344 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
134353 if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
134354 && !pParse->pToplevel && !pParse->isMultiWrite
134358 ** an immediate foreign key violation. So do nothing in this case. */
134363 if( !isIgnoreErrors || db->mallocFailed ) return;
134366 assert( aiCol || pFKey->nCol==1 );
134372 SrcItem *pItem = pSrc->a;
134373 pItem->pSTab = pFKey->pFrom;
134374 pItem->zName = pFKey->pFrom->zName;
134375 pItem->pSTab->nTabRef++;
134376 pItem->iCursor = pParse->nTab++;
134379 fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
134382 int eAction = pFKey->aAction[aChange!=0];
134383 if( (db->flags & SQLITE_FkNoAction) ) eAction = OE_None;
134389 ** So do not set the "may-abort" flag in this case.
134392 ** may-abort flag will eventually be set on this statement anyway
134403 if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
134407 pItem->zName = 0;
134425 if( pParse->db->flags&SQLITE_ForeignKeys && IsOrdinaryTable(pTab) ){
134428 for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
134429 for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
134431 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
134435 for(i=0; i<pIdx->nKeyCol; i++){
134436 assert( pIdx->aiColumn[i]>=0 );
134437 mask |= COLUMN_MASK(pIdx->aiColumn[i]);
134449 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
134450 ** to an array of size N, where N is the number of columns in table pTab.
134452 ** entry in the aChange[] array is set to -1. If the column is modified,
134457 ** non-zero. If there is no foreign key related processing, this function
134460 ** For an UPDATE, this function returns 2 if:
134473 int *aChange, /* Non-NULL for UPDATE operations */
134478 if( pParse->db->flags&SQLITE_ForeignKeys && IsOrdinaryTable(pTab) ){
134483 bHaveFK = (sqlite3FkReferences(pTab) || pTab->u.tab.pFKey);
134485 /* This is an UPDATE. Foreign key processing is only required if the
134490 for(p=pTab->u.tab.pFKey; p; p=p->pNextFrom){
134492 if( 0==sqlite3_stricmp(pTab->zName, p->zTo) ) eRet = 2;
134498 for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
134500 if( (pParse->db->flags & SQLITE_FkNoAction)==0
134501 && p->aAction[1]!=OE_None
134514 ** This function is called when an UPDATE or DELETE operation is being
134515 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
134516 ** If the current operation is an UPDATE, then the pChanges parameter is
134523 ** require no special handling by the triggers sub-system, code for them is
134546 ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
134548 sqlite3 *db = pParse->db; /* Database handle */
134553 action = pFKey->aAction[iAction];
134554 if( (db->flags & SQLITE_FkNoAction) ) action = OE_None;
134555 if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
134558 pTrigger = pFKey->apTrigger[iAction];
134564 int *aiCol = 0; /* child table cols -> parent key cols */
134573 assert( aiCol || pFKey->nCol==1 );
134575 for(i=0; i<pFKey->nCol; i++){
134583 iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
134585 assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
134586 assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
134588 pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zCnName);
134589 sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zCnName);
134627 Column *pCol = pFKey->pFrom->aCol + iFromCol;
134629 if( pCol->colFlags & COLFLAG_GENERATED ){
134630 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
134631 testcase( pCol->colFlags & COLFLAG_STORED );
134634 pDflt = sqlite3ColumnExpr(pFKey->pFrom, pCol);
134650 zFrom = pFKey->pFrom->zName;
134654 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
134661 pRaise->affExpr = OE_Abort;
134665 assert( pSrc->nSrc==1 );
134666 pSrc->a[0].zName = sqlite3DbStrDup(db, zFrom);
134667 assert( pSrc->a[0].fg.fixedSchema==0 && pSrc->a[0].fg.isSubquery==0 );
134668 pSrc->a[0].u4.zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zDbSName);
134685 nFrom + 1 /* Space for pStep->zTarget */
134688 pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
134689 pStep->zTarget = (char *)&pStep[1];
134690 memcpy((char *)pStep->zTarget, zFrom, nFrom);
134692 pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
134693 pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
134694 pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
134697 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
134701 /* Re-enable the lookaside buffer, if it was disabled earlier. */
134708 if( db->mallocFailed==1 ){
134717 pStep->op = TK_SELECT;
134721 pStep->op = TK_DELETE;
134726 pStep->op = TK_UPDATE;
134728 pStep->pTrig = pTrigger;
134729 pTrigger->pSchema = pTab->pSchema;
134730 pTrigger->pTabSchema = pTab->pSchema;
134731 pFKey->apTrigger[iAction] = pTrigger;
134732 pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
134745 ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
134750 /* If foreign-key support is enabled, iterate through all FKs that
134751 ** refer to table pTab. If there is an action associated with the FK
134753 ** trigger sub-program. */
134754 if( pParse->db->flags&SQLITE_ForeignKeys ){
134756 for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
134776 FKey *pNext; /* Copy of pFKey->pNextFrom */
134780 for(pFKey=pTab->u.tab.pFKey; pFKey; pFKey=pNext){
134781 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
134784 if( db->pnBytesFreed==0 ){
134785 if( pFKey->pPrevTo ){
134786 pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
134788 const char *z = (pFKey->pNextTo ? pFKey->pNextTo->zTo : pFKey->zTo);
134789 sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, pFKey->pNextTo);
134791 if( pFKey->pNextTo ){
134792 pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
134796 /* EV: R-30323-21917 Each foreign key constraint in SQLite is
134799 assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
134803 fkTriggerDelete(db, pFKey->apTrigger[0]);
134804 fkTriggerDelete(db, pFKey->apTrigger[1]);
134807 pNext = pFKey->pNextFrom;
134849 assert( pParse->pVdbe!=0 );
134850 v = pParse->pVdbe;
134852 if( !pParse->db->noSharedCache ){
134853 sqlite3TableLock(pParse, iDb, pTab->tnum,
134854 (opcode==OP_OpenWrite)?1:0, pTab->zName);
134857 sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nNVCol);
134858 VdbeComment((v, "%s", pTab->zName));
134862 assert( pPk->tnum==pTab->tnum || CORRUPT_DB );
134863 sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
134865 VdbeComment((v, "%s", pTab->zName));
134875 ** ------------------------------
134882 ** An extra 'D' is appended to the end of the string to cover the
134899 Table *pTab = pIdx->pTable;
134900 pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
134901 if( !pIdx->zColAff ){
134905 for(n=0; n<pIdx->nColumn; n++){
134906 i16 x = pIdx->aiColumn[n];
134909 aff = pTab->aCol[x].affinity;
134914 assert( pIdx->bHasExpr );
134915 assert( pIdx->aColExpr!=0 );
134916 aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
134920 pIdx->zColAff[n] = aff;
134922 pIdx->zColAff[n] = 0;
134923 return pIdx->zColAff;
134926 if( !pIdx->zColAff ) return computeIndexAffStr(db, pIdx);
134927 return pIdx->zColAff;
134932 ** Compute an affinity string for a table. Space is obtained
134938 zColAff = (char *)sqlite3DbMallocRaw(db, pTab->nCol+1);
134941 for(i=j=0; i<pTab->nCol; i++){
134942 if( (pTab->aCol[i].colFlags & COLFLAG_VIRTUAL)==0 ){
134943 zColAff[j++] = pTab->aCol[i].affinity;
134947 zColAff[j--] = 0;
134957 ** For ordinary (legacy, non-strict) tables:
134958 ** -----------------------------------------
134961 ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
134964 ** which were then optimized out) then this routine becomes a no-op.
134966 ** Otherwise if iReg>0 then code an OP_Affinity opcode that will set the
134969 ** an OP_MakeRecord) to the affinity string.
134974 ** --------- ---------------
134982 ** ------------------
134984 ** Generate an appropriate OP_TypeCheck opcode that will verify the
134986 ** means an OP_MakeRecord opcode has already been generated and should be
134996 if( pTab->tabFlags & TF_Strict ){
135005 assert( pPrev->opcode==OP_MakeRecord || sqlite3VdbeDb(v)->mallocFailed );
135006 pPrev->opcode = OP_TypeCheck;
135007 sqlite3VdbeAddOp3(v, OP_MakeRecord, pPrev->p1, pPrev->p2, pPrev->p3);
135009 /* Insert an isolated OP_Typecheck */
135010 sqlite3VdbeAddOp2(v, OP_TypeCheck, iReg, pTab->nNVCol);
135015 zColAff = pTab->zColAff;
135022 pTab->zColAff = zColAff;
135030 assert( sqlite3VdbeGetLastOp(v)->opcode==OP_MakeRecord
135031 || sqlite3VdbeDb(v)->mallocFailed );
135032 sqlite3VdbeChangeP4(v, -1, zColAff, i);
135038 ** Return non-zero if the table pTab in database iDb or any of its indices
135048 VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
135054 if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
135056 Pgno tnum = pOp->p2;
135057 if( tnum==pTab->tnum ){
135060 for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
135061 if( tnum==pIndex->tnum ){
135067 if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
135068 assert( pOp->p4.pVtab!=0 );
135069 assert( pOp->p4type==P4_VTAB );
135081 if( pExpr->op==TK_COLUMN && pExpr->iColumn>=0 ){
135082 assert( pExpr->iColumn < pWalker->u.pTab->nCol );
135083 pWalker->eCode |= pWalker->u.pTab->aCol[pExpr->iColumn].colFlags;
135107 assert( pTab->tabFlags & TF_HasGenerated );
135108 testcase( pTab->tabFlags & TF_HasVirtual );
135109 testcase( pTab->tabFlags & TF_HasStored );
135114 sqlite3TableAffinity(pParse->pVdbe, pTab, iRegStore);
135115 if( (pTab->tabFlags & TF_HasStored)!=0 ){
135116 pOp = sqlite3VdbeGetLastOp(pParse->pVdbe);
135117 if( pOp->opcode==OP_Affinity ){
135119 ** columns. '@' is the no-op affinity and those columns have not
135122 char *zP4 = pOp->p4.z;
135124 assert( pOp->p4type==P4_DYNAMIC );
135126 if( pTab->aCol[ii].colFlags & COLFLAG_VIRTUAL ){
135129 if( pTab->aCol[ii].colFlags & COLFLAG_STORED ){
135134 }else if( pOp->opcode==OP_TypeCheck ){
135135 /* If an OP_TypeCheck was generated because the table is STRICT,
135138 pOp->p3 = 1;
135143 ** this is a two-pass algorithm. On the first pass, mark all generated
135146 for(i=0; i<pTab->nCol; i++){
135147 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
135148 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
135149 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
135150 pTab->aCol[i].colFlags |= COLFLAG_NOTAVAIL;
135159 /* On the second pass, compute the value of each NOT-AVAILABLE column.
135164 pParse->iSelfTab = -iRegStore;
135168 for(i=0; i<pTab->nCol; i++){
135169 Column *pCol = pTab->aCol + i;
135170 if( (pCol->colFlags & COLFLAG_NOTAVAIL)!=0 ){
135172 pCol->colFlags |= COLFLAG_BUSY;
135175 pCol->colFlags &= ~COLFLAG_BUSY;
135181 assert( pCol->colFlags & COLFLAG_GENERATED );
135184 pCol->colFlags &= ~COLFLAG_NOTAVAIL;
135189 sqlite3ErrorMsg(pParse, "generated column loop on \"%s\"", pRedo->zCnName);
135191 pParse->iSelfTab = 0;
135198 ** Locate or create an AutoincInfo structure associated with table pTab
135200 ** that holds the maximum rowid. Return zero if pTab is not an AUTOINCREMENT
135226 assert( pParse->db->aDb[iDb].pSchema!=0 );
135227 if( (pTab->tabFlags & TF_Autoincrement)!=0
135228 && (pParse->db->mDbFlags & DBFLAG_Vacuum)==0
135232 Table *pSeqTab = pParse->db->aDb[iDb].pSchema->pSeqTab;
135234 /* Verify that the sqlite_sequence table exists and is an ordinary
135236 ** Ticket d8dc2b3a58cd5dc2918a1d4acb 2018-05-23 */
135240 || pSeqTab->nCol!=2
135242 pParse->nErr++;
135243 pParse->rc = SQLITE_CORRUPT_SEQUENCE;
135247 pInfo = pToplevel->pAinc;
135248 while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
135250 pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
135252 testcase( pParse->earlyCleanup );
135253 if( pParse->db->mallocFailed ) return 0;
135254 pInfo->pNext = pToplevel->pAinc;
135255 pToplevel->pAinc = pInfo;
135256 pInfo->pTab = pTab;
135257 pInfo->iDb = iDb;
135258 pToplevel->nMem++; /* Register to hold name of table */
135259 pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
135260 pToplevel->nMem +=2; /* Rowid in sqlite_sequence + orig max val */
135262 memId = pInfo->regCtr;
135272 AutoincInfo *p; /* Information about an AUTOINCREMENT */
135273 sqlite3 *db = pParse->db; /* The database connection */
135276 Vdbe *v = pParse->pVdbe; /* VDBE under construction */
135278 /* This routine is never called during trigger-generation. It is
135279 ** only called from the top-level */
135280 assert( pParse->pTriggerTab==0 );
135284 for(p = pParse->pAinc; p; p = p->pNext){
135301 pDb = &db->aDb[p->iDb];
135302 memId = p->regCtr;
135303 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
135304 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
135305 sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
135311 aOp[3].p1 = memId-1;
135320 if( pParse->nTab==0 ) pParse->nTab = 1;
135325 ** Update the maximum rowid for an autoincrement calculation.
135334 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
135341 ** Every statement that might do an INSERT into an autoincrement
135347 Vdbe *v = pParse->pVdbe;
135348 sqlite3 *db = pParse->db;
135351 for(p = pParse->pAinc; p; p = p->pNext){
135361 Db *pDb = &db->aDb[p->iDb];
135363 int memId = p->regCtr;
135366 assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
135369 sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
135374 aOp[2].p1 = memId-1;
135383 if( pParse->pAinc ) autoIncrementEnd(pParse);
135388 ** above are all no-ops
135395 ** If argument pVal is a Select object returned by an sqlite3MultiValues()
135396 ** that was able to use the co-routine optimization, finish coding the
135397 ** co-routine.
135400 if( ALWAYS(pVal) && pVal->pSrc->nSrc>0 ){
135401 SrcItem *pItem = &pVal->pSrc->a[0];
135402 assert( (pItem->fg.isSubquery && pItem->u4.pSubq!=0) || pParse->nErr );
135403 if( pItem->fg.isSubquery ){
135404 sqlite3VdbeEndCoroutine(pParse->pVdbe, pItem->u4.pSubq->regReturn);
135405 sqlite3VdbeJumpHere(pParse->pVdbe, pItem->u4.pSubq->addrFillSub - 1);
135411 ** Return true if all expressions in the expression-list passed as the
135416 for(ii=0; ii<pRow->nExpr; ii++){
135417 if( 0==sqlite3ExprIsConstant(pParse, pRow->a[ii].pExpr) ) return 0;
135423 ** Return true if all expressions in the expression-list passed as the
135429 for(ii=0; ii<pRow->nExpr; ii++){
135430 Expr *pExpr = pRow->a[ii].pExpr;
135431 assert( pExpr->op!=TK_RAISE );
135432 assert( pExpr->affExpr==0 );
135441 ** rows of a multi-row VALUES clause. Argument pLeft is the part of
135446 ** There are two ways in which this may be achieved - by incremental
135447 ** coding of a co-routine (the "co-routine" method) or by returning a
135455 ** When the co-routine method is used, each row that will be returned
135456 ** by the VALUES clause is coded into part of a co-routine as it is
135460 ** Select object to read co-routine
135463 ** The co-routine method is used in most cases. Exceptions are:
135471 ** This will not work, as the co-routine uses a hard-coded register
135478 ** a co-routine is not possible.
135480 ** c) There are non-constant expressions in the VALUES clause (e.g.
135481 ** the VALUES clause is part of a correlated sub-query).
135484 ** has an affinity (i.e. is a CAST expression). This causes problems
135492 if( pParse->bHasWith /* condition (a) above */
135493 || pParse->db->init.busy /* condition (b) above */
135495 || (pLeft->pSrc->nSrc==0 &&
135496 exprListIsNoAffinity(pParse,pLeft->pEList)==0) /* condition (d) above */
135499 /* The co-routine method cannot be used. Fall back to UNION ALL. */
135502 if( pLeft->pSrc->nSrc ){
135505 }else if( pLeft->pPrior ){
135507 f = (f & pLeft->selFlags);
135510 pLeft->selFlags &= ~(u32)SF_MultiValue;
135512 pSelect->op = TK_ALL;
135513 pSelect->pPrior = pLeft;
135517 SrcItem *p = 0; /* SrcItem that reads from co-routine */
135519 if( pLeft->pSrc->nSrc==0 ){
135520 /* Co-routine has not yet been started and the special Select object
135521 ** that accesses the co-routine has not yet been created. This block
135528 if( (pParse->db->mDbFlags & DBFLAG_SchemaKnownOk)==0 ){
135535 pRet->pSrc->nSrc = 1;
135536 pRet->pPrior = pLeft->pPrior;
135537 pRet->op = pLeft->op;
135538 if( pRet->pPrior ) pRet->selFlags |= SF_Values;
135539 pLeft->pPrior = 0;
135540 pLeft->op = TK_SELECT;
135541 assert( pLeft->pNext==0 );
135542 assert( pRet->pNext==0 );
135543 p = &pRet->pSrc->a[0];
135544 p->fg.viaCoroutine = 1;
135545 p->iCursor = -1;
135546 assert( !p->fg.isIndexedBy && !p->fg.isTabFunc );
135547 p->u1.nRow = 2;
135549 pSubq = p->u4.pSubq;
135550 pSubq->addrFillSub = sqlite3VdbeCurrentAddr(v) + 1;
135551 pSubq->regReturn = ++pParse->nMem;
135553 pSubq->regReturn, 0, pSubq->addrFillSub);
135554 sqlite3SelectDestInit(&dest, SRT_Coroutine, pSubq->regReturn);
135556 /* Allocate registers for the output of the co-routine. Do so so
135558 ** used by the co-routine. This allows the code in sqlite3Insert()
135560 ** of the co-routine to a separate array for processing. */
135561 dest.iSdst = pParse->nMem + 3;
135562 dest.nSdst = pLeft->pEList->nExpr;
135563 pParse->nMem += 2 + dest.nSdst;
135565 pLeft->selFlags |= SF_MultiValue;
135567 pSubq->regResult = dest.iSdst;
135568 assert( pParse->nErr || dest.iSdst>0 );
135573 p = &pLeft->pSrc->a[0];
135574 assert( !p->fg.isTabFunc && !p->fg.isIndexedBy );
135575 p->u1.nRow++;
135578 if( pParse->nErr==0 ){
135581 assert( p->fg.isSubquery );
135582 pSubq = p->u4.pSubq;
135584 assert( pSubq->pSelect!=0 );
135585 assert( pSubq->pSelect->pEList!=0 );
135586 if( pSubq->pSelect->pEList->nExpr!=pRow->nExpr ){
135587 sqlite3SelectWrongNumTermsError(pParse, pSubq->pSelect);
135589 sqlite3ExprCodeExprList(pParse, pRow, pSubq->regResult, 0, 0);
135590 sqlite3VdbeAddOp1(pParse->pVdbe, OP_Yield, pSubq->regReturn);
135593 sqlite3ExprListDelete(pParse->db, pRow);
135616 ** then a list of all (non-hidden) columns for the table is substituted.
135621 ** first two forms shown above. A VALUES clause is really just short-hand
135627 ** insert with data coming from a single-row VALUES clause, the code executes
135628 ** once straight down through. Pseudo-code follows (we call this
135640 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
135664 ** X <- A
135672 ** end-coroutine X
135682 ** we have to use an intermediate table to store the results of
135685 ** X <- A
135693 ** end co-routine R
135722 int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
135730 u8 appendFlag = 0; /* True if the insert is likely to be an append */
135752 db = pParse->db;
135753 assert( db->pParse==pParse );
135754 if( pParse->nErr ){
135757 assert( db->mallocFailed==0 );
135764 if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
135765 pList = pSelect->pEList;
135766 pSelect->pEList = 0;
135773 assert( pTabList->nSrc==1 );
135778 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
135779 assert( iDb<db->nDb );
135780 if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0,
135781 db->aDb[iDb].zDbSName) ){
135806 sqlite3TreeViewInsert(pParse->pWith, pTabList, pColumn, pSelect, pList,
135812 ** ViewGetColumnNames() is a no-op if pTab is not a view.
135818 /* Cannot insert into a read-only table.
135828 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
135852 /* If this is an AUTOINCREMENT table, look up the sequence number in the
135860 regRowid = regIns = pParse->nMem+1;
135861 pParse->nMem += pTab->nCol + 1;
135864 pParse->nMem++;
135868 /* If the INSERT statement included an IDLIST term, then make sure
135872 ** If the table has an INTEGER PRIMARY KEY column and that column
135877 ** PRIMARY KEY in the original table is pTab->iPKey.) After this
135878 ** loop, if ipkColumn==(-1), that means that integer primary key
135880 ** it will automatically generated an integer primary key.
135883 ** order. This enables an optimization that avoids shuffling the
135887 bIdListInOrder = (pTab->tabFlags & (TF_OOOHidden|TF_HasStored))==0;
135889 aTabColMap = sqlite3DbMallocZero(db, pTab->nCol*sizeof(int));
135891 for(i=0; i<pColumn->nId; i++){
135892 j = sqlite3ColumnIndex(pTab, pColumn->a[i].zName);
135896 if( j==pTab->iPKey ){
135900 if( pTab->aCol[j].colFlags & (COLFLAG_STORED|COLFLAG_VIRTUAL) ){
135903 pTab->aCol[j].zCnName);
135908 if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
135913 pTabList->a, pColumn->a[i].zName);
135914 pParse->checkSchema = 1;
135922 ** is coming from a SELECT statement, then generate a co-routine that
135924 ** co-routine is the common header to the 3rd and 4th templates.
135927 /* Data is coming from a SELECT or from a multi-row VALUES clause.
135928 ** Generate a co-routine to run the SELECT. */
135931 if( pSelect->pSrc->nSrc==1
135932 && pSelect->pSrc->a[0].fg.viaCoroutine
135933 && pSelect->pPrior==0
135935 SrcItem *pItem = &pSelect->pSrc->a[0];
135937 assert( pItem->fg.isSubquery );
135938 pSubq = pItem->u4.pSubq;
135939 dest.iSDParm = pSubq->regReturn;
135940 regFromSelect = pSubq->regResult;
135941 assert( pSubq->pSelect!=0 );
135942 assert( pSubq->pSelect->pEList!=0 );
135943 nColumn = pSubq->pSelect->pEList->nExpr;
135945 if( bIdListInOrder && nColumn==pTab->nCol ){
135947 regRowid = regData - 1;
135948 regIns = regRowid - (IsVirtual(pTab) ? 1 : 0);
135951 int addrTop; /* Top of the co-routine */
135952 int regYield = ++pParse->nMem;
135957 dest.nSdst = pTab->nCol;
135960 assert( db->pParse==pParse );
135961 if( rc || pParse->nErr ) goto insert_cleanup;
135962 assert( db->mallocFailed==0 );
135964 sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
135965 assert( pSelect->pEList );
135966 nColumn = pSelect->pEList->nExpr;
135997 srcTab = pParse->nTab++;
136012 ** single-row VALUES clause
136017 srcTab = -1;
136020 nColumn = pList->nExpr;
136029 /* If there is no IDLIST term but the table has an integer primary
136034 ipkColumn = pTab->iPKey;
136036 if( ipkColumn>=0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
136037 testcase( pTab->tabFlags & TF_HasVirtual );
136038 testcase( pTab->tabFlags & TF_HasStored );
136039 for(i=ipkColumn-1; i>=0; i--){
136040 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
136041 testcase( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL );
136042 testcase( pTab->aCol[i].colFlags & COLFLAG_STORED );
136043 ipkColumn--;
136055 if( (pTab->tabFlags & (TF_HasGenerated|TF_HasHidden))!=0 ){
136056 for(i=0; i<pTab->nCol; i++){
136057 if( pTab->aCol[i].colFlags & COLFLAG_NOINSERT ) nHidden++;
136060 if( nColumn!=(pTab->nCol-nHidden) ){
136063 pTabList->a, pTab->nCol-nHidden, nColumn);
136067 if( pColumn!=0 && nColumn!=pColumn->nId ){
136068 sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
136074 if( (db->flags & SQLITE_CountRows)!=0
136075 && !pParse->nested
136076 && !pParse->pTriggerTab
136077 && !pParse->bReturning
136079 regRowCount = ++pParse->nMem;
136086 nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
136092 for(i=0, pIdx=pTab->pIndex; i<nIdx; pIdx=pIdx->pNext, i++){
136094 aRegIdx[i] = ++pParse->nMem;
136095 pParse->nMem += pIdx->nColumn;
136097 aRegIdx[i] = ++pParse->nMem; /* Register to store the table record */
136104 pTab->zName);
136111 if( sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget) ){
136114 pTabList->a[0].iCursor = iDataCur;
136117 pNx->pUpsertSrc = pTabList;
136118 pNx->regData = regData;
136119 pNx->iDataCur = iDataCur;
136120 pNx->iIdxCur = iIdxCur;
136121 if( pNx->pUpsertTarget ){
136126 pNx = pNx->pNextUpsert;
136154 sqlite3VdbeReleaseRegisters(pParse, regData, pTab->nCol, 0, 0);
136158 /* tag-20191021-001: If the INTEGER PRIMARY KEY is being generated by the
136160 ** the value does not get overwritten by a NULL at tag-20191021-002. */
136174 for(i=0; i<pTab->nCol; i++, iRegStore++){
136178 if( i==pTab->iPKey ){
136179 /* tag-20191021-002: References to the INTEGER PRIMARY KEY are filled
136182 ** NULL - we cannot optimize further by skipping the column completely */
136186 if( ((colFlags = pTab->aCol[i].colFlags) & COLFLAG_NOINSERT)!=0 ){
136192 iRegStore--;
136196 ** triggers, the slots used for stored columns will be OP_Copy-ed
136198 ** initialized to NULL to avoid an uninitialized register read */
136207 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
136214 assert( j>=0 && j<=pColumn->nId );
136219 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
136223 k = j - 1;
136227 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
136231 k = i - nHidden;
136241 Expr *pX = pList->a[k].pExpr;
136255 int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
136257 /* build the NEW.* reference row. Note that if there is an INTEGER
136261 ** not happened yet) so we substitute a rowid of -1
136264 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
136272 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
136275 sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
136281 assert( pTab->nNVCol>0 || pParse->nErr>0 );
136282 sqlite3VdbeAddOp3(v, OP_Copy, regRowid+1, regCols+1, pTab->nNVCol-1);
136289 if( pTab->tabFlags & TF_HasGenerated ){
136290 testcase( pTab->tabFlags & TF_HasVirtual );
136291 testcase( pTab->tabFlags & TF_HasStored );
136296 /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
136307 pTab, regCols-pTab->nCol-1, onError, endOfLoop);
136309 sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
136322 /* Rowid already initialized at tag-20191021-001 */
136324 Expr *pIpk = pList->a[ipkColumn].pExpr;
136325 if( pIpk->op==TK_NULL && !IsVirtual(pTab) ){
136329 sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
136360 if( pTab->tabFlags & TF_HasGenerated ){
136372 sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
136383 if( db->flags & SQLITE_ForeignKeys ){
136390 ** flag in the second case as if any REPLACE constraint is hit, an
136401 }else if( pParse->bReturning ){
136403 ** constant value -1, in case one or more of the returned expressions
136405 sqlite3VdbeAddOp2(v, OP_Integer, -1, regRowid);
136418 pTab, regData-2-pTab->nCol, onError, endOfLoop);
136432 /* If we are jumping back to an OP_Yield that is preceded by an
136435 if( sqlite3VdbeGetOp(v, addrCont-1)->opcode==OP_ReleaseReg ){
136436 assert( sqlite3VdbeGetOp(v, addrCont)->opcode==OP_Yield );
136450 if( pParse->nested==0 && pParse->pTriggerTab==0 ){
136489 ** Meanings of bits in of pWalker->eCode for
136496 * Set bit 0x01 of pWalker->eCode if pWalker->eCode to 0 and if this
136498 ** columns that are being modified by an UPDATE statement.
136501 if( pExpr->op==TK_COLUMN ){
136502 assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
136503 if( pExpr->iColumn>=0 ){
136504 if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
136505 pWalker->eCode |= CKCNSTRNT_COLUMN;
136508 pWalker->eCode |= CKCNSTRNT_ROWID;
136515 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
136524 ** 2018-09-15: pExpr might also be an expression for an index-on-expressions.
136525 ** The operation of this routine is the same - return true if an only if
136553 ** the indexes of a table in the order provided in the Table->pIndex list.
136554 ** However, sometimes (rarely - when there is an upsert) it wants to visit
136560 ** by an array of IndexListTerm objects.
136565 int eType; /* 0 for Index.pNext list. 1 for an array of IndexListTerm */
136578 /* When IndexIterator.eType==1, then each index is an array of instances
136588 assert( pIter->i==0 );
136589 if( pIter->eType ){
136590 *pIx = pIter->u.ax.aIdx[0].ix;
136591 return pIter->u.ax.aIdx[0].p;
136594 return pIter->u.lx.pIdx;
136600 if( pIter->eType ){
136601 int i = ++pIter->i;
136602 if( i>=pIter->u.ax.nIdx ){
136606 *pIx = pIter->u.ax.aIdx[i].ix;
136607 return pIter->u.ax.aIdx[i].p;
136610 pIter->u.lx.pIdx = pIter->u.lx.pIdx->pNext;
136611 return pIter->u.lx.pIdx;
136616 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
136621 ** pTab->nCol+1 registers in this range. The first register (the one
136628 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
136629 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
136632 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
136637 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
136640 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
136641 ** pkChng will only be true if the INSERT statement provides an integer
136648 ** at pTab->pIndex.
136650 ** (2019-05-07) The generated code also creates a new record for the
136652 ** register identified by aRegIdx[nIdx] - in other words in the first
136663 ** for the first index in the pTab->pIndex list. Cursors for other indices
136664 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
136672 ** --------------- ---------- ----------------------------------------
136688 ** row is skipped, without throwing an error.
136690 ** (There is an immediate jump to ignoreDest.)
136699 ** CHECK REPLACE Illegal. The results in an exception.
136702 ** Or if overrideError==OE_Default, then the pParse->onError parameter
136703 ** is used. Or if pParse->onError==OE_Default then the onError value
136714 u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
136716 int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
136732 u8 isUpdate; /* True if this is an UPDATE operation */
136748 db = pParse->db;
136749 v = pParse->pVdbe;
136752 nCol = pTab->nCol;
136763 nPkField = pPk->nKeyCol;
136772 if( pTab->tabFlags & TF_HasNotNull ){
136779 Column *pCol = &pTab->aCol[i]; /* The column to check for NOT NULL */
136780 int isGenerated; /* non-zero if column is generated */
136781 onError = pCol->notNull;
136783 if( i==pTab->iPKey ){
136786 isGenerated = pCol->colFlags & COLFLAG_GENERATED;
136802 || pCol->iDflt==0 /* REPLACE is ABORT if no DEFAULT value */
136804 testcase( pCol->colFlags & COLFLAG_VIRTUAL );
136805 testcase( pCol->colFlags & COLFLAG_STORED );
136806 testcase( pCol->colFlags & COLFLAG_GENERATED );
136822 assert( (pCol->colFlags & COLFLAG_GENERATED)==0 );
136834 char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
136835 pCol->zCnName);
136836 testcase( zMsg==0 && db->mallocFailed==0 );
136861 if( nSeenReplace>0 && (pTab->tabFlags & TF_HasGenerated)!=0 ){
136869 } /* end of 2-pass loop */
136870 } /* end if( has-not-null-constraints ) */
136875 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
136876 ExprList *pCheck = pTab->pCheck;
136877 pParse->iSelfTab = -(regNewData+1);
136879 for(i=0; i<pCheck->nExpr; i++){
136882 Expr *pExpr = pCheck->a[i].pExpr;
136897 if( !db->mallocFailed ){
136904 char *zName = pCheck->a[i].zEName;
136905 assert( zName!=0 || pParse->db->mallocFailed );
136906 if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-26383-51744 */
136913 pParse->iSelfTab = 0;
136930 ** 2018-08-14: Ticket https://sqlite.org/src/info/908f001483982c43
136948 sIdxIter.u.lx.pIdx = pTab->pIndex;
136950 if( pUpsert->pUpsertTarget==0 ){
136951 /* There is just on ON CONFLICT clause and it has no constraint-target */
136952 assert( pUpsert->pNextUpsert==0 );
136953 if( pUpsert->isDoUpdate==0 ){
136954 /* A single ON CONFLICT DO NOTHING clause, without a constraint-target.
136962 }else if( pTab->pIndex!=0 ){
136970 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
136979 pUpsert->pToFree = sIdxIter.u.ax.aIdx;
136980 for(i=0, pTerm=pUpsert; pTerm; pTerm=pTerm->pNextUpsert){
136981 if( pTerm->pUpsertTarget==0 ) break;
136982 if( pTerm->pUpsertIdx==0 ) continue; /* Skip ON CONFLICT for the IPK */
136984 pIdx = pTab->pIndex;
136985 while( ALWAYS(pIdx!=0) && pIdx!=pTerm->pUpsertIdx ){
136986 pIdx = pIdx->pNext;
136995 for(jj=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, jj++){
137025 if( (db->flags & (SQLITE_RecTriggers|SQLITE_ForeignKeys))==0 ){
137031 if( db->flags&SQLITE_RecTriggers ){
137041 regTrigCnt = ++pParse->nMem;
137056 onError = pTab->keyConf;
137067 if( pUpsertClause->isDoUpdate==0 ){
137088 && pTab->pIndex /* There exist other constraints */
137127 ** recursive-triggers flag is set, call GenerateRowDelete() to
137129 ** the triggers and remove both the table and index b-tree entries.
137131 ** Otherwise, if there are no triggers or the recursive-triggers
137133 ** GenerateRowIndexDelete(). This removes the index b-tree entries
137134 ** only. The table b-tree entry will be replaced by the new entry
137151 regNewData, 1, 0, OE_Replace, 1, -1);
137157 /* This OP_Delete opcode fires the pre-update-hook only. It does
137158 ** not modify the b-tree. It is more efficient to let the coming
137164 if( pTab->pIndex ){
137166 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
137189 sqlite3VdbeJumpHere(v, ipkTop-1);
137222 VdbeNoopComment((v, "prep index %s", pIdx->zName));
137227 if( pIdx->pPartIdxWhere ){
137229 pParse->iSelfTab = -(regNewData+1);
137230 sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
137232 pParse->iSelfTab = 0;
137239 for(i=0; i<pIdx->nColumn; i++){
137240 int iField = pIdx->aiColumn[i];
137243 pParse->iSelfTab = -(regNewData+1);
137244 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
137245 pParse->iSelfTab = 0;
137246 VdbeComment((v, "%s column %d", pIdx->zName, i));
137247 }else if( iField==XN_ROWID || iField==pTab->iPKey ){
137255 VdbeComment((v, "%s", pTab->aCol[iField].zCnName));
137258 sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
137259 VdbeComment((v, "for %s", pIdx->zName));
137261 if( pIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
137262 sqlite3SetMakeRecordP5(v, pIdx->pTable);
137265 sqlite3VdbeReleaseRegisters(pParse, regIdx, pIdx->nColumn, 0, 0);
137267 /* In an UPDATE operation, if this index is the PRIMARY KEY index
137277 onError = pIdx->onError;
137290 if( pUpsertClause->isDoUpdate==0 ){
137305 ** must be explicitly deleted in order to ensure any pre-update hook
137309 if( (ix==0 && pIdx->pNext==0) /* Condition 3 */
137312 && ( 0==(db->flags&SQLITE_RecTriggers) || /* Condition 4 */
137314 && ( 0==(db->flags&SQLITE_ForeignKeys) || /* Condition 5 */
137315 (0==pTab->u.tab.pFKey && 0==sqlite3FkReferences(pTab)))
137326 regIdx, pIdx->nKeyCol); VdbeCoverage(v);
137334 ** is different from old-rowid */
137343 ** store it in registers regR..regR+nPk-1 */
137345 for(i=0; i<pPk->nKeyCol; i++){
137346 assert( pPk->aiColumn[i]>=0 );
137347 x = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
137349 VdbeComment((v, "%s.%s", pTab->zName,
137350 pTab->aCol[pPk->aiColumn[i]].zCnName));
137361 int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
137365 for(i=0; i<pPk->nKeyCol; i++){
137366 char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
137367 x = pPk->aiColumn[i];
137369 if( i==(pPk->nKeyCol-1) ){
137413 nConflictCk = sqlite3VdbeCurrentAddr(v) - addrConflictCk;
137414 assert( nConflictCk>0 || db->mallocFailed );
137442 if( pIdx->pPartIdxWhere ){
137445 sqlite3VdbeAddOp2(v, OP_IsNull, regIdx-1, lblRecheckOk);
137449 ** the constraint-ok jump destination to be the address of
137470 nConflictCk--;
137473 /* If the retest fails, issue an abort */
137525 sqlite3VdbeAddOp3(v, OP_MakeRecord, regNewData+1, pTab->nNVCol, regRec);
137538 ** Change the P5 operand on the last opcode (which should be an OP_MakeRecord)
137539 ** to be the number of columns in table pTab that must not be NULL-trimmed.
137541 ** Or if no columns of pTab may be NULL-trimmed, leave P5 at zero.
137547 ** version 2 and later (SQLite version 3.1.4, 2005-02-20). */
137548 if( pTab->pSchema->file_format<2 ) return;
137550 for(i=pTab->nCol-1; i>0; i--){
137551 if( pTab->aCol[i].iDflt!=0 ) break;
137552 if( pTab->aCol[i].colFlags & COLFLAG_PRIMKEY ) break;
137561 ** PK index. This function adds code to invoke the pre-update hook,
137571 Vdbe *v = pParse->pVdbe;
137574 assert( 0==(pParse->db->mDbFlags & DBFLAG_Vacuum) || CORRUPT_DB );
137601 int appendBias, /* True if this is likely to be an append */
137605 Index *pIdx; /* An index being inserted or updated */
137614 v = pParse->pVdbe;
137617 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
137619 assert( pIdx->onError!=OE_Replace
137620 || pIdx->pNext==0
137621 || pIdx->pNext->onError==OE_Replace );
137623 if( pIdx->pPartIdxWhere ){
137637 pIdx->uniqNotNull ? pIdx->nKeyCol: pIdx->nColumn);
137641 if( pParse->nested ){
137654 if( !pParse->nested ){
137670 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
137676 ** pTab->pIndex list.
137678 ** If pTab is a virtual table, then this routine is a no-op and the
137702 /* This routine is a no-op for virtual tables. Leave the output
137705 *piDataCur = *piIdxCur = -999;
137708 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
137709 v = pParse->pVdbe;
137711 if( iBase<0 ) iBase = pParse->nTab;
137716 }else if( pParse->db->noSharedCache==0 ){
137717 sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
137720 for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
137722 assert( pIdx->pSchema==pTab->pSchema );
137728 sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
137731 VdbeComment((v, "%s", pIdx->zName));
137734 if( iBase>pParse->nTab ) pParse->nTab = iBase;
137743 ** purposes only - to make sure the transfer optimization really
137753 ** for index pDest in an insert transfer optimization. The rules
137765 assert( pDest->pTable!=pSrc->pTable );
137766 if( pDest->nKeyCol!=pSrc->nKeyCol || pDest->nColumn!=pSrc->nColumn ){
137769 if( pDest->onError!=pSrc->onError ){
137772 for(i=0; i<pSrc->nKeyCol; i++){
137773 if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
137776 if( pSrc->aiColumn[i]==XN_EXPR ){
137777 assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
137778 if( sqlite3ExprCompare(0, pSrc->aColExpr->a[i].pExpr,
137779 pDest->aColExpr->a[i].pExpr, -1)!=0 ){
137783 if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
137786 if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
137790 if( sqlite3ExprCompare(0, pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
137808 ** There are lots of rules for determining compatibility - see comments
137813 ** is empty - a factor that can only be determined at run-time. In that
137818 ** an unoptimized transfer. This routine also returns FALSE if there
137830 sqlite3 *db = pParse->db;
137834 SrcItem *pItem; /* An element of pSelect->pSrc */
137847 if( pParse->pWith || pSelect->pWith ){
137848 /* Do not attempt to process this query if there are an WITH clauses
137859 if( pDest->iPKey>=0 ) onError = pDest->keyConf;
137862 assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
137863 if( pSelect->pSrc->nSrc!=1 ){
137866 if( pSelect->pSrc->a[0].fg.isSubquery ){
137869 if( pSelect->pWhere ){
137872 if( pSelect->pOrderBy ){
137873 return 0; /* SELECT may not have an ORDER BY clause */
137876 ** there is no ORDER BY, we will get an error. */
137877 if( pSelect->pGroupBy ){
137880 if( pSelect->pLimit ){
137883 if( pSelect->pPrior ){
137886 if( pSelect->selFlags & SF_Distinct ){
137889 pEList = pSelect->pEList;
137891 if( pEList->nExpr!=1 ){
137894 assert( pEList->a[0].pExpr );
137895 if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
137903 pItem = pSelect->pSrc->a;
137908 if( pSrc->tnum==pDest->tnum && pSrc->pSchema==pDest->pSchema ){
137918 if( pDest->nCol!=pSrc->nCol ){
137921 if( pDest->iPKey!=pSrc->iPKey ){
137924 if( (pDest->tabFlags & TF_Strict)!=0 && (pSrc->tabFlags & TF_Strict)==0 ){
137925 return 0; /* Cannot feed from a non-strict into a strict table */
137927 for(i=0; i<pDest->nCol; i++){
137928 Column *pDestCol = &pDest->aCol[i];
137929 Column *pSrcCol = &pSrc->aCol[i];
137931 if( (db->mDbFlags & DBFLAG_Vacuum)==0
137932 && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
137954 if( (pDestCol->colFlags & COLFLAG_GENERATED) !=
137955 (pSrcCol->colFlags & COLFLAG_GENERATED) ){
137956 return 0; /* Both columns have the same generated-column type */
137962 if( (pDestCol->colFlags & COLFLAG_GENERATED)!=0 ){
137965 sqlite3ColumnExpr(pDest, pDestCol), -1)!=0 ){
137966 testcase( pDestCol->colFlags & COLFLAG_VIRTUAL );
137967 testcase( pDestCol->colFlags & COLFLAG_STORED );
137972 if( pDestCol->affinity!=pSrcCol->affinity ){
137979 if( pDestCol->notNull && !pSrcCol->notNull ){
137983 if( (pDestCol->colFlags & COLFLAG_GENERATED)==0 && i>0 ){
137986 assert( pDestExpr==0 || pDestExpr->op==TK_SPAN );
137988 assert( pSrcExpr==0 || pSrcExpr->op==TK_SPAN );
137991 || (pDestExpr!=0 && strcmp(pDestExpr->u.zToken,
137992 pSrcExpr->u.zToken)!=0)
137998 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
138002 for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
138008 if( pSrcIdx->tnum==pDestIdx->tnum && pSrc->pSchema==pDest->pSchema
138013 return 0; /* Corrupt schema - two indexes on the same btree */
138017 if( pDest->pCheck
138018 && (db->mDbFlags & DBFLAG_Vacuum)==0
138019 && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1)
138033 if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->u.tab.pFKey!=0 ){
138037 if( (db->flags & SQLITE_CountRows)!=0 ){
138048 iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
138051 iSrc = pParse->nTab++;
138052 iDest = pParse->nTab++;
138059 if( (db->mDbFlags & DBFLAG_Vacuum)==0 && (
138060 (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
138089 if( pDest->iPKey>=0 ){
138091 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
138099 }else if( pDest->pIndex==0 && !(db->mDbFlags & DBFLAG_VacuumInto) ){
138103 assert( (pDest->tabFlags & TF_Autoincrement)==0 );
138106 if( db->mDbFlags & DBFLAG_Vacuum ){
138113 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
138122 if( (db->mDbFlags & DBFLAG_Vacuum)==0 ){
138123 sqlite3VdbeChangeP4(v, -1, (char*)pDest, P4_TABLE);
138131 sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
138132 sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
138134 for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
138136 for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
138140 sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
138142 VdbeComment((v, "%s", pSrcIdx->zName));
138143 sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
138146 VdbeComment((v, "%s", pDestIdx->zName));
138148 if( db->mDbFlags & DBFLAG_Vacuum ){
138153 ** order. In this case, instead of seeking within the b-tree as part
138154 ** of every OP_IdxInsert opcode, an OP_SeekEnd is added before the
138155 ** OP_IdxInsert to seek to the point within the b-tree where each key
138163 for(i=0; i<pSrcIdx->nColumn; i++){
138164 const char *zColl = pSrcIdx->azColl[i];
138167 if( i==pSrcIdx->nColumn ){
138172 }else if( !HasRowid(pSrc) && pDestIdx->idxType==SQLITE_IDXTYPE_PRIMARYKEY ){
138177 if( (db->mDbFlags & DBFLAG_Vacuum)==0
138229 ** codes. Also write an error message into memory obtained from
138253 sqlite3_mutex_enter(db->mutex);
138260 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
138266 /* this happens for a comment or white-space */
138279 && db->flags&SQLITE_NullCallback)) ){
138306 /* EVIDENCE-OF: R-38229-40159 If the callback function to
138307 ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
138345 assert( (rc&db->errMask)==rc );
138346 sqlite3_mutex_leave(db->mutex);
138385 ** an SQLite instance. Shared libraries that intend to be loaded
138759 ** (part of the main SQLite library - not an extension) so that
138766 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
138768 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
138770 #define sqlite3_bind_blob sqlite3_api->bind_blob
138771 #define sqlite3_bind_double sqlite3_api->bind_double
138772 #define sqlite3_bind_int sqlite3_api->bind_int
138773 #define sqlite3_bind_int64 sqlite3_api->bind_int64
138774 #define sqlite3_bind_null sqlite3_api->bind_null
138775 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
138776 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
138777 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
138778 #define sqlite3_bind_text sqlite3_api->bind_text
138779 #define sqlite3_bind_text16 sqlite3_api->bind_text16
138780 #define sqlite3_bind_value sqlite3_api->bind_value
138781 #define sqlite3_busy_handler sqlite3_api->busy_handler
138782 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
138783 #define sqlite3_changes sqlite3_api->changes
138784 #define sqlite3_close sqlite3_api->close
138785 #define sqlite3_collation_needed sqlite3_api->collation_needed
138786 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
138787 #define sqlite3_column_blob sqlite3_api->column_blob
138788 #define sqlite3_column_bytes sqlite3_api->column_bytes
138789 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
138790 #define sqlite3_column_count sqlite3_api->column_count
138791 #define sqlite3_column_database_name sqlite3_api->column_database_name
138792 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
138793 #define sqlite3_column_decltype sqlite3_api->column_decltype
138794 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
138795 #define sqlite3_column_double sqlite3_api->column_double
138796 #define sqlite3_column_int sqlite3_api->column_int
138797 #define sqlite3_column_int64 sqlite3_api->column_int64
138798 #define sqlite3_column_name sqlite3_api->column_name
138799 #define sqlite3_column_name16 sqlite3_api->column_name16
138800 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
138801 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
138802 #define sqlite3_column_table_name sqlite3_api->column_table_name
138803 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
138804 #define sqlite3_column_text sqlite3_api->column_text
138805 #define sqlite3_column_text16 sqlite3_api->column_text16
138806 #define sqlite3_column_type sqlite3_api->column_type
138807 #define sqlite3_column_value sqlite3_api->column_value
138808 #define sqlite3_commit_hook sqlite3_api->commit_hook
138809 #define sqlite3_complete sqlite3_api->complete
138810 #define sqlite3_complete16 sqlite3_api->complete16
138811 #define sqlite3_create_collation sqlite3_api->create_collation
138812 #define sqlite3_create_collation16 sqlite3_api->create_collation16
138813 #define sqlite3_create_function sqlite3_api->create_function
138814 #define sqlite3_create_function16 sqlite3_api->create_function16
138815 #define sqlite3_create_module sqlite3_api->create_module
138816 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
138817 #define sqlite3_data_count sqlite3_api->data_count
138818 #define sqlite3_db_handle sqlite3_api->db_handle
138819 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
138820 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
138821 #define sqlite3_errcode sqlite3_api->errcode
138822 #define sqlite3_errmsg sqlite3_api->errmsg
138823 #define sqlite3_errmsg16 sqlite3_api->errmsg16
138824 #define sqlite3_exec sqlite3_api->exec
138826 #define sqlite3_expired sqlite3_api->expired
138828 #define sqlite3_finalize sqlite3_api->finalize
138829 #define sqlite3_free sqlite3_api->free
138830 #define sqlite3_free_table sqlite3_api->free_table
138831 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
138832 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
138833 #define sqlite3_get_table sqlite3_api->get_table
138835 #define sqlite3_global_recover sqlite3_api->global_recover
138837 #define sqlite3_interrupt sqlite3_api->interruptx
138838 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
138839 #define sqlite3_libversion sqlite3_api->libversion
138840 #define sqlite3_libversion_number sqlite3_api->libversion_number
138841 #define sqlite3_malloc sqlite3_api->malloc
138842 #define sqlite3_mprintf sqlite3_api->mprintf
138843 #define sqlite3_open sqlite3_api->open
138844 #define sqlite3_open16 sqlite3_api->open16
138845 #define sqlite3_prepare sqlite3_api->prepare
138846 #define sqlite3_prepare16 sqlite3_api->prepare16
138847 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
138848 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
138849 #define sqlite3_profile sqlite3_api->profile
138850 #define sqlite3_progress_handler sqlite3_api->progress_handler
138851 #define sqlite3_realloc sqlite3_api->realloc
138852 #define sqlite3_reset sqlite3_api->reset
138853 #define sqlite3_result_blob sqlite3_api->result_blob
138854 #define sqlite3_result_double sqlite3_api->result_double
138855 #define sqlite3_result_error sqlite3_api->result_error
138856 #define sqlite3_result_error16 sqlite3_api->result_error16
138857 #define sqlite3_result_int sqlite3_api->result_int
138858 #define sqlite3_result_int64 sqlite3_api->result_int64
138859 #define sqlite3_result_null sqlite3_api->result_null
138860 #define sqlite3_result_text sqlite3_api->result_text
138861 #define sqlite3_result_text16 sqlite3_api->result_text16
138862 #define sqlite3_result_text16be sqlite3_api->result_text16be
138863 #define sqlite3_result_text16le sqlite3_api->result_text16le
138864 #define sqlite3_result_value sqlite3_api->result_value
138865 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
138866 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
138867 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
138868 #define sqlite3_snprintf sqlite3_api->xsnprintf
138869 #define sqlite3_step sqlite3_api->step
138870 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
138871 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
138872 #define sqlite3_total_changes sqlite3_api->total_changes
138873 #define sqlite3_trace sqlite3_api->trace
138875 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
138877 #define sqlite3_update_hook sqlite3_api->update_hook
138878 #define sqlite3_user_data sqlite3_api->user_data
138879 #define sqlite3_value_blob sqlite3_api->value_blob
138880 #define sqlite3_value_bytes sqlite3_api->value_bytes
138881 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
138882 #define sqlite3_value_double sqlite3_api->value_double
138883 #define sqlite3_value_int sqlite3_api->value_int
138884 #define sqlite3_value_int64 sqlite3_api->value_int64
138885 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
138886 #define sqlite3_value_text sqlite3_api->value_text
138887 #define sqlite3_value_text16 sqlite3_api->value_text16
138888 #define sqlite3_value_text16be sqlite3_api->value_text16be
138889 #define sqlite3_value_text16le sqlite3_api->value_text16le
138890 #define sqlite3_value_type sqlite3_api->value_type
138891 #define sqlite3_vmprintf sqlite3_api->vmprintf
138892 #define sqlite3_vsnprintf sqlite3_api->xvsnprintf
138893 #define sqlite3_overload_function sqlite3_api->overload_function
138894 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
138895 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
138896 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
138897 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
138898 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
138899 #define sqlite3_blob_close sqlite3_api->blob_close
138900 #define sqlite3_blob_open sqlite3_api->blob_open
138901 #define sqlite3_blob_read sqlite3_api->blob_read
138902 #define sqlite3_blob_write sqlite3_api->blob_write
138903 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
138904 #define sqlite3_file_control sqlite3_api->file_control
138905 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
138906 #define sqlite3_memory_used sqlite3_api->memory_used
138907 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
138908 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
138909 #define sqlite3_mutex_free sqlite3_api->mutex_free
138910 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
138911 #define sqlite3_mutex_try sqlite3_api->mutex_try
138912 #define sqlite3_open_v2 sqlite3_api->open_v2
138913 #define sqlite3_release_memory sqlite3_api->release_memory
138914 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
138915 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
138916 #define sqlite3_sleep sqlite3_api->sleep
138917 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
138918 #define sqlite3_vfs_find sqlite3_api->vfs_find
138919 #define sqlite3_vfs_register sqlite3_api->vfs_register
138920 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
138921 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
138922 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
138923 #define sqlite3_result_error_code sqlite3_api->result_error_code
138924 #define sqlite3_test_control sqlite3_api->test_control
138925 #define sqlite3_randomness sqlite3_api->randomness
138926 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
138927 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
138928 #define sqlite3_limit sqlite3_api->limit
138929 #define sqlite3_next_stmt sqlite3_api->next_stmt
138930 #define sqlite3_sql sqlite3_api->sql
138931 #define sqlite3_status sqlite3_api->status
138932 #define sqlite3_backup_finish sqlite3_api->backup_finish
138933 #define sqlite3_backup_init sqlite3_api->backup_init
138934 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
138935 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
138936 #define sqlite3_backup_step sqlite3_api->backup_step
138937 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
138938 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
138939 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
138940 #define sqlite3_db_config sqlite3_api->db_config
138941 #define sqlite3_db_mutex sqlite3_api->db_mutex
138942 #define sqlite3_db_status sqlite3_api->db_status
138943 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
138944 #define sqlite3_log sqlite3_api->log
138945 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
138946 #define sqlite3_sourceid sqlite3_api->sourceid
138947 #define sqlite3_stmt_status sqlite3_api->stmt_status
138948 #define sqlite3_strnicmp sqlite3_api->strnicmp
138949 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
138950 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
138951 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
138952 #define sqlite3_wal_hook sqlite3_api->wal_hook
138953 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
138954 #define sqlite3_vtab_config sqlite3_api->vtab_config
138955 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
138957 #define sqlite3_close_v2 sqlite3_api->close_v2
138958 #define sqlite3_db_filename sqlite3_api->db_filename
138959 #define sqlite3_db_readonly sqlite3_api->db_readonly
138960 #define sqlite3_db_release_memory sqlite3_api->db_release_memory
138961 #define sqlite3_errstr sqlite3_api->errstr
138962 #define sqlite3_stmt_busy sqlite3_api->stmt_busy
138963 #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
138964 #define sqlite3_stricmp sqlite3_api->stricmp
138965 #define sqlite3_uri_boolean sqlite3_api->uri_boolean
138966 #define sqlite3_uri_int64 sqlite3_api->uri_int64
138967 #define sqlite3_uri_parameter sqlite3_api->uri_parameter
138968 #define sqlite3_uri_vsnprintf sqlite3_api->xvsnprintf
138969 #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
138971 #define sqlite3_auto_extension sqlite3_api->auto_extension
138972 #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
138973 #define sqlite3_bind_text64 sqlite3_api->bind_text64
138974 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
138975 #define sqlite3_load_extension sqlite3_api->load_extension
138976 #define sqlite3_malloc64 sqlite3_api->malloc64
138977 #define sqlite3_msize sqlite3_api->msize
138978 #define sqlite3_realloc64 sqlite3_api->realloc64
138979 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
138980 #define sqlite3_result_blob64 sqlite3_api->result_blob64
138981 #define sqlite3_result_text64 sqlite3_api->result_text64
138982 #define sqlite3_strglob sqlite3_api->strglob
138984 #define sqlite3_value_dup sqlite3_api->value_dup
138985 #define sqlite3_value_free sqlite3_api->value_free
138986 #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
138987 #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
138989 #define sqlite3_value_subtype sqlite3_api->value_subtype
138990 #define sqlite3_result_subtype sqlite3_api->result_subtype
138992 #define sqlite3_status64 sqlite3_api->status64
138993 #define sqlite3_strlike sqlite3_api->strlike
138994 #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
138996 #define sqlite3_system_errno sqlite3_api->system_errno
138998 #define sqlite3_trace_v2 sqlite3_api->trace_v2
138999 #define sqlite3_expanded_sql sqlite3_api->expanded_sql
139001 #define sqlite3_set_last_insert_rowid sqlite3_api->set_last_insert_rowid
139003 #define sqlite3_prepare_v3 sqlite3_api->prepare_v3
139004 #define sqlite3_prepare16_v3 sqlite3_api->prepare16_v3
139005 #define sqlite3_bind_pointer sqlite3_api->bind_pointer
139006 #define sqlite3_result_pointer sqlite3_api->result_pointer
139007 #define sqlite3_value_pointer sqlite3_api->value_pointer
139009 #define sqlite3_vtab_nochange sqlite3_api->vtab_nochange
139010 #define sqlite3_value_nochange sqlite3_api->value_nochange
139011 #define sqlite3_vtab_collation sqlite3_api->vtab_collation
139013 #define sqlite3_keyword_count sqlite3_api->keyword_count
139014 #define sqlite3_keyword_name sqlite3_api->keyword_name
139015 #define sqlite3_keyword_check sqlite3_api->keyword_check
139016 #define sqlite3_str_new sqlite3_api->str_new
139017 #define sqlite3_str_finish sqlite3_api->str_finish
139018 #define sqlite3_str_appendf sqlite3_api->str_appendf
139019 #define sqlite3_str_vappendf sqlite3_api->str_vappendf
139020 #define sqlite3_str_append sqlite3_api->str_append
139021 #define sqlite3_str_appendall sqlite3_api->str_appendall
139022 #define sqlite3_str_appendchar sqlite3_api->str_appendchar
139023 #define sqlite3_str_reset sqlite3_api->str_reset
139024 #define sqlite3_str_errcode sqlite3_api->str_errcode
139025 #define sqlite3_str_length sqlite3_api->str_length
139026 #define sqlite3_str_value sqlite3_api->str_value
139028 #define sqlite3_create_window_function sqlite3_api->create_window_function
139030 #define sqlite3_normalized_sql sqlite3_api->normalized_sql
139032 #define sqlite3_stmt_isexplain sqlite3_api->stmt_isexplain
139033 #define sqlite3_value_frombind sqlite3_api->value_frombind
139035 #define sqlite3_drop_modules sqlite3_api->drop_modules
139037 #define sqlite3_hard_heap_limit64 sqlite3_api->hard_heap_limit64
139038 #define sqlite3_uri_key sqlite3_api->uri_key
139039 #define sqlite3_filename_database sqlite3_api->filename_database
139040 #define sqlite3_filename_journal sqlite3_api->filename_journal
139041 #define sqlite3_filename_wal sqlite3_api->filename_wal
139043 #define sqlite3_create_filename sqlite3_api->create_filename
139044 #define sqlite3_free_filename sqlite3_api->free_filename
139045 #define sqlite3_database_file_object sqlite3_api->database_file_object
139047 #define sqlite3_txn_state sqlite3_api->txn_state
139049 #define sqlite3_changes64 sqlite3_api->changes64
139050 #define sqlite3_total_changes64 sqlite3_api->total_changes64
139052 #define sqlite3_autovacuum_pages sqlite3_api->autovacuum_pages
139054 #define sqlite3_error_offset sqlite3_api->error_offset
139055 #define sqlite3_vtab_rhs_value sqlite3_api->vtab_rhs_value
139056 #define sqlite3_vtab_distinct sqlite3_api->vtab_distinct
139057 #define sqlite3_vtab_in sqlite3_api->vtab_in
139058 #define sqlite3_vtab_in_first sqlite3_api->vtab_in_first
139059 #define sqlite3_vtab_in_next sqlite3_api->vtab_in_next
139062 #define sqlite3_deserialize sqlite3_api->deserialize
139063 #define sqlite3_serialize sqlite3_api->serialize
139065 #define sqlite3_db_name sqlite3_api->db_name
139067 #define sqlite3_value_encoding sqlite3_api->value_encoding
139069 #define sqlite3_is_interrupted sqlite3_api->is_interrupted
139071 #define sqlite3_stmt_explain sqlite3_api->stmt_explain
139073 #define sqlite3_get_clientdata sqlite3_api->get_clientdata
139074 #define sqlite3_set_clientdata sqlite3_api->set_clientdata
139076 #define sqlite3_setlk_timeout sqlite3_api->setlk_timeout
139089 # define SQLITE_EXTENSION_INIT1 /*no-op*/
139091 # define SQLITE_EXTENSION_INIT3 /*no-op*/
139612 ** Attempt to load an SQLite extension library contained in the file
139619 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
139629 sqlite3_vfs *pVfs = db->pVfs;
139661 if( (db->flags & SQLITE_LoadExtension)==0 ){
139670 /* tag-20210611-1. Some dlopen() implementations will segfault if given
139671 ** an oversize filename. Most filesystems have a pathname limit of 4K,
139675 ** Later (2023-03-25): Save an extra 6 bytes for the filename suffix.
139681 ** running application, by passing in an empty filename. */
139700 ** construct an entry point name "sqlite3_X_init" where the X is
139718 for(iFile=ncFile-1; iFile>=0 && !DirSep(zFile[iFile]); iFile--){}
139738 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
139757 /* Append the new shared library handle to the db->aExtension array. */
139758 aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
139762 if( db->nExtension>0 ){
139763 memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
139765 sqlite3DbFree(db, db->aExtension);
139766 db->aExtension = aHandle;
139768 db->aExtension[db->nExtension++] = handle;
139779 sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
139791 sqlite3_mutex_enter(db->mutex);
139794 sqlite3_mutex_leave(db->mutex);
139804 assert( sqlite3_mutex_held(db->mutex) );
139805 for(i=0; i<db->nExtension; i++){
139806 sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
139808 sqlite3DbFree(db, db->aExtension);
139819 sqlite3_mutex_enter(db->mutex);
139821 db->flags |= SQLITE_LoadExtension|SQLITE_LoadExtFunc;
139823 db->flags &= ~(u64)(SQLITE_LoadExtension|SQLITE_LoadExtFunc);
139825 sqlite3_mutex_leave(db->mutex);
139846 ** we have to locate the state vector at run-time. In the more common
139909 ** routine is a no-op.
139927 for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
139929 wsdAutoext.nExt--;
139962 ** If anything goes wrong, set an error in the database connection.
140029 ** The "pragma.h" include file is an automatically generated file that
140095 #define PragFlg_ReadOnly 0x08 /* Read-only HEADER_VALUE */
140099 #define PragFlg_SchemaReq 0x80 /* Schema required - "main" is default */
140101 /* Names of columns for pragmas that return multi-column result
140102 ** or that return single-column results where the name of the
140169 /* Definitions of all built-in pragmas */
140703 ** will be run with an analysis_limit set to the lessor of the value of
140704 ** the following macro or to the actual analysis_limit if it is non-zero,
140707 ** The value of 2000 is chosen empirically so that the worst-case run-time
140709 ** of test databases on a RaspberryPI-4 compiled using -Os and without
140710 ** -DSQLITE_DEBUG. Of course, your mileage may vary. For the purpose of
140711 ** this paragraph, "worst-case" means that ANALYZE ends up being
140718 ** optimize on a PI-4 is more like 1 millisecond or less with the 0x10000
140721 ** An analysis limit of 2000 is almost always sufficient for the query
140722 ** planner to fully characterize an index. The additional accuracy from
140731 ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
140788 ** Interpret the given string as an auto-vacuum mode value.
140806 ** backed temporary databases, 2 for the Red-Black tree in memory database
140807 ** and 0 to use the compile-time default.
140811 return z[0] - '0';
140828 sqlite3 *db = pParse->db;
140829 if( db->aDb[1].pBt!=0 ){
140830 if( !db->autoCommit
140831 || sqlite3BtreeTxnState(db->aDb[1].pBt)!=SQLITE_TXN_NONE
140837 sqlite3BtreeClose(db->aDb[1].pBt);
140838 db->aDb[1].pBt = 0;
140853 sqlite3 *db = pParse->db;
140854 if( db->temp_store==ts ) return SQLITE_OK;
140858 db->temp_store = (u8)ts;
140870 u8 n = pPragma->nPragCName;
140873 sqlite3VdbeSetColName(v, 0, COLNAME_NAME, pPragma->zName, SQLITE_STATIC);
140876 for(i=0, j=pPragma->iPragCName; i<n; i++, j++){
140910 if( db->autoCommit ){
140911 Db *pDb = db->aDb;
140912 int n = db->nDb;
140918 assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
140919 while( (n--) > 0 ){
140920 if( pDb->pBt ){
140921 sqlite3BtreeSetPagerFlags(pDb->pBt,
140922 pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
140929 # define setAllPagerFlags(X) /* no-op */
140934 ** Return a human-readable name for a constraint resolution action.
140955 ** journal-mode name.
140982 upr = ArraySize(aPragmaName)-1;
140988 upr = mid - 1;
141003 int isBuiltin, /* True if this is a built-in function */
141014 for(; p; p=p->pNext){
141023 if( p->xSFunc==0 ) continue;
141024 if( (p->funcFlags & SQLITE_FUNC_INTERNAL)!=0
141029 if( p->xValue!=0 ){
141031 }else if( p->xFinalize!=0 ){
141037 p->zName, isBuiltin,
141038 zType, azEnc[p->funcFlags&SQLITE_FUNC_ENCMASK],
141039 p->nArg,
141040 (p->funcFlags & mask) ^ SQLITE_INNOCUOUS
141049 ** Generate code to output a single-column result row with a value of the
141082 int minusFlag /* True if a '-' sign preceded <value> */
141084 char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
141085 char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
141091 sqlite3 *db = pParse->db; /* The database connection */
141098 pParse->nMem = 2;
141104 pDb = &db->aDb[iDb];
141116 zRight = sqlite3MPrintf(db, "-%T", pValue);
141122 zDb = pId2->n>0 ? pDb->zDbSName : 0;
141127 /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
141129 ** handled the pragma and generate a no-op prepared statement.
141131 ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
141132 ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
141136 ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
141137 ** file control is an array of pointers to strings (char**) in which the
141146 db->busyHandler.nBusy = 0;
141160 pParse->nErr++;
141161 pParse->rc = rc;
141168 /* IMP: R-43042-22504 No error messages are generated if an
141174 if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){
141179 if( (pPragma->mPragFlg & PragFlg_NoColumns)==0
141180 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0)
141186 switch( pPragma->ePragTyp ){
141221 pParse->nMem += 2;
141233 pDb->pSchema->cache_size = size;
141234 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
141251 Btree *pBt = pDb->pBt;
141257 /* Malloc may fail when setting the page-size, as there is an internal
141260 db->nextPagesize = sqlite3Atoi(zRight);
141261 if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,0,0) ){
141277 Btree *pBt = pDb->pBt;
141278 int b = -1;
141287 if( pId2->n==0 && b>=0 ){
141289 for(ii=0; ii<db->nDb; ii++){
141290 sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
141308 ** change. The only purpose is to provide an easy way to test
141319 iReg = ++pParse->nMem;
141343 if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
141346 ** the locking-mode of the main database).
141348 eMode = db->dfltLockMode;
141351 if( pId2->n==0 ){
141353 ** of the PRAGMA command. In this case the locking-mode must be
141361 assert(pDb==&db->aDb[0]);
141362 for(ii=2; ii<db->nDb; ii++){
141363 pPager = sqlite3BtreePager(db->aDb[ii].pBt);
141366 db->dfltLockMode = (u8)eMode;
141368 pPager = sqlite3BtreePager(pDb->pBt);
141405 if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){
141406 /* Do not allow journal-mode "OFF" in defensive since the database
141411 if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
141414 pId2->n = 1;
141416 for(ii=db->nDb-1; ii>=0; ii--){
141417 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
141433 Pager *pPager = sqlite3BtreePager(pDb->pBt);
141434 i64 iLimit = -2;
141437 if( iLimit<-1 ) iLimit = -1;
141450 ** Get or set the value of the database 'auto-vacuum' parameter.
141455 Btree *pBt = pDb->pBt;
141462 db->nextAutovac = (u8)eAuto;
141464 ** incr-vacuum flags. This is required in case this connection
141466 ** as an auto-vacuum capable db.
141473 ** that this really is an auto-vacuum capable database.
141492 aOp[4].p3 = eAuto - 1;
141515 sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
141531 ** number of pages is adjusted so that the cache uses -N kibibytes
141537 returnSingleInt(v, pDb->pSchema->cache_size);
141540 pDb->pSchema->cache_size = size;
141541 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
141558 ** number of pages is adjusted so that the cache uses -N kibibytes
141572 (db->flags & SQLITE_CacheSpill)==0 ? 0 :
141573 sqlite3BtreeSetSpillSize(pDb->pBt,0));
141577 sqlite3BtreeSetSpillSize(pDb->pBt, size);
141580 db->flags |= SQLITE_CacheSpill;
141582 db->flags &= ~(u64)SQLITE_CacheSpill;
141611 if( pId2->n==0 ) db->szMmap = sz;
141612 for(ii=db->nDb-1; ii>=0; ii--){
141613 if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
141614 sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
141618 sz = -1;
141627 pParse->nErr++;
141628 pParse->rc = rc;
141641 ** Note that it is possible for the library compile-time options to
141646 returnSingleInt(v, db->temp_store);
141671 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
141679 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
141680 || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
141706 ** process. Database file specified with an absolute path are not impacted
141718 rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
141749 Pager *pPager = sqlite3BtreePager(pDb->pBt);
141756 Pager *pPager = sqlite3BtreePager(pDb->pBt);
141786 returnSingleInt(v, pDb->safety_level-1);
141788 if( !db->autoCommit ){
141794 pDb->safety_level = iLevel;
141795 pDb->bSyncSet = 1;
141807 returnSingleInt(v, (db->flags & pPragma->iArg)!=0 );
141809 u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */
141810 if( db->autoCommit==0 ){
141812 ** in auto-commit mode. */
141818 || (db->flags & SQLITE_Defensive)==0
141820 db->flags |= mask;
141823 db->flags &= ~mask;
141825 db->nDeferredImmCons = 0;
141826 db->nDeferredCons = 0;
141831 /* IMP: R-60817-01178 If the argument is "RESET" then schema
141838 /* Many of the flag-pragmas modify the code generated by the SQL
141839 ** compiler (eg. count_changes). So add an opcode to expire all
141861 ** pk: Non-zero for PK fields.
141872 pParse->nMem = 7;
141874 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
141877 if( pCol->colFlags & COLFLAG_NOINSERT ){
141878 if( pPragma->iArg==0 ){
141882 if( pCol->colFlags & COLFLAG_VIRTUAL ){
141884 }else if( pCol->colFlags & COLFLAG_STORED ){
141886 }else{ assert( pCol->colFlags & COLFLAG_HIDDEN );
141890 if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
141895 for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
141898 assert( pColExpr==0 || pColExpr->op==TK_SPAN || isHidden>=2 );
141901 sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi",
141902 i-nHidden,
141903 pCol->zCnName,
141905 pCol->notNull ? 1 : 0,
141906 (isHidden>=2 || pColExpr==0) ? 0 : pColExpr->u.zToken,
141929 pParse->nMem = 6;
141931 for(ii=0; ii<db->nDb; ii++){
141935 if( zDb && sqlite3_stricmp(zDb, db->aDb[ii].zDbSName)!=0 ) continue;
141942 pHash = &db->aDb[ii].pSchema->tblHash;
141944 while( initNCol-- ){
141949 if( pTab->nCol==0 ){
141950 char *zSql = sqlite3MPrintf(db, "SELECT*FROM\"%w\"", pTab->zName);
141953 (void)sqlite3_prepare_v3(db, zSql, -1, SQLITE_PREPARE_DONT_LOG,
141958 if( db->mallocFailed ){
141959 sqlite3ErrorMsg(db->pParse, "out of memory");
141960 db->pParse->rc = SQLITE_NOMEM_BKPT;
141962 pHash = &db->aDb[ii].pSchema->tblHash;
141971 if( zRight && sqlite3_stricmp(zRight, pTab->zName)!=0 ) continue;
141976 }else if( pTab->tabFlags & TF_Shadow ){
141982 db->aDb[ii].zDbSName,
141983 sqlite3PreferredTableName(pTab->zName),
141985 pTab->nCol,
141986 (pTab->tabFlags & TF_WithoutRowid)!=0,
141987 (pTab->tabFlags & TF_Strict)!=0
141998 pParse->nMem = 5;
142000 for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
142003 sqlite3PreferredTableName(pTab->zName),
142005 pTab->szTabRow,
142006 pTab->nRowLogEst,
142007 pTab->tabFlags);
142008 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
142010 pIdx->zName,
142011 pIdx->szIdxRow,
142012 pIdx->aiRowLogEst[0],
142013 pIdx->hasStat1);
142035 int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
142038 if( pPragma->iArg ){
142040 mx = pIdx->nColumn;
142041 pParse->nMem = 6;
142044 mx = pIdx->nKeyCol;
142045 pParse->nMem = 3;
142047 pTab = pIdx->pTable;
142049 assert( pParse->nMem<=pPragma->nPragCName );
142051 i16 cnum = pIdx->aiColumn[i];
142053 cnum<0 ? 0 : pTab->aCol[cnum].zCnName);
142054 if( pPragma->iArg ){
142056 pIdx->aSortOrder[i],
142057 pIdx->azColl[i],
142058 i<pIdx->nKeyCol);
142060 sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
142072 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
142073 pParse->nMem = 5;
142075 for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
142079 pIdx->zName,
142081 azOrigin[pIdx->idxType],
142082 pIdx->pPartIdxWhere!=0);
142090 pParse->nMem = 3;
142091 for(i=0; i<db->nDb; i++){
142092 if( db->aDb[i].pBt==0 ) continue;
142093 assert( db->aDb[i].zDbSName!=0 );
142096 db->aDb[i].zDbSName,
142097 sqlite3BtreeGetFilename(db->aDb[i].pBt));
142105 pParse->nMem = 2;
142106 for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
142108 sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
142118 int showInternFunc = (db->mDbFlags & DBFLAG_InternalFunc)!=0;
142119 pParse->nMem = 6;
142121 for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){
142122 assert( p->funcFlags & SQLITE_FUNC_BUILTIN );
142126 for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){
142128 assert( (p->funcFlags & SQLITE_FUNC_BUILTIN)==0 );
142137 pParse->nMem = 1;
142138 for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){
142140 sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName);
142163 pFK = pTab->u.tab.pFKey;
142165 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
142167 pParse->nMem = 8;
142171 for(j=0; j<pFK->nCol; j++){
142175 pFK->zTo,
142176 pTab->aCol[pFK->aCol[j].iFrom].zCnName,
142177 pFK->aCol[j].zCol,
142178 actionName(pFK->aAction[1]), /* ON UPDATE */
142179 actionName(pFK->aAction[0]), /* ON DELETE */
142183 pFK = pFK->pNextFrom;
142208 regResult = pParse->nMem+1;
142209 pParse->nMem += 4;
142210 regRow = ++pParse->nMem;
142211 k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
142220 if( pTab==0 || !IsOrdinaryTable(pTab) || pTab->u.tab.pFKey==0 ) continue;
142221 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
142222 zDb = db->aDb[iDb].zDbSName;
142224 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
142225 sqlite3TouchRegister(pParse, pTab->nCol+regRow);
142227 sqlite3VdbeLoadString(v, regResult, pTab->zName);
142229 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
142230 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
142233 sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
142239 sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
142247 assert( pParse->nErr>0 || pFK==0 );
142249 if( pParse->nTab<i ) pParse->nTab = i;
142252 for(i=1, pFK=pTab->u.tab.pFKey; pFK; i++, pFK=pFK->pNextFrom){
142253 pParent = sqlite3FindTable(db, pFK->zTo, zDb);
142258 assert( x==0 || db->mallocFailed );
142264 ** row cannot cause an FK violation. Jump directly to addrOk in
142266 sqlite3TouchRegister(pParse, regRow + pFK->nCol);
142267 for(j=0; j<pFK->nCol; j++){
142268 int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom;
142276 sqlite3VdbeAddOp4(v, OP_Affinity, regRow, pFK->nCol, 0,
142277 sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
142278 sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regRow, pFK->nCol);
142284 assert( pFK->nCol==1 || db->mallocFailed );
142287 /* Generate code to report an FK violation to the caller. */
142293 sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1);
142332 ** without the overhead of cross-checking indexes. Quick_check
142360 ** to -1 here, to indicate that the VDBE should verify the integrity
142363 assert( iDb==0 || pId2->z );
142364 if( pId2->z==0 ) iDb = -1;
142367 pParse->nMem = 6;
142372 if( sqlite3GetInt32(pValue->z, &mxErr) ){
142378 iDb>=0 ? db->aDb[iDb].zDbSName : 0);
142381 sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */
142383 /* Do an integrity check on each database file */
142384 for(i=0; i<db->nDb; i++){
142394 pParse->okConstFactor = 0; /* tag-20230327-1 */
142396 /* Do an integrity check of the B-Tree
142402 pTbls = &db->aDb[i].pSchema->tblHash;
142405 Index *pIdx; /* An index on pTab */
142409 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
142421 if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum;
142422 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
142423 aRoot[++cnt] = pIdx->tnum;
142433 /* Do the b-tree integrity checks */
142438 sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName),
142456 for(pIdx=pTab->pIndex; ALWAYS(pIdx); pIdx=pIdx->pNext){
142461 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
142462 if( pIdx->pPartIdxWhere==0 ){
142465 sqlite3VdbeLoadString(v, 4, pIdx->zName);
142482 int r1 = -1;
142485 int mxCol; /* Maximum non-virtual column number */
142494 r2 = sqlite3GetTempRange(pParse, pPk->nKeyCol);
142495 sqlite3VdbeAddOp3(v, OP_Null, 1, r2, r2+pPk->nKeyCol-1);
142500 ** reg[8+i] counts the number of entries in the i-th index
142503 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
142506 assert( pParse->nMem>=8+j );
142511 /* Fetch the right-most column from the table. This will cause
142518 mxCol = -1;
142519 for(j=0; j<pTab->nCol; j++){
142520 if( (pTab->aCol[j].colFlags & COLFLAG_VIRTUAL)==0 ) mxCol++;
142522 if( mxCol==pTab->iPKey ) mxCol--;
142525 ** PK index column-count, so there is no need to account for them
142527 mxCol = sqlite3PrimaryKeyIndex(pTab)->nColumn-1;
142539 a1 = sqlite3VdbeAddOp4Int(v, OP_IdxGT, iDataCur, 0,r2,pPk->nKeyCol);
142544 pTab->zName);
142549 for(j=0; j<pPk->nKeyCol; j++){
142557 ** (2) Datatype must be exact for non-ANY columns in STRICT tables
142558 ** (3) Datatype for TEXT columns in non-STRICT tables must be
142560 ** (4) Datatype for numeric columns in non-STRICT tables must not
142563 bStrict = (pTab->tabFlags & TF_Strict)!=0;
142564 for(j=0; j<pTab->nCol; j++){
142566 Column *pCol = pTab->aCol + j; /* The column to be checked */
142567 int labelError; /* Jump here to report an error */
142572 if( j==pTab->iPKey ) continue;
142574 doTypeCheck = pCol->eCType>COLTYPE_ANY;
142576 doTypeCheck = pCol->affinity>SQLITE_AFF_BLOB;
142578 if( pCol->notNull==0 && !doTypeCheck ) continue;
142582 if( pCol->colFlags & COLFLAG_VIRTUAL ){
142584 p1 = -1;
142587 if( pCol->iDflt ){
142590 pCol->affinity, &pDfltValue);
142608 if( pCol->notNull ){
142627 zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
142628 pCol->zCnName);
142639 /* (2) Datatype must be exact for non-ANY columns in STRICT tables*/
142649 assert( pCol->eCType>=1 && pCol->eCType<=sizeof(aStdTypeMask) );
142650 sqlite3VdbeChangeP5(v, aStdTypeMask[pCol->eCType-1]);
142652 zErr = sqlite3MPrintf(db, "non-%s value in %s.%s",
142653 sqlite3StdType[pCol->eCType-1],
142654 pTab->zName, pTab->aCol[j].zCnName);
142656 }else if( !bStrict && pCol->affinity==SQLITE_AFF_TEXT ){
142657 /* (3) Datatype for TEXT columns in non-STRICT tables must be
142663 pTab->zName, pTab->aCol[j].zCnName);
142665 }else if( !bStrict && pCol->affinity>=SQLITE_AFF_NUMERIC ){
142666 /* (4) Datatype for numeric columns in non-STRICT tables must not
142675 sqlite3VdbeAddOp4Int(v, OP_IsType, -1, labelOk, 3, p4);
142679 pTab->zName, pTab->aCol[j].zCnName);
142687 if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
142688 ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0);
142689 if( db->mallocFailed==0 ){
142694 pParse->iSelfTab = iDataCur + 1;
142695 for(k=pCheck->nExpr-1; k>0; k--){
142696 sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0);
142698 sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk,
142701 pParse->iSelfTab = 0;
142703 pTab->zName);
142712 for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
142721 /* Verify that an index entry exists for the current table row */
142723 pIdx->nColumn); VdbeCoverage(v);
142728 jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
142733 /* The OP_IdxRowid opcode is an optimized version of OP_Column
142740 jmp7 = sqlite3VdbeAddOp3(v, OP_Eq, 3, 0, r1+pIdx->nColumn-1);
142743 "rowid not at end-of-record for row ");
142746 sqlite3VdbeGoto(v, jmp5-1);
142750 /* Any indexed columns with non-BINARY collations must still hold
142753 for(kk=0; kk<pIdx->nKeyCol; kk++){
142754 if( pIdx->azColl[kk]==sqlite3StrBINARY ) continue;
142765 sqlite3VdbeGoto(v, jmp5-1);
142775 for(kk=0; kk<pIdx->nKeyCol; kk++){
142776 int iCol = pIdx->aiColumn[kk];
142777 assert( iCol!=XN_ROWID && iCol<pTab->nCol );
142778 if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
142786 pIdx->nKeyCol); VdbeCoverage(v);
142787 sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
142796 sqlite3VdbeJumpHere(v, loopTop-1);
142799 sqlite3ReleaseTempRange(pParse, r2, pPk->nKeyCol);
142814 if( pTab->nCol<=0 ){
142815 const char *zMod = pTab->u.vtab.azArg[0];
142816 if( sqlite3HashFind(&db->aModule, zMod)==0 ) continue;
142819 if( pTab->u.vtab.p==0 ) continue;
142820 pVTab = pTab->u.vtab.p->pVtab;
142822 if( NEVER(pVTab->pModule==0) ) continue;
142823 if( pVTab->pModule->iVersion<4 ) continue;
142824 if( pVTab->pModule->xIntegrity==0 ) continue;
142826 pTab->nTabRef++;
142850 aOp[0].p2 = 1-mxErr;
142856 sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2);
142865 ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
142870 ** The second form of this pragma is a no-op if the main database file
142873 ** is created. If an existing main database file is opened, then the
142891 { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
142892 { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
142893 { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
142896 { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
142906 returnSingleText(v, encnames[ENC(pParse->db)].zName);
142913 if( (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
142914 for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
142915 if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
142916 u8 enc = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
142922 if( !pEnc->zName ){
142947 ** the value of the schema-version and user-version, respectively. Both
142948 ** the schema-version and the user-version are 32-bit signed integers
142951 ** The schema-cookie is usually only manipulated internally by SQLite. It
142958 ** the schema-version is potentially dangerous and may lead to program
142961 ** The user-version is not used internally by SQLite. It may be used by
142965 int iCookie = pPragma->iArg; /* Which cookie to read or write */
142967 if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){
142982 if( iCookie==BTREE_SCHEMA_VERSION && (db->flags & SQLITE_Defensive)!=0 ){
142984 ** mode. Change the OP_SetCookie opcode into a no-op. */
143011 ** Return the names of all compile-time options used in this build,
143017 pParse->nMem = 1;
143034 int iBt = (pId2->z?iDb:SQLITE_MAX_DB);
143045 pParse->nMem = 3;
143064 db->xWalCallback==sqlite3WalDefaultHook ?
143065 SQLITE_PTR_TO_INT(db->pWalArg) : 0);
143073 ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
143104 ** 0x00010 Run all ANALYZE operations using an analysis_limit that
143106 ** SQLITE_DEFAULT_OPTIMIZE_LIMIT compile-time option.
143108 ** currently (2024-02-19) set to 2000, which is such that
143109 ** the worst case run-time for PRAGMA optimize on a 100MB
143111 ** a RaspberryPI-4 class machine. On by default.
143130 ** (2) The table is an ordinary table, not a virtual table or view.
143136 ** (4b) One or more indexes on the table lacks an entry
143138 ** (4c) The query planner used sqlite_stat1-style statistics for one
143143 ** (5a) One or more indexes on the table lacks an entry
143146 ** 10-fold. In other words, the current size of the table is
143161 Index *pIdx; /* An index of the table */
143178 }else if( db->nAnalysisLimit>0
143179 && db->nAnalysisLimit<SQLITE_DEFAULT_OPTIMIZE_LIMIT ){
143184 iTabCur = pParse->nTab++;
143185 for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){
143188 pSchema = db->aDb[iDb].pSchema;
143189 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
143196 if( 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7) ) continue;
143199 ** If any index is unanalyzed, then the threshold is -1 to
143202 szThreshold = pTab->nRowLogEst;
143204 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
143206 if( !pIdx->hasStat1 ){
143207 szThreshold = -1; /* Always analyze if any index lacks statistics */
143214 if( (pTab->tabFlags & TF_MaybeReanalyze)!=0 ){
143218 }else if( pTab->pIndex!=0 && szThreshold<0 ){
143241 szThreshold>=iRange ? szThreshold-iRange : -1,
143250 db->aDb[iDb].zDbSName, pTab->zName);
143264 ** the analysis_limit to avoid excess run-time in the worst case.
143266 if( !db->mallocFailed && nLimit>0 && nBtree>100 ){
143290 assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
143294 returnSingleInt(v, db->busyTimeout);
143302 ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
143304 ** specified and is a non-negative integer.
143305 ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
143307 ** sqlite3_soft_heap_limit64(-1) C-language function.
143314 returnSingleInt(v, sqlite3_soft_heap_limit64(-1));
143325 ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate
143326 ** the hard heap limit. This allows an application to set a heap limit
143327 ** constraint that cannot be relaxed by an untrusted SQL script.
143332 sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1);
143335 returnSingleInt(v, sqlite3_hard_heap_limit64(-1));
143354 returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
143368 && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK /* IMP: R-40975-20399 */
143371 db->nAnalysisLimit = (int)(N&0x7fffffff);
143373 returnSingleInt(v, db->nAnalysisLimit); /* IMP: R-57594-65522 */
143386 pParse->nMem = 2;
143387 for(i=0; i<db->nDb; i++){
143391 if( db->aDb[i].zDbSName==0 ) continue;
143392 pBt = db->aDb[i].pBt;
143395 }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0,
143399 sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState);
143407 if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
143416 /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only
143418 ** PragFlg_NoColumns1 flag is set and the caller specified an argument
143421 if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){
143431 ** Implementation of an eponymous virtual table that runs a pragma.
143472 for(i=0, j=pPragma->iPragCName; i<pPragma->nPragCName; i++, j++){
143477 sqlite3_str_appendf(&acc, "(\"%s\"", pPragma->zName);
143481 if( pPragma->mPragFlg & PragFlg_Result1 ){
143485 if( pPragma->mPragFlg & (PragFlg_SchemaOpt|PragFlg_SchemaReq) ){
143491 assert( strlen(zBuf) < sizeof(zBuf)-1 );
143499 pTab->pName = pPragma;
143500 pTab->db = db;
143501 pTab->iHidden = i;
143502 pTab->nHidden = j;
143534 pIdxInfo->estimatedCost = (double)1;
143535 if( pTab->nHidden==0 ){ return SQLITE_OK; }
143536 pConstraint = pIdxInfo->aConstraint;
143539 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
143540 if( pConstraint->iColumn < pTab->iHidden ) continue;
143541 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
143542 if( pConstraint->usable==0 ) return SQLITE_CONSTRAINT;
143543 j = pConstraint->iColumn - pTab->iHidden;
143548 pIdxInfo->estimatedCost = (double)2147483647;
143549 pIdxInfo->estimatedRows = 2147483647;
143552 j = seen[0]-1;
143553 pIdxInfo->aConstraintUsage[j].argvIndex = 1;
143554 pIdxInfo->aConstraintUsage[j].omit = 1;
143555 pIdxInfo->estimatedCost = (double)20;
143556 pIdxInfo->estimatedRows = 20;
143558 j = seen[1]-1;
143559 pIdxInfo->aConstraintUsage[j].argvIndex = 2;
143560 pIdxInfo->aConstraintUsage[j].omit = 1;
143571 pCsr->base.pVtab = pVtab;
143572 *ppCursor = &pCsr->base;
143579 sqlite3_finalize(pCsr->pPragma);
143580 pCsr->pPragma = 0;
143581 pCsr->iRowid = 0;
143582 for(i=0; i<ArraySize(pCsr->azArg); i++){
143583 sqlite3_free(pCsr->azArg[i]);
143584 pCsr->azArg[i] = 0;
143602 pCsr->iRowid++;
143603 assert( pCsr->pPragma );
143604 if( SQLITE_ROW!=sqlite3_step(pCsr->pPragma) ){
143605 rc = sqlite3_finalize(pCsr->pPragma);
143606 pCsr->pPragma = 0;
143621 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
143630 j = (pTab->pName->mPragFlg & PragFlg_Result1)!=0 ? 0 : 1;
143633 assert( j<ArraySize(pCsr->azArg) );
143634 assert( pCsr->azArg[j]==0 );
143636 pCsr->azArg[j] = sqlite3_mprintf("%s", zText);
143637 if( pCsr->azArg[j]==0 ){
143642 sqlite3StrAccumInit(&acc, 0, 0, 0, pTab->db->aLimit[SQLITE_LIMIT_SQL_LENGTH]);
143644 if( pCsr->azArg[1] ){
143645 sqlite3_str_appendf(&acc, "%Q.", pCsr->azArg[1]);
143647 sqlite3_str_appendall(&acc, pTab->pName->zName);
143648 if( pCsr->azArg[0] ){
143649 sqlite3_str_appendf(&acc, "=%Q", pCsr->azArg[0]);
143653 rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pPragma, 0);
143656 pTab->base.zErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pTab->db));
143667 return (pCsr->pPragma==0);
143679 PragmaVtab *pTab = (PragmaVtab*)(pVtabCursor->pVtab);
143680 if( i<pTab->iHidden ){
143681 sqlite3_result_value(ctx, sqlite3_column_value(pCsr->pPragma, i));
143683 sqlite3_result_text(ctx, pCsr->azArg[i-pTab->iHidden],-1,SQLITE_TRANSIENT);
143693 *p = pCsr->iRowid;
143700 0, /* xCreate - create a table */
143701 pragmaVtabConnect, /* xConnect - connect to an existing table */
143702 pragmaVtabBestIndex, /* xBestIndex - Determine search strategy */
143703 pragmaVtabDisconnect, /* xDisconnect - Disconnect from a table */
143704 0, /* xDestroy - Drop a table */
143705 pragmaVtabOpen, /* xOpen - open a cursor */
143706 pragmaVtabClose, /* xClose - close a cursor */
143707 pragmaVtabFilter, /* xFilter - configure scan constraints */
143708 pragmaVtabNext, /* xNext - advance a cursor */
143710 pragmaVtabColumn, /* xColumn - read data */
143711 pragmaVtabRowid, /* xRowid - read data */
143712 0, /* xUpdate - write data */
143713 0, /* xBegin - begin transaction */
143714 0, /* xSync - sync transaction */
143715 0, /* xCommit - commit transaction */
143716 0, /* xRollback - rollback transaction */
143717 0, /* xFindFunction - function overloading */
143718 0, /* xRename - rename the table */
143728 ** then register an eponymous virtual table for that pragma and return
143736 if( (pName->mPragFlg & (PragFlg_Result0|PragFlg_Result1))==0 ) return 0;
143737 assert( sqlite3HashFind(&db->aModule, zName)==0 );
143765 ** Fill the InitData structure with an error message that indicates
143773 sqlite3 *db = pData->db;
143774 if( db->mallocFailed ){
143775 pData->rc = SQLITE_NOMEM_BKPT;
143776 }else if( pData->pzErrMsg[0]!=0 ){
143778 }else if( pData->mInitFlags & (INITFLAG_AlterMask) ){
143784 *pData->pzErrMsg = sqlite3MPrintf(db,
143786 azAlterType[(pData->mInitFlags&INITFLAG_AlterMask)-1],
143789 pData->rc = SQLITE_ERROR;
143790 }else if( db->flags & SQLITE_WriteSchema ){
143791 pData->rc = SQLITE_CORRUPT_BKPT;
143796 if( zExtra && zExtra[0] ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
143797 *pData->pzErrMsg = z;
143798 pData->rc = SQLITE_CORRUPT_BKPT;
143809 for(p=pIndex->pTable->pIndex; p; p=p->pNext){
143810 if( p->tnum==pIndex->tnum && p!=pIndex ) return 1;
143818 const char *zSql, /* UTF-8 encoded SQL statement. */
143836 ** argv[2] = associated table if an index or trigger
143843 sqlite3 *db = pData->db;
143844 int iDb = pData->iDb;
143848 assert( sqlite3_mutex_held(db->mutex) );
143849 db->mDbFlags |= DBFLAG_EncodingFixed;
143851 pData->nInitRow++;
143852 if( db->mallocFailed ){
143857 assert( iDb>=0 && iDb<db->nDb );
143864 ** But because db->init.busy is set to 1, no VDBE code is generated
143874 u8 saved_iDb = db->init.iDb;
143878 assert( db->init.busy );
143879 db->init.iDb = iDb;
143880 if( sqlite3GetUInt32(argv[3], &db->init.newTnum)==0
143881 || (db->init.newTnum>pData->mxPage && pData->mxPage>0)
143887 db->init.orphanTrigger = 0;
143888 db->init.azInit = (const char**)argv;
143890 TESTONLY(rcp = ) sqlite3Prepare(db, argv[4], -1, 0, 0, &pStmt, 0);
143891 rc = db->errCode;
143893 db->init.iDb = saved_iDb;
143894 /* assert( saved_iDb==0 || (db->mDbFlags & DBFLAG_Vacuum)!=0 ); */
143896 if( db->init.orphanTrigger ){
143899 if( rc > pData->rc ) pData->rc = rc;
143907 db->init.azInit = sqlite3StdType; /* Any array of string ptrs will do */
143912 /* If the SQL column is blank it means this is an index that
143919 pIndex = sqlite3FindIndex(db, argv[1], db->aDb[iDb].zDbSName);
143923 if( sqlite3GetUInt32(argv[3],&pIndex->tnum)==0
143924 || pIndex->tnum<2
143925 || pIndex->tnum>pData->mxPage
143956 int mask = ((db->mDbFlags & DBFLAG_EncodingFixed) | ~DBFLAG_EncodingFixed);
143958 assert( (db->mDbFlags & DBFLAG_SchemaKnownOk)==0 );
143959 assert( iDb>=0 && iDb<db->nDb );
143960 assert( db->aDb[iDb].pSchema );
143961 assert( sqlite3_mutex_held(db->mutex) );
143962 assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
143964 db->init.busy = 1;
143966 /* Construct the in-memory representation schema tables (sqlite_schema or
143970 ** the schema table as read-only. */
143986 db->mDbFlags &= mask;
143994 pDb = &db->aDb[iDb];
143995 if( pDb->pBt==0 ){
144002 /* If there is not already a read-only (or read-write) transaction opened
144003 ** on the b-tree database, open one now. If a transaction is opened, it
144005 sqlite3BtreeEnter(pDb->pBt);
144006 if( sqlite3BtreeTxnState(pDb->pBt)==SQLITE_TXN_NONE ){
144007 rc = sqlite3BtreeBeginTrans(pDb->pBt, 0, 0);
144022 ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
144033 sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
144035 if( (db->flags & SQLITE_ResetDatabase)!=0 ){
144038 pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
144040 /* If opening a non-empty database, check the text encoding. For the
144042 ** For an attached db, it is an error if the encoding is not the same
144045 if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
144046 if( iDb==0 && (db->mDbFlags & DBFLAG_EncodingFixed)==0 ){
144050 encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
144057 /* If opening an attached database, the encoding much match ENC(db) */
144058 if( (meta[BTREE_TEXT_ENCODING-1] & 3)!=ENC(db) ){
144066 pDb->pSchema->enc = ENC(db);
144068 if( pDb->pSchema->cache_size==0 ){
144070 size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
144072 pDb->pSchema->cache_size = size;
144074 pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
144076 sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
144082 ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
144085 pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
144086 if( pDb->pSchema->file_format==0 ){
144087 pDb->pSchema->file_format = 1;
144089 if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
144100 if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
144101 db->flags &= ~(u64)SQLITE_LegacyFileFmt;
144106 assert( db->init.busy );
144107 initData.mxPage = sqlite3BtreeLastPage(pDb->pBt);
144112 db->aDb[iDb].zDbSName, zSchemaTabName);
144116 xAuth = db->xAuth;
144117 db->xAuth = 0;
144121 db->xAuth = xAuth;
144132 assert( pDb == &(db->aDb[iDb]) );
144133 if( db->mallocFailed ){
144136 pDb = &db->aDb[iDb];
144138 if( rc==SQLITE_OK || ((db->flags&SQLITE_NoSchemaError) && rc!=SQLITE_NOMEM)){
144153 /* Jump here for an error that occurs after successfully allocating
144154 ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
144159 sqlite3BtreeCommit(pDb->pBt);
144161 sqlite3BtreeLeave(pDb->pBt);
144170 db->init.busy = 0;
144175 ** Initialize all database files - the main database file, the file
144177 ** created using ATTACH statements. Return a success code. If an
144178 ** error occurs, write an error message into *pzErrMsg.
144185 int commit_internal = !(db->mDbFlags&DBFLAG_SchemaChange);
144187 assert( sqlite3_mutex_held(db->mutex) );
144188 assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
144189 assert( db->init.busy==0 );
144191 assert( db->nDb>0 );
144198 for(i=db->nDb-1; i>0; i--){
144199 assert( i==1 || sqlite3BtreeHoldsMutex(db->aDb[i].pBt) );
144212 ** This routine is a no-op if the database schema is already initialized.
144213 ** Otherwise, the schema is loaded. An error code is returned.
144217 sqlite3 *db = pParse->db;
144218 assert( sqlite3_mutex_held(db->mutex) );
144219 if( !db->init.busy ){
144220 rc = sqlite3Init(db, &pParse->zErrMsg);
144222 pParse->rc = rc;
144223 pParse->nErr++;
144224 }else if( db->noSharedCache ){
144225 db->mDbFlags |= DBFLAG_SchemaKnownOk;
144234 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
144235 ** make no changes to pParse->rc.
144238 sqlite3 *db = pParse->db;
144243 assert( pParse->checkSchema );
144244 assert( sqlite3_mutex_held(db->mutex) );
144245 for(iDb=0; iDb<db->nDb; iDb++){
144247 Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
144250 /* If there is not already a read-only (or read-write) transaction opened
144251 ** on the b-tree database, open one now. If a transaction is opened, it
144252 ** will be closed immediately after reading the meta-value. */
144257 pParse->rc = SQLITE_NOMEM;
144264 ** value stored as part of the in-memory schema representation,
144268 if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
144269 if( DbHasProperty(db, iDb, DB_SchemaLoaded) ) pParse->rc = SQLITE_SCHEMA;
144282 ** which database file in db->aDb[] the schema refers to.
144288 int i = -32768;
144290 /* If pSchema is NULL, then return -32768. This happens when code in
144292 ** created by a sub-select). In this case the return value of this
144295 ** We return -32768 instead of the more usual -1 simply because using
144296 ** -32768 as the incorrect index into db->aDb[] is much
144297 ** more likely to cause a segfault than -1 (of course there are assert()
144299 ** -32768 will still fit into a 16-bit signed integer.
144301 assert( sqlite3_mutex_held(db->mutex) );
144304 assert( i<db->nDb );
144305 if( db->aDb[i].pSchema==pSchema ){
144309 assert( i>=0 && i<db->nDb );
144318 sqlite3 *db = pParse->db;
144320 assert( db->pParse==pParse );
144321 assert( pParse->nested==0 );
144323 if( pParse->aTableLock ) sqlite3DbNNFreeNN(db, pParse->aTableLock);
144325 while( pParse->pCleanup ){
144326 ParseCleanup *pCleanup = pParse->pCleanup;
144327 pParse->pCleanup = pCleanup->pNext;
144328 pCleanup->xCleanup(db, pCleanup->pPtr);
144331 if( pParse->aLabel ) sqlite3DbNNFreeNN(db, pParse->aLabel);
144332 if( pParse->pConstExpr ){
144333 sqlite3ExprListDelete(db, pParse->pConstExpr);
144335 assert( db->lookaside.bDisable >= pParse->disableLookaside );
144336 db->lookaside.bDisable -= pParse->disableLookaside;
144337 db->lookaside.sz = db->lookaside.bDisable ? 0 : db->lookaside.szTrue;
144338 assert( pParse->db->pParse==pParse );
144339 db->pParse = pParse->pOuterParse;
144348 ** cost for this mechanism (an extra malloc), so it should not be used
144350 ** common cleanups, we save a single NULL-pointer comparison in
144355 ** pParse->earlyCleanup flag is set in that case. Calling code show verify
144357 ** use-after-free errors following an OOM. The preferred way to do this is
144360 ** testcase( pParse->earlyCleanup );
144363 ** except if an early cleanup occurs, in which case it returns NULL. So
144378 sqlite3OomFault(pParse->db);
144380 pCleanup = sqlite3DbMallocRaw(pParse->db, sizeof(*pCleanup));
144383 pCleanup->pNext = pParse->pCleanup;
144384 pParse->pCleanup = pCleanup;
144385 pCleanup->pPtr = pPtr;
144386 pCleanup->xCleanup = xCleanup;
144388 xCleanup(pParse->db, pPtr);
144391 pParse->earlyCleanup = 1;
144409 assert( db->pParse!=pParse );
144410 pParse->pOuterParse = db->pParse;
144411 db->pParse = pParse;
144412 pParse->db = db;
144413 if( db->mallocFailed ) sqlite3ErrorMsg(pParse, "out of memory");
144425 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
144429 const char *zSql, /* UTF-8 encoded SQL statement. */
144443 sParse.pOuterParse = db->pParse;
144444 db->pParse = &sParse;
144453 if( db->mallocFailed ){
144455 db->errCode = rc = SQLITE_NOMEM;
144458 assert( sqlite3_mutex_held(db->mutex) );
144460 /* For a long-term use prepared statement avoid the use of
144471 ** some other database connection is holding a write-lock, which in
144492 if( !db->noSharedCache ){
144493 for(i=0; i<db->nDb; i++) {
144494 Btree *pBt = db->aDb[i].pBt;
144499 const char *zDb = db->aDb[i].zDbSName;
144501 testcase( db->flags & SQLITE_ReadUncommit );
144509 if( db->pDisconnect ) sqlite3VtabUnlockList(db);
144512 if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
144514 int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
144525 sParse.zTail = &zSql[sParse.zTail-zSqlCopy];
144539 if( db->init.busy==0 ){
144540 sqlite3VdbeSetSql(sParse.pVdbe, zSql, (int)(sParse.zTail-zSql), prepFlags);
144542 if( db->mallocFailed ){
144547 if( sParse.checkSchema && db->init.busy==0 ){
144572 sParse.pTriggerPrg = pT->pNext;
144583 const char *zSql, /* UTF-8 encoded SQL statement. */
144600 sqlite3_mutex_enter(db->mutex);
144608 if( rc==SQLITE_OK || db->mallocFailed ) break;
144610 || (rc==SQLITE_SCHEMA && (sqlite3ResetOneSchema(db,-1), cnt++)==0) );
144613 assert( (rc&db->errMask)==rc );
144614 db->busyHandler.nBusy = 0;
144615 sqlite3_mutex_leave(db->mutex);
144636 assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
144640 assert( sqlite3_mutex_held(db->mutex) );
144642 rc = sqlite3LockAndPrepare(db, zSql, -1, prepFlags, p, &pNew, 0);
144665 ** and the statement is automatically recompiled if an schema change
144670 const char *zSql, /* UTF-8 encoded SQL statement. */
144682 const char *zSql, /* UTF-8 encoded SQL statement. */
144688 /* EVIDENCE-OF: R-37923-12173 The sqlite3_prepare_v2() interface works
144700 const char *zSql, /* UTF-8 encoded SQL statement. */
144707 /* EVIDENCE-OF: R-56861-42673 sqlite3_prepare_v3() differs from
144724 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
144728 const void *zSql, /* UTF-16 encoded SQL statement. */
144734 /* This function currently works by first transforming the UTF-16
144735 ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
144750 /* Make sure nBytes is non-negative and correct. It should be the
144753 ** an even number. If the input nBytes is negative, then the input
144767 sqlite3_mutex_enter(db->mutex);
144770 rc = sqlite3LockAndPrepare(db, zSql8, -1, prepFlags, 0, ppStmt, &zTail8);
144775 ** equivalent pointer into the UTF-16 string by counting the unicode
144777 ** the same number of characters into the UTF-16 string.
144779 int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
144784 sqlite3_mutex_leave(db->mutex);
144793 ** and the statement is automatically recompiled if an schema change
144798 const void *zSql, /* UTF-16 encoded SQL statement. */
144810 const void *zSql, /* UTF-16 encoded SQL statement. */
144822 const void *zSql, /* UTF-16 encoded SQL statement. */
144857 ** An instance of the following object is used to record information about
144870 ** An instance of the following object is used to record information about
144873 ** The aDefer[] array is used by the sorter-references optimization. For
144883 ** When the sorter-reference optimization is used, there is one entry in the
144892 int regReturn; /* Register holding block-output return address */
144893 int labelBkOut; /* Start label for the block-output subroutine */
144924 Select *pPrior = p->pPrior;
144925 sqlite3ExprListDelete(db, p->pEList);
144926 sqlite3SrcListDelete(db, p->pSrc);
144927 sqlite3ExprDelete(db, p->pWhere);
144928 sqlite3ExprListDelete(db, p->pGroupBy);
144929 sqlite3ExprDelete(db, p->pHaving);
144930 sqlite3ExprListDelete(db, p->pOrderBy);
144931 sqlite3ExprDelete(db, p->pLimit);
144932 if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
144934 if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
144935 sqlite3WindowListDelete(db, p->pWinDefn);
144937 while( p->pWin ){
144938 assert( p->pWin->ppThis==&p->pWin );
144939 sqlite3WindowUnlinkFromSelect(p->pWin);
144952 pDest->eDest = (u8)eDest;
144953 pDest->iSDParm = iParm;
144954 pDest->iSDParm2 = 0;
144955 pDest->zAffSdst = 0;
144956 pDest->iSdst = 0;
144957 pDest->nSdst = 0;
144968 SrcList *pSrc, /* the FROM clause -- which tables to scan */
144978 pAllocated = pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
144980 assert( pParse->db->mallocFailed );
144985 sqlite3Expr(pParse->db,TK_ASTERISK,0));
144987 pNew->pEList = pEList;
144988 pNew->op = TK_SELECT;
144989 pNew->selFlags = selFlags;
144990 pNew->iLimit = 0;
144991 pNew->iOffset = 0;
144992 pNew->selId = ++pParse->nSelect;
144993 pNew->addrOpenEphm[0] = -1;
144994 pNew->addrOpenEphm[1] = -1;
144995 pNew->nSelectRow = 0;
144996 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, SZ_SRCLIST_1);
144997 pNew->pSrc = pSrc;
144998 pNew->pWhere = pWhere;
144999 pNew->pGroupBy = pGroupBy;
145000 pNew->pHaving = pHaving;
145001 pNew->pOrderBy = pOrderBy;
145002 pNew->pPrior = 0;
145003 pNew->pNext = 0;
145004 pNew->pLimit = pLimit;
145005 pNew->pWith = 0;
145007 pNew->pWin = 0;
145008 pNew->pWinDefn = 0;
145010 if( pParse->db->mallocFailed ) {
145011 clearSelect(pParse->db, pNew, pNew!=&standin);
145014 assert( pNew->pSrc!=0 || pParse->nErr>0 );
145031 ** Return a pointer to the right-most SELECT statement in a compound.
145034 while( p->pNext ) p = p->pNext;
145040 ** type of join. Return an integer constant that expresses that type
145052 ** If an illegal or unsupported join type is seen, then still return
145053 ** a join type, but put an error in the pParse structure.
145059 ** ------- ----- ----- ------------
145060 ** CROSS - - JT_CROSS
145061 ** INNER - - JT_INNER
145062 ** LEFT - - JT_LEFT|JT_OUTER
145063 ** LEFT OUTER - JT_LEFT|JT_OUTER
145064 ** RIGHT - - JT_RIGHT|JT_OUTER
145065 ** RIGHT OUTER - JT_RIGHT|JT_OUTER
145066 ** FULL - - JT_LEFT|JT_RIGHT|JT_OUTER
145067 ** FULL OUTER - JT_LEFT|JT_RIGHT|JT_OUTER
145068 ** NATURAL INNER - JT_NATURAL|JT_INNER
145069 ** NATURAL LEFT - JT_NATURAL|JT_LEFT|JT_OUTER
145071 ** NATURAL RIGHT - JT_NATURAL|JT_RIGHT|JT_OUTER
145073 ** NATURAL FULL - JT_NATURAL|JT_LEFT|JT_RIGHT
145077 ** of other non-standard and in many cases nonsensical join types.
145082 ** INNER CROSS JOIN -> same as JOIN
145083 ** NATURAL CROSS JOIN -> same as NATURAL JOIN
145084 ** OUTER LEFT JOIN -> same as LEFT JOIN
145085 ** LEFT NATURAL JOIN -> same as NATURAL LEFT JOIN
145086 ** LEFT RIGHT JOIN -> same as FULL JOIN
145087 ** RIGHT OUTER FULL JOIN -> same as FULL JOIN
145088 ** CROSS CROSS CROSS JOIN -> same as JOIN
145127 if( p->n==aKeyword[j].nChar
145128 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
145156 ** Return the index of a column in a table. Return -1 if the column
145166 aCol = pTab->aCol;
145167 nCol = pTab->nCol;
145170 i = pTab->aHx[h % sizeof(pTab->aHx)];
145180 while( 1 /*exit-by-break*/ ){
145189 return -1;
145197 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem) );
145198 if( pItem->fg.isNestedFrom ){
145200 assert( pItem->fg.isSubquery );
145201 assert( pItem->u4.pSubq!=0 );
145202 assert( pItem->u4.pSubq->pSelect!=0 );
145203 pResults = pItem->u4.pSubq->pSelect->pEList;
145205 assert( iCol>=0 && iCol<pResults->nExpr );
145206 pResults->a[iCol].fg.bUsed = 1;
145212 ** table that has a column named zCol. The search is left-to-right.
145222 int iStart, /* First member of pSrc->a[] to check */
145223 int iEnd, /* Last member of pSrc->a[] to check */
145225 int *piTab, /* Write index of pSrc->a[] here */
145226 int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
145232 assert( iEnd<pSrc->nSrc );
145237 iCol = sqlite3ColumnIndex(pSrc->a[i].pSTab, zCol);
145239 && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pSTab->aCol[iCol])==0)
145242 sqlite3SrcItemColumnUsed(&pSrc->a[i], iCol);
145257 ** The EP_OuterON property is used on terms of an expression to tell
145284 p->w.iJoin = iTable;
145285 if( p->op==TK_FUNCTION ){
145287 if( p->x.pList ){
145289 for(i=0; i<p->x.pList->nExpr; i++){
145290 sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable, joinFlag);
145294 sqlite3SetJoinExpr(p->pLeft, iTable, joinFlag);
145295 p = p->pRight;
145300 ** is simplified into an ordinary JOIN, and when an ON expression is
145304 ** an ordinary term that omits the EP_OuterON mark. Or if iTable<0, then
145315 if( iTable<0 || (ExprHasProperty(p, EP_OuterON) && p->w.iJoin==iTable) ){
145319 if( p->op==TK_COLUMN && p->iTable==iTable && !nullable ){
145322 if( p->op==TK_FUNCTION ){
145324 assert( p->pLeft==0 );
145325 if( p->x.pList ){
145327 for(i=0; i<p->x.pList->nExpr; i++){
145328 unsetJoinExpr(p->x.pList->a[i].pExpr, iTable, nullable);
145332 unsetJoinExpr(p->pLeft, iTable, nullable);
145333 p = p->pRight;
145350 ** The left most table is the first entry in Select.pSrc. The right-most
145364 pSrc = p->pSrc;
145365 pLeft = &pSrc->a[0];
145367 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
145368 Table *pRightTab = pRight->pSTab;
145371 if( NEVER(pLeft->pSTab==0 || pRightTab==0) ) continue;
145372 joinType = (pRight->fg.jointype & JT_OUTER)!=0 ? EP_OuterON : EP_InnerON;
145374 /* If this is a NATURAL join, synthesize an appropriate USING clause
145377 if( pRight->fg.jointype & JT_NATURAL ){
145379 if( pRight->fg.isUsing || pRight->u3.pOn ){
145381 "an ON or USING clause", 0);
145384 for(j=0; j<pRightTab->nCol; j++){
145387 if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
145388 zName = pRightTab->aCol[j].zCnName;
145392 assert( pUsing->nId>0 );
145393 assert( pUsing->a[pUsing->nId-1].zName==0 );
145394 pUsing->a[pUsing->nId-1].zName = sqlite3DbStrDup(pParse->db, zName);
145399 pRight->fg.isUsing = 1;
145400 pRight->fg.isSynthUsing = 1;
145401 pRight->u3.pUsing = pUsing;
145403 if( pParse->nErr ) return 1;
145410 ** Report an error if any column mentioned in the USING clause is
145413 if( pRight->fg.isUsing ){
145414 IdList *pList = pRight->u3.pUsing;
145415 sqlite3 *db = pParse->db;
145417 for(j=0; j<pList->nId; j++){
145426 zName = pList->a[j].zName;
145430 pRight->fg.isSynthUsing)==0
145432 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
145437 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
145438 if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 && pParse->nErr==0 ){
145441 ** contains the zName column, then this branch is a no-op.
145444 ** such tables. Raise an error if more than one of those references
145447 ** We really ought to raise an error if there are two or more
145448 ** non-USING references to zName on the left of an INNER or LEFT
145457 pRight->fg.isSynthUsing)!=0 ){
145458 if( pSrc->a[iLeft].fg.isUsing==0
145459 || sqlite3IdListIndex(pSrc->a[iLeft].u3.pUsing, zName)<0
145467 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
145473 pE1->affExpr = SQLITE_AFF_DEFER;
145476 }else if( (pSrc->a[i+1].fg.jointype & JT_LEFT)!=0 && pParse->nErr==0 ){
145488 pEq->w.iJoin = pE2->iTable;
145490 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pEq);
145495 ** an AND operator.
145497 else if( pRight->u3.pOn ){
145498 sqlite3SetJoinExpr(pRight->u3.pOn, pRight->iCursor, joinType);
145499 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn);
145500 pRight->u3.pOn = 0;
145501 pRight->fg.isOn = 1;
145508 ** An instance of this object holds information (beyond pParse and pSelect)
145522 ** This routine does the work of loading query data into an array of
145530 sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
145531 0, pInfo->ecelFlags);
145533 if( pInfo->pExtra ){
145534 sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
145535 sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
145553 int nOBSat = pSort->nOBSat;
145554 Vdbe *v = pParse->pVdbe;
145555 int regOut = ++pParse->nMem;
145556 if( pSort->pDeferredRowLoad ){
145557 innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
145559 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
145565 ** through regData+nData-1 onto the sorter.
145576 Vdbe *v = pParse->pVdbe; /* Stmt under construction */
145577 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
145578 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
145582 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
145605 pSort->addrPush = sqlite3VdbeCurrentAddr(v);
145610 regBase = regData - nPrefixReg;
145612 regBase = pParse->nMem + 1;
145613 pParse->nMem += nBase;
145615 assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
145616 iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
145617 pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
145618 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
145621 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
145635 regPrevKey = pParse->nMem+1;
145636 pParse->nMem += pSort->nOBSat;
145637 nKey = nExpr - pSort->nOBSat + bSeq;
145641 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
145644 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
145645 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
145646 if( pParse->db->mallocFailed ) return;
145647 pOp->p2 = nKey + nData;
145648 pKI = pOp->p4.pKeyInfo;
145649 memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
145650 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
145651 testcase( pKI->nAllField > pKI->nKeyField+2 );
145652 pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
145653 pKI->nAllField-pKI->nKeyField-1);
145657 pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
145658 pSort->regReturn = ++pParse->nMem;
145659 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
145660 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
145662 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
145666 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
145671 ** in an array of registers. They need to be composed into a record
145680 ** jump to the next iteration of the loop. If the pSort->labelOBLopt
145685 int iCsr = pSort->iECursor;
145690 iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
145697 if( pSort->sortFlags & SORTFLAG_UseSorter ){
145702 sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
145703 regBase+nOBSat, nBase-nOBSat);
145706 pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
145709 pSort->addrPushEnd = sqlite3VdbeCurrentAddr(v)-1;
145735 ** Build an ephemeral table that contains all entries seen before and
145738 ** Parameter iTab is the cursor number of an ephemeral table that must
145755 ** in an array of registers used to store the previous result row so that
145779 int nResultCol = pEList->nExpr;
145780 Vdbe *v = pParse->pVdbe;
145789 iRet = regPrev = pParse->nMem+1;
145790 pParse->nMem += nResultCol;
145794 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
145795 if( i<nResultCol-1 ){
145802 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
145805 assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
145806 sqlite3VdbeAddOp3(v, OP_Copy, regElem, regPrev, nResultCol-1);
145841 ** No adjustments necessary. This function is a no-op.
145846 ** OP_OpenEphemeral opcode into an OP_Noop.
145852 ** into an OP_Null on the iVal register.
145860 if( pParse->nErr==0
145863 Vdbe *v = pParse->pVdbe;
145865 if( sqlite3VdbeGetOp(v, iOpenEphAddr+1)->opcode==OP_Explain ){
145869 /* Change the OP_OpenEphemeral to an OP_Null that sets the MEM_Cleared
145874 pOp->opcode = OP_Null;
145875 pOp->p1 = 1;
145876 pOp->p2 = iVal;
145883 ** This function is called as part of inner-loop generation for a SELECT
145884 ** statement with an ORDER BY that is not optimized by an index. It
145885 ** determines the expressions, if any, that the sorter-reference
145886 ** optimization should be used for. The sorter-reference optimization
145899 ** for which the sorter-reference optimization should be enabled.
145900 ** Additionally, the pSort->aDefer[] array is populated with entries
145902 ** output variable (*ppExtra) is set to an expression list containing
145915 for(i=0; i<pEList->nExpr; i++){
145916 struct ExprList_item *pItem = &pEList->a[i];
145917 if( pItem->u.x.iOrderByCol==0 ){
145918 Expr *pExpr = pItem->pExpr;
145920 if( pExpr->op==TK_COLUMN
145921 && pExpr->iColumn>=0
145923 && (pTab = pExpr->y.pTab)!=0
145925 && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)!=0
145929 if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
145932 if( nDefer==ArraySize(pSort->aDefer) ){
145940 nKey = pPk->nKeyCol;
145945 pNew->iTable = pExpr->iTable;
145947 pNew->y.pTab = pExpr->y.pTab;
145948 pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
145952 pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
145953 pSort->aDefer[nDefer].iCsr = pExpr->iTable;
145954 pSort->aDefer[nDefer].nKey = nKey;
145958 pItem->fg.bSorterRef = 1;
145962 pSort->nDefer = (u8)nDefer;
145971 ** If srcTab is negative, then the p->pEList expressions
145973 ** zero or more, then data is pulled from srcTab and p->pEList is used only
145979 int srcTab, /* Pull data from this table if non-negative */
145986 Vdbe *v = pParse->pVdbe;
145989 int eDest = pDest->eDest; /* How to dispose of results */
145990 int iParm = pDest->iSDParm; /* First argument to disposal method */
145995 /* Usually, regResult is the first cell in an array of memory cells
145998 ** values for any expressions that are also part of the sort-key are omitted
146004 assert( p->pEList!=0 );
146005 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
146006 if( pSort && pSort->pOrderBy==0 ) pSort = 0;
146009 codeOffset(v, p->iOffset, iContinue);
146014 nResultCol = p->pEList->nExpr;
146016 if( pDest->iSdst==0 ){
146018 nPrefixReg = pSort->pOrderBy->nExpr;
146019 if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
146020 pParse->nMem += nPrefixReg;
146022 pDest->iSdst = pParse->nMem+1;
146023 pParse->nMem += nResultCol;
146024 }else if( pDest->iSdst+nResultCol > pParse->nMem ){
146025 /* This is an error condition that can result, for example, when a SELECT
146026 ** on the right-hand side of an INSERT contains more result columns than
146030 pParse->nMem += nResultCol;
146032 pDest->nSdst = nResultCol;
146033 regOrig = regResult = pDest->iSdst;
146037 VdbeComment((v, "%s", p->pEList->a[i].zEName));
146043 /* If the destination is an EXISTS(...) expression, the actual
146046 u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
146054 /* For each expression in p->pEList that is a copy of an expression in
146055 ** the ORDER BY clause (pSort->pOrderBy), set the associated
146057 ** expression within the sort-key that pushOntoSorter() will generate.
146058 ** This allows the p->pEList field to be omitted from the sorted record,
146062 for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
146064 if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
146065 p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
146069 selectExprDefer(pParse, pSort, p->pEList, &pExtra);
146070 if( pExtra && pParse->db->mallocFailed==0 ){
146076 VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
146077 pOp->p2 += (pExtra->nExpr - pSort->nDefer);
146078 pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
146079 pParse->nMem += pExtra->nExpr;
146085 pEList = p->pEList;
146086 for(i=0; i<pEList->nExpr; i++){
146087 if( pEList->a[i].u.x.iOrderByCol>0
146089 || pEList->a[i].fg.bSorterRef
146092 nResultCol--;
146111 if( pExtra ) nResultCol += pExtra->nExpr;
146113 if( p->iLimit
146119 pSort->pDeferredRowLoad = &sRowLoadInfo;
146131 int eType = pDistinct->eTnctType;
146132 int iTab = pDistinct->tabTnct;
146133 assert( nResultCol==p->pEList->nExpr );
146134 iTab = codeDistinct(pParse, eType, iTab, iContinue, p->pEList, regResult);
146135 fixDistinctOpenEph(pParse, eType, iTab, pDistinct->addrTnct);
146137 codeOffset(v, p->iOffset, iContinue);
146178 /* A destination of SRT_Table and a non-zero iSDParm2 parameter means
146179 ** that this is an "UPDATE ... FROM" on a virtual table or view. In this
146181 ** This does not affect operation in any way - it just allows MakeRecord
146182 ** to process OPFLAG_NOCHANGE values without an assert() failing. */
146183 if( eDest==SRT_Table && pDest->iSDParm2 ){
146190 ** on an ephemeral index. If the current row is already present
146220 int i2 = pDest->iSDParm2;
146223 /* If the UPDATE FROM join is an aggregate that matches no rows, it
146229 regResult+(i2<0), nResultCol-(i2<0), r1);
146240 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
146252 pDest->iSDParm2 = 0; /* Signal that any Bloom filter is unpopulated */
146255 assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
146257 r1, pDest->zAffSdst, nResultCol);
146259 if( pDest->iSDParm2 ){
146260 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0,
146278 /* If this is a scalar select that is part of an expression, then
146284 assert( nResultCol<=pDest->nSdst );
146288 assert( nResultCol==pDest->nSdst );
146296 case SRT_Coroutine: /* Send data to a co-routine */
146304 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
146313 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
146314 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
146315 ** pSO->nExpr columns, then make sure all keys are unique by adding a
146324 pSO = pDest->pOrderBy;
146326 nKey = pSO->nExpr;
146345 regResult + pSO->a[i].u.x.iOrderByCol - 1,
146363 ** user-defined functions that have side effects. We do not care
146377 if( pSort==0 && p->iLimit ){
146378 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
146383 ** Allocate a KeyInfo object sufficient for an index of N key columns and
146390 p->aSortFlags = (u8*)&p->aColl[N+X];
146391 p->nKeyField = (u16)N;
146392 p->nAllField = (u16)(N+X);
146393 p->enc = ENC(db);
146394 p->db = db;
146395 p->nRef = 1;
146396 memset(p->aColl, 0, nExtra);
146408 assert( p->db!=0 );
146409 assert( p->nRef>0 );
146410 p->nRef--;
146411 if( p->nRef==0 ) sqlite3DbNNFreeNN(p->db, p);
146420 assert( p->nRef>0 );
146421 p->nRef++;
146433 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
146437 ** Given an expression list, generate a KeyInfo structure that records
146440 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
146459 sqlite3 *db = pParse->db;
146462 nExpr = pList->nExpr;
146463 pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
146466 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
146467 pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
146468 pInfo->aSortFlags[i-iStart] = pItem->fg.sortFlags;
146490 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
146491 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
146494 ** "USE TEMP B-TREE FOR xxx"
146500 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
146504 ** Assign expression b to lvalue a. A second, no-op, version of this macro
146513 /* No-op versions of the explainXXX() functions and macros. */
146520 ** If the inner loop was generated using a non-null pOrderBy argument,
146532 Vdbe *v = pParse->pVdbe; /* The prepared statement */
146533 int addrBreak = pSort->labelDone; /* Jump here to exit loop */
146538 ExprList *pOrderBy = pSort->pOrderBy;
146539 int eDest = pDest->eDest;
146540 int iParm = pDest->iSDParm;
146549 struct ExprList_item *aOutEx = p->pEList->a;
146554 nKey = pOrderBy->nExpr - pSort->nOBSat;
146555 if( pSort->nOBSat==0 || nKey==1 ){
146557 "USE TEMP B-TREE FOR %sORDER BY", pSort->nOBSat?"LAST TERM OF ":""
146561 "USE TEMP B-TREE FOR LAST %d TERMS OF ORDER BY", nKey
146564 sqlite3VdbeScanStatusRange(v, addrExplain,pSort->addrPush,pSort->addrPushEnd);
146565 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, pSort->addrPush);
146569 if( pSort->labelBkOut ){
146570 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
146572 sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
146576 /* Open any cursors needed for sorter-reference expressions */
146577 for(i=0; i<pSort->nDefer; i++){
146578 Table *pTab = pSort->aDefer[i].pTab;
146579 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
146580 sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
146581 nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
146585 iTab = pSort->iECursor;
146587 if( eDest==SRT_Mem && p->iOffset ){
146588 sqlite3VdbeAddOp2(v, OP_Null, 0, pDest->iSdst);
146591 regRow = pDest->iSdst;
146601 if( pSort->sortFlags & SORTFLAG_UseSorter ){
146602 int regSortOut = ++pParse->nMem;
146603 iSortTab = pParse->nTab++;
146604 if( pSort->labelBkOut ){
146612 assert( p->iLimit==0 && p->iOffset==0 );
146617 codeOffset(v, p->iOffset, addrContinue);
146620 if( p->iOffset>0 ){
146621 sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
146624 for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
146631 if( pSort->nDefer ){
146635 for(i=0; i<pSort->nDefer; i++){
146636 int iCsr = pSort->aDefer[i].iCsr;
146637 Table *pTab = pSort->aDefer[i].pTab;
146638 int nKey = pSort->aDefer[i].nKey;
146648 assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
146661 for(i=nColumn-1; i>=0; i--){
146670 iRead = aOutEx[i].u.x.iOrderByCol-1;
146672 iRead = iCol--;
146678 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
146690 assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
146692 pDest->zAffSdst, nColumn);
146702 int i2 = pDest->iSDParm2;
146704 sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1);
146717 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
146719 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
146735 if( pSort->sortFlags & SORTFLAG_UseSorter ){
146740 sqlite3VdbeScanStatusRange(v, addrExplain, sqlite3VdbeCurrentAddr(v)-1, -1);
146741 if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
146751 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
146753 ** result-set expression in all of the following SELECT statements is
146764 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
146791 assert( pNC->pSrcList!=0 );
146792 switch( pExpr->op ){
146800 int iCol = pExpr->iColumn; /* Index of column in pTab */
146802 SrcList *pTabList = pNC->pSrcList;
146803 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
146804 if( j<pTabList->nSrc ){
146805 pTab = pTabList->a[j].pSTab;
146806 if( pTabList->a[j].fg.isSubquery ){
146807 pS = pTabList->a[j].u4.pSubq->pSelect;
146812 pNC = pNC->pNext;
146827 ** sub-select. In this case, set the column type to NULL, even
146837 assert( pTab && ExprUseYTab(pExpr) && pExpr->y.pTab==pTab );
146839 /* The "table" is actually a sub-select or a view in the FROM clause
146841 ** data for the result-set column of the sub-select.
146843 if( iCol<pS->pEList->nExpr
146847 ** rowid of the sub-select or view. This expression is legal (see
146848 ** test case misc2.2.2) - it always evaluates to NULL.
146851 Expr *p = pS->pEList->a[iCol].pExpr;
146852 sNC.pSrcList = pS->pSrc;
146854 sNC.pParse = pNC->pParse;
146861 if( iCol<0 ) iCol = pTab->iPKey;
146862 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
146867 zOrigCol = pTab->aCol[iCol].zCnName;
146868 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
146870 zOrigTab = pTab->zName;
146871 if( pNC->pParse && pTab->pSchema ){
146872 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
146873 zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
146876 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
146880 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
146888 /* The expression is a sub-select. Return the declaration type and
146896 pS = pExpr->x.pSelect;
146897 p = pS->pEList->a[0].pExpr;
146898 sNC.pSrcList = pS->pSrc;
146900 sNC.pParse = pNC->pParse;
146928 Vdbe *v = pParse->pVdbe;
146934 for(i=0; i<pEList->nExpr; i++){
146935 Expr *p = pEList->a[i].pExpr;
146943 /* The vdbe must make its own copy of the column-type and other
146963 ** column has an AS clause assigning it a name, that will be the name used.
146993 Vdbe *v = pParse->pVdbe;
146998 sqlite3 *db = pParse->db;
147002 if( pParse->colNamesSet ) return;
147003 /* Column names are determined by the left-most term of a compound select */
147004 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
147006 pTabList = pSelect->pSrc;
147007 pEList = pSelect->pEList;
147010 pParse->colNamesSet = 1;
147011 fullName = (db->flags & SQLITE_FullColNames)!=0;
147012 srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
147013 sqlite3VdbeSetNumCols(v, pEList->nExpr);
147014 for(i=0; i<pEList->nExpr; i++){
147015 Expr *p = pEList->a[i].pExpr;
147018 assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
147019 assert( p->op!=TK_COLUMN
147020 || (ExprUseYTab(p) && p->y.pTab!=0) ); /* Covering idx not yet coded */
147021 if( pEList->a[i].zEName && pEList->a[i].fg.eEName==ENAME_NAME ){
147022 /* An AS clause always takes first priority */
147023 char *zName = pEList->a[i].zEName;
147025 }else if( srcName && p->op==TK_COLUMN ){
147027 int iCol = p->iColumn;
147028 pTab = p->y.pTab;
147030 if( iCol<0 ) iCol = pTab->iPKey;
147031 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
147035 zCol = pTab->aCol[iCol].zCnName;
147039 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
147045 const char *z = pEList->a[i].zEName;
147054 ** Given an expression list (which is really the list of expressions
147067 ** column has an AS clause assigning it a name, that will be the name used.
147081 sqlite3 *db = pParse->db; /* Database connection */
147093 nCol = pEList->nExpr;
147105 for(i=0, pCol=aCol; i<nCol && !pParse->nErr; i++, pCol++){
147106 struct ExprList_item *pX = &pEList->a[i];
147108 /* Get an appropriate name for the column
147110 if( (zName = pX->zEName)!=0 && pX->fg.eEName==ENAME_NAME ){
147111 /* If the column contains an "AS <name>" phrase, use <name> as the name */
147113 Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pX->pExpr);
147114 while( ALWAYS(pColExpr!=0) && pColExpr->op==TK_DOT ){
147115 pColExpr = pColExpr->pRight;
147118 if( pColExpr->op==TK_COLUMN
147120 && ALWAYS( pColExpr->y.pTab!=0 )
147123 int iCol = pColExpr->iColumn;
147124 pTab = pColExpr->y.pTab;
147125 if( iCol<0 ) iCol = pTab->iPKey;
147126 zName = iCol>=0 ? pTab->aCol[iCol].zCnName : "rowid";
147127 }else if( pColExpr->op==TK_ID ){
147129 zName = pColExpr->u.zToken;
147132 assert( zName==pX->zEName ); /* pointer comparison intended */
147142 ** append an integer to the name so that it becomes unique.
147146 if( pCollide->fg.bUsingTerm ){
147147 pCol->colFlags |= COLFLAG_NOEXPAND;
147151 for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
147160 pCol->zCnName = zName;
147161 pCol->hName = sqlite3StrIHash(zName);
147162 if( pX->fg.bNoExpand ){
147163 pCol->colFlags |= COLFLAG_NOEXPAND;
147171 if( pParse->nErr ){
147178 return pParse->rc;
147200 sqlite3 *db = pParse->db;
147209 assert( (pSelect->selFlags & SF_Resolved)!=0 );
147210 assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
147212 if( db->mallocFailed || IN_RENAME_OBJECT ) return;
147213 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
147214 a = pSelect->pEList->a;
147216 sNC.pSrcList = pSelect->pSrc;
147217 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
147222 pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
147224 /* pCol->szEst = ... // Column size est for SELECT tables never used */
147225 pCol->affinity = sqlite3ExprAffinity(p);
147226 while( pCol->affinity<=SQLITE_AFF_NONE && pS2->pNext!=0 ){
147227 m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
147228 pS2 = pS2->pNext;
147229 pCol->affinity = sqlite3ExprAffinity(pS2->pEList->a[i].pExpr);
147231 if( pCol->affinity<=SQLITE_AFF_NONE ){
147232 pCol->affinity = aff;
147234 if( pCol->affinity>=SQLITE_AFF_TEXT && (pS2->pNext || pS2!=pSelect) ){
147235 for(pS2=pS2->pNext; pS2; pS2=pS2->pNext){
147236 m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
147238 if( pCol->affinity==SQLITE_AFF_TEXT && (m&0x01)!=0 ){
147239 pCol->affinity = SQLITE_AFF_BLOB;
147241 if( pCol->affinity>=SQLITE_AFF_NUMERIC && (m&0x02)!=0 ){
147242 pCol->affinity = SQLITE_AFF_BLOB;
147244 if( pCol->affinity>=SQLITE_AFF_NUMERIC && p->op==TK_CAST ){
147245 pCol->affinity = SQLITE_AFF_FLEXNUM;
147249 if( zType==0 || pCol->affinity!=sqlite3AffinityType(zType, 0) ){
147250 if( pCol->affinity==SQLITE_AFF_NUMERIC
147251 || pCol->affinity==SQLITE_AFF_FLEXNUM
147257 if( sqlite3StdTypeAffinity[j]==pCol->affinity ){
147266 n = sqlite3Strlen30(pCol->zCnName);
147267 pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+k+2);
147268 pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
147269 if( pCol->zCnName ){
147270 memcpy(&pCol->zCnName[n+1], zType, k+1);
147271 pCol->colFlags |= COLFLAG_HASTYPE;
147276 assert( pTab->pIndex==0 );
147277 sqlite3ColumnSetColl(db, pCol, pColl->zName);
147280 pTab->szTabRow = 1; /* Any non-zero value works */
147289 sqlite3 *db = pParse->db;
147292 savedFlags = db->flags;
147293 db->flags &= ~(u64)SQLITE_FullColNames;
147294 db->flags |= SQLITE_ShortColNames;
147296 db->flags = savedFlags;
147297 if( pParse->nErr ) return 0;
147298 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
147303 pTab->nTabRef = 1;
147304 pTab->zName = 0;
147305 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
147306 sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
147308 pTab->iPKey = -1;
147309 if( db->mallocFailed ){
147318 ** If an error occurs, return NULL and leave a message in pParse.
147321 if( pParse->pVdbe ){
147322 return pParse->pVdbe;
147324 if( pParse->pToplevel==0
147325 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
147327 pParse->okConstFactor = 1;
147335 ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
147343 ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
147351 ** Only if pLimit->pLeft!=0 do the limit registers get
147361 Expr *pLimit = p->pLimit;
147363 if( p->iLimit ) return;
147366 ** "LIMIT -1" always shows all rows. There is some
147372 assert( pLimit->op==TK_LIMIT );
147373 assert( pLimit->pLeft!=0 );
147374 p->iLimit = iLimit = ++pParse->nMem;
147377 if( sqlite3ExprIsInteger(pLimit->pLeft, &n, pParse) ){
147382 }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
147383 p->nSelectRow = sqlite3LogEst((u64)n);
147384 p->selFlags |= SF_FixedLimit;
147387 sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
147392 if( pLimit->pRight ){
147393 p->iOffset = iOffset = ++pParse->nMem;
147394 pParse->nMem++; /* Allocate an extra register for limit+offset */
147395 sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
147406 ** Return the appropriate collating sequence for the iCol-th column of
147407 ** the result set for the compound-select statement "p". Return NULL if
147411 ** left-most term of the select that has a collating sequence.
147415 if( p->pPrior ){
147416 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
147421 /* iCol must be less than p->pEList->nExpr. Otherwise an error would
147424 if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
147425 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
147432 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
147440 ExprList *pOrderBy = p->pOrderBy;
147441 int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0;
147442 sqlite3 *db = pParse->db;
147447 struct ExprList_item *pItem = &pOrderBy->a[i];
147448 Expr *pTerm = pItem->pExpr;
147451 if( pTerm->flags & EP_Collate ){
147454 pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
147455 if( pColl==0 ) pColl = db->pDfltColl;
147456 pOrderBy->a[i].pExpr =
147457 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
147460 pRet->aColl[i] = pColl;
147461 pRet->aSortFlags[i] = pOrderBy->a[i].fg.sortFlags;
147473 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
147475 ** p->pPrior p
147478 ** There is exactly one reference to the recursive-table in the FROM clause
147479 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
147481 ** The setup-query runs once to generate an initial set of rows that go
147485 ** recursive-table for a recursive-query run. The output of the recursive-query
147494 ** If the query has an ORDER BY, then entries in the Queue table are kept in
147496 ** an ORDER BY, the Queue table is just a FIFO.
147500 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
147510 SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
147511 int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
147512 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
147514 Select *pFirstRec; /* Left-most recursive term */
147530 if( p->pWin ){
147541 p->nSelectRow = 320; /* 4 billion rows */
147543 pLimit = p->pLimit;
147544 regLimit = p->iLimit;
147545 regOffset = p->iOffset;
147546 p->pLimit = 0;
147547 p->iLimit = p->iOffset = 0;
147548 pOrderBy = p->pOrderBy;
147551 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
147552 if( pSrc->a[i].fg.isRecursive ){
147553 iCurrent = pSrc->a[i].iCursor;
147561 iQueue = pParse->nTab++;
147562 if( p->op==TK_UNION ){
147564 iDistinct = pParse->nTab++;
147571 regCurrent = ++pParse->nMem;
147575 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
147583 p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
147584 p->selFlags |= SF_UsesEphemeral;
147588 p->pOrderBy = 0;
147594 ** iDistinct table. pFirstRec is left pointing to the left-most
147597 for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){
147598 if( pFirstRec->selFlags & SF_Aggregate ){
147602 pFirstRec->op = TK_ALL;
147603 if( (pFirstRec->pPrior->selFlags & SF_Recursive)==0 ) break;
147606 /* Store the results of the setup-query in Queue. */
147607 pSetup = pFirstRec->pPrior;
147608 pSetup->pNext = 0;
147611 pSetup->pNext = p;
147620 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
147638 ** the value for the recursive-table. Store the results in the Queue.
147640 pFirstRec->pPrior = 0;
147643 assert( pFirstRec->pPrior==0 );
147644 pFirstRec->pPrior = pSetup;
147651 sqlite3ExprListDelete(pParse->db, p->pOrderBy);
147652 p->pOrderBy = pOrderBy;
147653 p->pLimit = pLimit;
147661 Select *p, /* The right-most of SELECTs to be coded */
147666 ** Handle the special case of a compound-select that originates from a
147679 ** Since the limit is exactly 1, we only need to evaluate the left-most VALUES.
147683 Select *p, /* The right-most of SELECTs to be coded */
147688 int bShowAll = p->pLimit==0;
147689 assert( p->selFlags & SF_MultiValue );
147691 assert( p->selFlags & SF_Values );
147692 assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
147693 assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
147695 if( p->pWin ) return -1;
147697 if( p->pPrior==0 ) break;
147698 assert( p->pPrior->pNext==p );
147699 p = p->pPrior;
147705 selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
147707 p->nSelectRow = nRow;
147708 p = p->pNext;
147719 while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
147728 ** "p" points to the right-most of the two queries. the query on the
147729 ** left is p->pPrior. The left query could also be a compound query
147735 ** Example 1: Consider a three-way compound SQL statement.
147743 ** `-----> SELECT b FROM t2
147745 ** `------> SELECT a FROM t1
147749 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
147756 Select *p, /* The right-most of SELECTs to be coded */
147767 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
147769 assert( p && p->pPrior ); /* Calling function guarantees this much */
147770 assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
147771 assert( p->selFlags & SF_Compound );
147772 db = pParse->db;
147773 pPrior = p->pPrior;
147775 assert( pPrior->pOrderBy==0 );
147776 assert( pPrior->pLimit==0 );
147784 assert( p->pEList );
147785 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
147789 /* Special handling for a compound-select that originates as a VALUES clause.
147791 if( p->selFlags & SF_MultiValue ){
147800 assert( p->pEList && pPrior->pEList );
147801 assert( p->pEList->nExpr==pPrior->pEList->nExpr );
147804 if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){
147809 /* Compound SELECTs that have an ORDER BY clause are handled separately.
147811 if( p->pOrderBy ){
147816 if( pPrior->pPrior==0 ){
147818 ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
147824 switch( p->op ){
147828 assert( !pPrior->pLimit );
147829 pPrior->iLimit = p->iLimit;
147830 pPrior->iOffset = p->iOffset;
147831 pPrior->pLimit = p->pLimit;
147834 pPrior->pLimit = 0;
147838 p->pPrior = 0;
147839 p->iLimit = pPrior->iLimit;
147840 p->iOffset = pPrior->iOffset;
147841 if( p->iLimit ){
147842 addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
147844 if( p->iOffset ){
147846 p->iLimit, p->iOffset+1, p->iOffset);
147853 pDelete = p->pPrior;
147854 p->pPrior = pPrior;
147855 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
147856 if( p->pLimit
147857 && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit, pParse)
147858 && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
147860 p->nSelectRow = sqlite3LogEst((u64)nLimit);
147872 Expr *pLimit; /* Saved values of p->nLimit */
147876 testcase( p->op==TK_EXCEPT );
147877 testcase( p->op==TK_UNION );
147883 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
147889 unionTab = pParse->nTab++;
147890 assert( p->pOrderBy==0 );
147892 assert( p->addrOpenEphm[0] == -1 );
147893 p->addrOpenEphm[0] = addr;
147894 findRightmost(p)->selFlags |= SF_UsesEphemeral;
147895 assert( p->pEList );
147901 assert( !pPrior->pOrderBy );
147911 if( p->op==TK_EXCEPT ){
147914 assert( p->op==TK_UNION );
147917 p->pPrior = 0;
147918 pLimit = p->pLimit;
147919 p->pLimit = 0;
147921 ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
147922 sqlite3SelectOpName(p->op)));
147926 assert( p->pOrderBy==0 );
147927 pDelete = p->pPrior;
147928 p->pPrior = pPrior;
147929 p->pOrderBy = 0;
147930 if( p->op==TK_UNION ){
147931 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
147933 sqlite3ExprDelete(db, p->pLimit);
147934 p->pLimit = pLimit;
147935 p->iLimit = 0;
147936 p->iOffset = 0;
147942 assert( p->pEList || db->mallocFailed );
147943 if( dest.eDest!=priorOp && db->mallocFailed==0 ){
147959 default: assert( p->op==TK_INTERSECT ); {
147971 tab1 = pParse->nTab++;
147972 tab2 = pParse->nTab++;
147973 assert( p->pOrderBy==0 );
147976 assert( p->addrOpenEphm[0] == -1 );
147977 p->addrOpenEphm[0] = addr;
147978 findRightmost(p)->selFlags |= SF_UsesEphemeral;
147979 assert( p->pEList );
147993 assert( p->addrOpenEphm[1] == -1 );
147994 p->addrOpenEphm[1] = addr;
147995 p->pPrior = 0;
147996 pLimit = p->pLimit;
147997 p->pLimit = 0;
147999 ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
148000 sqlite3SelectOpName(p->op)));
148004 pDelete = p->pPrior;
148005 p->pPrior = pPrior;
148006 if( p->nSelectRow>pPrior->nSelectRow ){
148007 p->nSelectRow = pPrior->nSelectRow;
148009 sqlite3ExprDelete(db, p->pLimit);
148010 p->pLimit = pLimit;
148016 assert( p->pEList );
148038 if( p->pNext==0 ){
148043 if( pParse->nErr ) goto multi_select_end;
148049 ** This section is run by the right-most SELECT statement only.
148050 ** SELECT statements to the left always skip this part. The right-most
148054 if( p->selFlags & SF_UsesEphemeral ){
148058 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
148061 assert( p->pNext==0 );
148062 assert( p->pEList!=0 );
148063 nCol = p->pEList->nExpr;
148069 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
148072 *apColl = db->pDfltColl;
148076 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
148078 int addr = pLoop->addrOpenEphm[i];
148082 assert( pLoop->addrOpenEphm[1]<0 );
148088 pLoop->addrOpenEphm[i] = -1;
148095 pDest->iSdst = dest.iSdst;
148096 pDest->nSdst = dest.nSdst;
148097 pDest->iSDParm2 = dest.iSDParm2;
148110 if( p->selFlags & SF_Values ){
148115 sqlite3SelectOpName(p->op));
148120 ** Code an output subroutine for a coroutine implementation of a
148123 ** The data to be output is contained in pIn->iSdst. There are
148124 ** pIn->nSdst columns to be output. pDest is where the output should
148136 ** If the LIMIT found in p->iLimit is reached, jump immediately to
148149 Vdbe *v = pParse->pVdbe;
148161 addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
148165 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
148168 if( pParse->db->mallocFailed ) return 0;
148170 /* Suppress the first OFFSET entries if there is an OFFSET clause
148172 codeOffset(v, p->iOffset, iContinue);
148174 assert( pDest->eDest!=SRT_Exists );
148175 assert( pDest->eDest!=SRT_Table );
148176 switch( pDest->eDest ){
148182 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
148183 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
148184 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
148192 /* If we are creating a set for an "expr IN (SELECT ...)".
148196 testcase( pIn->nSdst>1 );
148198 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
148199 r1, pDest->zAffSdst, pIn->nSdst);
148200 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
148201 pIn->iSdst, pIn->nSdst);
148202 if( pDest->iSDParm2>0 ){
148203 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0,
148204 pIn->iSdst, pIn->nSdst);
148211 /* If this is a scalar select that is part of an expression, then
148214 ** if it is the RHS of a row-value IN operator.
148217 testcase( pIn->nSdst>1 );
148218 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
148225 ** starting at pDest->iSdst. Then the co-routine yields.
148228 if( pDest->iSdst==0 ){
148229 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
148230 pDest->nSdst = pIn->nSdst;
148232 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
148233 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
148246 assert( pDest->eDest==SRT_Output );
148247 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
148254 if( p->iLimit ){
148255 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
148268 ** is an ORDER BY clause.
148276 ** co-routines. Then run the co-routines in parallel and merge the results
148303 ** ------------- ----------------- -------------- -----------------
148314 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
148315 ** causes an immediate jump to EofA and an EOF on B following nextB causes
148316 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
148354 Select *p, /* The right-most of SELECTs to be coded */
148359 Select *pSplit; /* Left-most SELECT in the right-hand group */
148364 int regAddrA; /* Address register for select-A coroutine */
148365 int regAddrB; /* Address register for select-B coroutine */
148366 int addrSelectA; /* Address of the select-A coroutine */
148367 int addrSelectB; /* Address of the select-B coroutine */
148368 int regOutA; /* Address register for the output-A subroutine */
148369 int regOutB; /* Address register for the output-B subroutine */
148370 int addrOutA; /* Address of the output-A subroutine */
148371 int addrOutB = 0; /* Address of the output-B subroutine */
148372 int addrEofA; /* Address of the select-A-exhausted subroutine */
148374 int addrEofB; /* Address of the select-B-exhausted subroutine */
148378 int regLimitA; /* Limit register for select-A */
148379 int regLimitB; /* Limit register for select-A */
148381 int savedLimit; /* Saved value of p->iLimit */
148382 int savedOffset; /* Saved value of p->iOffset */
148394 assert( p->pOrderBy!=0 );
148396 db = pParse->db;
148397 v = pParse->pVdbe;
148405 op = p->op;
148406 assert( p->pPrior->pOrderBy==0 );
148407 pOrderBy = p->pOrderBy;
148409 nOrderBy = pOrderBy->nExpr;
148416 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
148418 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
148420 assert( pItem->u.x.iOrderByCol>0 );
148421 if( pItem->u.x.iOrderByCol==i ) break;
148426 pNew->flags |= EP_IntValue;
148427 pNew->u.iValue = i;
148428 p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
148429 if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
148445 for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
148447 assert( pItem->u.x.iOrderByCol>0 );
148448 assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
148449 aPermute[i] = pItem->u.x.iOrderByCol - 1;
148463 int nExpr = p->pEList->nExpr;
148464 assert( nOrderBy>=nExpr || db->mallocFailed );
148465 regPrev = pParse->nMem+1;
148466 pParse->nMem += nExpr+1;
148472 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
148473 pKeyDup->aSortFlags[i] = 0;
148484 for(pSplit=p; pSplit->pPrior!=0 && pSplit->op==op; pSplit=pSplit->pPrior){
148486 assert( pSplit->pPrior->pNext==pSplit );
148493 for(i=2; i<nSelect; i+=2){ pSplit = pSplit->pPrior; }
148495 pPrior = pSplit->pPrior;
148497 pSplit->pPrior = 0;
148498 pPrior->pNext = 0;
148499 assert( p->pOrderBy == pOrderBy );
148500 assert( pOrderBy!=0 || db->mallocFailed );
148501 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
148502 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
148503 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
148507 if( p->iLimit && op==TK_ALL ){
148508 regLimitA = ++pParse->nMem;
148509 regLimitB = ++pParse->nMem;
148510 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
148516 sqlite3ExprDelete(db, p->pLimit);
148517 p->pLimit = 0;
148519 regAddrA = ++pParse->nMem;
148520 regAddrB = ++pParse->nMem;
148521 regOutA = ++pParse->nMem;
148522 regOutB = ++pParse->nMem;
148526 ExplainQueryPlan((pParse, 1, "MERGE (%s)", sqlite3SelectOpName(p->op)));
148529 ** left of the compound operator - the "A" select.
148534 pPrior->iLimit = regLimitA;
148541 ** the right - the "B" select
148546 savedLimit = p->iLimit;
148547 savedOffset = p->iOffset;
148548 p->iLimit = regLimitB;
148549 p->iOffset = 0;
148552 p->iLimit = savedLimit;
148553 p->iOffset = savedOffset;
148581 VdbeNoopComment((v, "eof-A subroutine"));
148586 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
148594 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
148596 VdbeNoopComment((v, "eof-B subroutine"));
148604 VdbeNoopComment((v, "A-lt-B subroutine"));
148617 VdbeNoopComment((v, "A-eq-B subroutine"));
148625 VdbeNoopComment((v, "A-gt-B subroutine"));
148654 if( pSplit->pPrior ){
148655 sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pSplit->pPrior);
148657 pSplit->pPrior = pPrior;
148658 pPrior->pNext = pSplit;
148659 sqlite3ExprListDelete(db, pPrior->pOrderBy);
148660 pPrior->pOrderBy = 0;
148665 return pParse->nErr!=0;
148671 /* An instance of the SubstContext object describes an substitution edit
148680 ** position in the parent that NULL-able due to an OUTER JOIN. Either the
148685 ** Suppose the original expression is an integer constant. Even though the table
148686 ** has the nullRow flag set, because the expression is an integer constant,
148687 ** it will not be NULLed out. So instead, we insert an OP_IfNullRow opcode
148703 ** when processing a non-matched row of the left.
148720 ** a column in table number iTable with a copy of the iColumn-th
148737 && pExpr->w.iJoin==pSubst->iTable
148740 pExpr->w.iJoin = pSubst->iNewTable;
148742 if( pExpr->op==TK_COLUMN
148743 && pExpr->iTable==pSubst->iTable
148747 if( pExpr->iColumn<0 ){
148748 pExpr->op = TK_NULL;
148756 iColumn = pExpr->iColumn;
148758 assert( pSubst->pEList!=0 && iColumn<pSubst->pEList->nExpr );
148759 assert( pExpr->pRight==0 );
148760 pCopy = pSubst->pEList->a[iColumn].pExpr;
148762 sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
148764 sqlite3 *db = pSubst->pParse->db;
148765 if( pSubst->isOuterJoin
148766 && (pCopy->op!=TK_COLUMN || pCopy->iTable!=pSubst->iNewTable)
148771 ifNullRow.iTable = pSubst->iNewTable;
148772 ifNullRow.iColumn = -99;
148778 if( db->mallocFailed ){
148782 if( pSubst->isOuterJoin ){
148785 if( pNew->op==TK_TRUEFALSE ){
148786 pNew->u.iValue = sqlite3ExprTruthValue(pNew);
148787 pNew->op = TK_INTEGER;
148791 /* Ensure that the expression now has an implicit collation sequence,
148792 ** just as it did when it was a column of a view or sub-query. */
148794 CollSeq *pNat = sqlite3ExprCollSeq(pSubst->pParse, pNew);
148795 CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse,
148796 pSubst->pCList->a[iColumn].pExpr
148798 if( pNat!=pColl || (pNew->op!=TK_COLUMN && pNew->op!=TK_COLLATE) ){
148799 pNew = sqlite3ExprAddCollateString(pSubst->pParse, pNew,
148800 (pColl ? pColl->zName : "BINARY")
148806 sqlite3SetJoinExpr(pNew, pExpr->w.iJoin,
148807 pExpr->flags & (EP_OuterON|EP_InnerON));
148814 if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
148815 pExpr->iTable = pSubst->iNewTable;
148817 pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
148818 pExpr->pRight = substExpr(pSubst, pExpr->pRight);
148820 substSelect(pSubst, pExpr->x.pSelect, 1);
148822 substExprList(pSubst, pExpr->x.pList);
148826 Window *pWin = pExpr->y.pWin;
148827 pWin->pFilter = substExpr(pSubst, pWin->pFilter);
148828 substExprList(pSubst, pWin->pPartition);
148829 substExprList(pSubst, pWin->pOrderBy);
148841 for(i=0; i<pList->nExpr; i++){
148842 pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
148848 int doPrior /* Do substitutes on p->pPrior too */
148855 substExprList(pSubst, p->pEList);
148856 substExprList(pSubst, p->pGroupBy);
148857 substExprList(pSubst, p->pOrderBy);
148858 p->pHaving = substExpr(pSubst, p->pHaving);
148859 p->pWhere = substExpr(pSubst, p->pWhere);
148860 pSrc = p->pSrc;
148862 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
148863 if( pItem->fg.isSubquery ){
148864 substSelect(pSubst, pItem->u4.pSubq->pSelect, 1);
148866 if( pItem->fg.isTabFunc ){
148867 substExprList(pSubst, pItem->u1.pFuncArg);
148870 }while( doPrior && (p = p->pPrior)!=0 );
148880 ** pSrcItem->colUsed mask.
148884 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
148885 pItem = pWalker->u.pSrcItem;
148886 if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
148887 if( pExpr->iColumn<0 ) return WRC_Continue;
148888 pItem->colUsed |= sqlite3ExprColUsed(pExpr);
148896 if( NEVER(pSrcItem->pSTab==0) ) return;
148901 pSrcItem->colUsed = 0;
148909 ** new cursor number assigned, set an entry in the aCsrMap[] array
148917 ** If pSrc contains any sub-selects, call this routine recursively
148918 ** on the FROM clause of each such sub-select, with iExcept set to -1.
148928 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
148931 assert( pItem->iCursor < aCsrMap[0] );
148932 if( !pItem->fg.isRecursive || aCsrMap[pItem->iCursor+1]==0 ){
148933 aCsrMap[pItem->iCursor+1] = pParse->nTab++;
148935 pItem->iCursor = aCsrMap[pItem->iCursor+1];
148936 if( pItem->fg.isSubquery ){
148937 for(p=pItem->u4.pSubq->pSelect; p; p=p->pPrior){
148938 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1);
148949 int *aCsrMap = pWalker->u.aiCol;
148961 int op = pExpr->op;
148963 renumberCursorDoMapping(pWalker, &pExpr->iTable);
148966 renumberCursorDoMapping(pWalker, &pExpr->w.iJoin);
148974 ** cursor in the FROM clause of any FROM clause sub-selects, recursively.
148979 ** Argument aCsrMap is an array that may be used for temporary working
148983 ** select statement passed as an argument, and
148996 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, iExcept);
149011 while( pSel->pPrior ){
149012 pSel = pSel->pPrior;
149014 return pSel->pEList;
149018 ** Return true if any of the result-set columns in the compound query
149025 assert( p->pEList!=0 );
149026 assert( p->pPrior!=0 );
149027 pList = p->pEList;
149028 for(ii=0; ii<pList->nExpr; ii++){
149031 assert( pList->a[ii].pExpr!=0 );
149032 aff = sqlite3ExprAffinity(pList->a[ii].pExpr);
149033 for(pSub1=p->pPrior; pSub1; pSub1=pSub1->pPrior){
149034 assert( pSub1->pEList!=0 );
149035 assert( pSub1->pEList->nExpr>ii );
149036 assert( pSub1->pEList->a[ii].pExpr!=0 );
149037 if( sqlite3ExprAffinity(pSub1->pEList->a[ii].pExpr)!=aff ){
149078 ** (2) If the subquery is an aggregate then
149081 ** other than the one FROM-clause subquery that is a candidate
149083 ** from 2015-02-09.)
149097 ** sub-queries that were excluded from this optimization. Restriction
149112 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
149113 ** accidentally carried the comment forward until 2014-09-15. Original
149150 ** The parent and sub-query may contain WHERE clauses. Subject to
149154 ** operators have an implied DISTINCT which is disallowed by
149157 ** Also, each component of the sub-query must return the same number
149160 ** such (illegal) sub-query is flattened. The caller will detect the
149163 ** (18) If the sub-query is a compound select, then all terms of the
149170 ** (20) If the sub-query is a compound select, then it must not use
149171 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
149181 ** (23) If the outer query is a recursive CTE, then the sub-query may not be
149187 ** The subquery may not be an aggregate that uses the built-in min() or
149210 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
149213 ** If flattening is not attempted, this routine is a no-op and returns 0.
149222 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
149225 const char *zSavedAuthContext = pParse->zAuthContext;
149228 Select *pSub1; /* Pointer to the rightmost select in sub-query */
149232 int iNewParent = -1;/* Replacement table for iParent */
149237 sqlite3 *db = pParse->db;
149244 assert( p->pPrior==0 );
149246 pSrc = p->pSrc;
149247 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
149248 pSubitem = &pSrc->a[iFrom];
149249 iParent = pSubitem->iCursor;
149250 assert( pSubitem->fg.isSubquery );
149251 pSub = pSubitem->u4.pSubq->pSelect;
149255 if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
149258 pSubSrc = pSub->pSrc;
149262 ** because they could be computed at compile-time. But when LIMIT and OFFSET
149265 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
149266 if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
149267 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
149270 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
149271 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
149272 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
149275 if( p->pOrderBy && pSub->pOrderBy ){
149278 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
149279 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
149280 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
149283 if( pSub->selFlags & (SF_Recursive) ){
149302 if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){
149303 if( pSubSrc->nSrc>1 /* (3a) */
149304 /**** || IsVirtual(pSubSrc->a[0].pSTab) (3b)-omitted */
149305 || (p->selFlags & SF_Distinct)!=0 /* (3d) */
149306 || (pSubitem->fg.jointype & JT_RIGHT)!=0 /* (26) */
149313 assert( pSubSrc->nSrc>0 ); /* True by restriction (7) */
149314 if( iFrom>0 && (pSubSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
149319 assert( !pSubitem->fg.isCte || pSubitem->u2.pCteUse->eM10d!=M10d_Yes );
149321 /* Restriction (17): If the sub-query is a compound SELECT, then it must
149326 if( pSub->pPrior ){
149328 if( pSub->pOrderBy ){
149331 if( isAgg || (p->selFlags & SF_Distinct)!=0 || isOuterJoin>0 ){
149334 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
149335 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
149336 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
149337 assert( pSub->pSrc!=0 );
149338 assert( (pSub->selFlags & SF_Recursive)==0 );
149339 assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
149340 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
149341 || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
149342 || pSub1->pSrc->nSrc<1 /* (17c) */
149344 || pSub1->pWin /* (17e) */
149349 if( iFrom>0 && (pSub1->pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
149351 ** omitted on left-hand tables of the right join that is being
149355 testcase( pSub1->pSrc->nSrc>1 );
149359 if( p->pOrderBy ){
149360 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
149361 if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
149366 if( (p->selFlags & SF_Recursive) ) return 0;
149371 if( pSrc->nSrc>1 ){
149372 if( pParse->nSelect>500 ) return 0;
149374 aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
149375 if( aCsrMap ) aCsrMap[0] = pParse->nTab;
149381 pSub->selId, pSub, iFrom));
149384 pParse->zAuthContext = pSubitem->zName;
149387 pParse->zAuthContext = zSavedAuthContext;
149391 if( ALWAYS(pSubitem->fg.isSubquery) ){
149396 assert( pSubitem->fg.isSubquery==0 );
149397 assert( pSubitem->fg.fixedSchema==0 );
149398 sqlite3DbFree(db, pSubitem->zName);
149399 sqlite3DbFree(db, pSubitem->zAlias);
149400 pSubitem->zName = 0;
149401 pSubitem->zAlias = 0;
149402 assert( pSubitem->fg.isUsing!=0 || pSubitem->u3.pOn==0 );
149404 /* If the sub-query is a compound SELECT statement, then (by restrictions
149408 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
149411 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
149412 ** OFFSET clauses and joins them to the left-hand-side of the original
149414 ** select statements in the compound sub-query.
149435 ** We call this the "compound-subquery flattening".
149437 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
149439 ExprList *pOrderBy = p->pOrderBy;
149440 Expr *pLimit = p->pLimit;
149441 Select *pPrior = p->pPrior;
149442 Table *pItemTab = pSubitem->pSTab;
149443 pSubitem->pSTab = 0;
149444 p->pOrderBy = 0;
149445 p->pPrior = 0;
149446 p->pLimit = 0;
149448 p->pLimit = pLimit;
149449 p->pOrderBy = pOrderBy;
149450 p->op = TK_ALL;
149451 pSubitem->pSTab = pItemTab;
149453 p->pPrior = pPrior;
149455 pNew->selId = ++pParse->nSelect;
149456 if( aCsrMap && ALWAYS(db->mallocFailed==0) ){
149459 pNew->pPrior = pPrior;
149460 if( pPrior ) pPrior->pNext = pNew;
149461 pNew->pNext = p;
149462 p->pPrior = pNew;
149463 TREETRACE(0x4,pParse,p,("compound-subquery flattener"
149464 " creates %u as peer\n",pNew->selId));
149466 assert( pSubitem->fg.isSubquery==0 );
149469 if( db->mallocFailed ){
149470 assert( pSubitem->fg.fixedSchema==0 );
149471 assert( pSubitem->fg.isSubquery==0 );
149472 assert( pSubitem->u4.zDatabase==0 );
149482 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
149484 if( ALWAYS(pSubitem->pSTab!=0) ){
149485 Table *pTabToDel = pSubitem->pSTab;
149486 if( pTabToDel->nTabRef==1 ){
149489 testcase( pToplevel->earlyCleanup );
149491 pTabToDel->nTabRef--;
149493 pSubitem->pSTab = 0;
149496 /* The following loop runs once for each term in a compound-subquery
149498 ** of flattening - a flattening other than a compound-subquery flattening -
149510 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
149513 u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ;
149515 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
149516 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
149517 pSrc = pParent->pSrc; /* FROM clause of the outer query */
149520 jointype = pSubitem->fg.jointype; /* First time through the loop */
149539 pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
149541 pParent->pSrc = pSrc;
149547 iNewParent = pSubSrc->a[0].iCursor;
149549 SrcItem *pItem = &pSrc->a[i+iFrom];
149550 assert( pItem->fg.isTabFunc==0 );
149551 assert( pItem->fg.isSubquery
149552 || pItem->fg.fixedSchema
149553 || pItem->u4.zDatabase==0 );
149554 if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing);
149555 *pItem = pSubSrc->a[i];
149556 pItem->fg.jointype |= ltorj;
149557 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
149559 pSrc->a[iFrom].fg.jointype &= JT_LTORJ;
149560 pSrc->a[iFrom].fg.jointype |= jointype | ltorj;
149574 if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){
149575 /* At this point, any non-zero iOrderByCol values indicate that the
149581 ** Not doing this may cause an error if a subsequent call to this
149582 ** function attempts to flatten a compound sub-query into pParent
149583 ** (the only way this can happen is if the compound sub-query is
149584 ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
149585 ExprList *pOrderBy = pSub->pOrderBy;
149586 for(i=0; i<pOrderBy->nExpr; i++){
149587 pOrderBy->a[i].u.x.iOrderByCol = 0;
149589 assert( pParent->pOrderBy==0 );
149590 pParent->pOrderBy = pOrderBy;
149591 pSub->pOrderBy = 0;
149593 pWhere = pSub->pWhere;
149594 pSub->pWhere = 0;
149596 assert( pSubSrc->nSrc==1 );
149600 if( pParent->pWhere ){
149601 pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
149603 pParent->pWhere = pWhere;
149606 if( db->mallocFailed==0 ){
149612 x.pEList = pSub->pEList;
149619 pParent->selFlags |= pSub->selFlags & SF_Compound;
149620 assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
149628 if( pSub->pLimit ){
149629 pParent->pLimit = pSub->pLimit;
149630 pSub->pLimit = 0;
149636 recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
149664 u8 *pOomFault; /* Pointer to pParse->db->mallocFailed */
149688 assert( pColumn->op==TK_COLUMN );
149689 assert( sqlite3ExprIsConstant(pConst->pParse, pValue) );
149693 if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
149697 /* 2018-10-25 ticket [cf5ed20f]
149699 for(i=0; i<pConst->nConst; i++){
149700 const Expr *pE2 = pConst->apExpr[i*2];
149701 assert( pE2->op==TK_COLUMN );
149702 if( pE2->iTable==pColumn->iTable
149703 && pE2->iColumn==pColumn->iColumn
149710 pConst->bHasAffBlob = 1;
149713 pConst->nConst++;
149714 pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
149715 pConst->nConst*2*sizeof(Expr*));
149716 if( pConst->apExpr==0 ){
149717 pConst->nConst = 0;
149719 pConst->apExpr[pConst->nConst*2-2] = pColumn;
149720 pConst->apExpr[pConst->nConst*2-1] = pValue;
149727 ** is part of the AND-connected terms of the expression. For each term
149733 if( ExprHasProperty(pExpr, pConst->mExcludeOn) ){
149738 if( pExpr->op==TK_AND ){
149739 findConstInWhere(pConst, pExpr->pRight);
149740 findConstInWhere(pConst, pExpr->pLeft);
149743 if( pExpr->op!=TK_EQ ) return;
149744 pRight = pExpr->pRight;
149745 pLeft = pExpr->pLeft;
149748 if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pConst->pParse, pLeft) ){
149751 if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pConst->pParse, pRight) ){
149760 ** pExpr is equivalent to one of the columns named in pWalker->u.pConst,
149762 ** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr
149771 if( pConst->pOomFault[0] ) return WRC_Prune;
149772 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
149773 if( ExprHasProperty(pExpr, EP_FixedCol|pConst->mExcludeOn) ){
149779 for(i=0; i<pConst->nConst; i++){
149780 Expr *pColumn = pConst->apExpr[i*2];
149782 if( pColumn->iTable!=pExpr->iTable ) continue;
149783 if( pColumn->iColumn!=pExpr->iColumn ) continue;
149789 pConst->nChng++;
149792 assert( pExpr->pLeft==0 );
149793 pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
149794 if( pConst->pParse->db->mallocFailed ) return WRC_Prune;
149803 ** any substitutions based on the contents of pWalker->u.pConst should
149808 ** + pExpr is a column with an affinity other than BLOB that matches
149809 ** one of the columns in pWalker->u.pConst, or
149812 ** uses an affinity other than TEXT and one of its immediate
149814 ** pWalker->u.pConst.
149817 WhereConst *pConst = pWalker->u.pConst;
149822 if( pConst->bHasAffBlob ){
149823 if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
149824 || pExpr->op==TK_IS
149826 propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
149827 if( pConst->pOomFault[0] ) return WRC_Prune;
149828 if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
149829 propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
149833 return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob);
149837 ** The WHERE-clause constant propagation optimization.
149840 ** CONSTANT=COLUMN that are top-level AND-connected terms that are not
149872 ** 2021-05-25 forum post 6a06202608: Another troublesome case is...
149895 x.pOomFault = &pParse->db->mallocFailed;
149901 if( ALWAYS(p->pSrc!=0)
149902 && p->pSrc->nSrc>0
149903 && (p->pSrc->a[0].fg.jointype & JT_LTORJ)!=0
149912 findConstInWhere(&x, p->pWhere);
149921 sqlite3WalkExpr(&w, p->pWhere);
149922 sqlite3DbFree(x.pParse->db, x.apExpr);
149933 ** push WHERE clause expression pExpr down to FROM clause sub-query
149940 ** BY clause of all window function used by the sub-query. It is safe
149946 ** * the sub-query uses only one distinct window frame, and
149950 assert( pSubq->pWin->pPartition );
149951 assert( (pSubq->selFlags & SF_MultiPart)==0 );
149952 assert( pSubq->pPrior==0 );
149953 return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition);
149963 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
149967 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
149975 ** This optimization is called the "WHERE-clause push-down optimization"
149976 ** or sometimes the "predicate push-down optimization".
149979 ** with a similar name: The "MySQL push-down optimization" causes WHERE
149988 ** (1) (** This restriction was removed on 2017-09-29. We used to
150006 ** of a LEFT JOIN where iCursor is not the right-hand table of that
150007 ** left join. An example:
150025 ** (6b) The inner query is a compound and uses window-functions.
150029 ** all window-functions used by the sub-query. It is safe to
150031 ** window over which any window-function is calculated.
150044 ** of a join (either an INNER or an OUTER join), and
150051 ** Without this restriction, the WHERE-clause push-down optimization
150056 ** (10) The inner query is not the right-hand table of a RIGHT JOIN.
150064 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
150077 pSrc = &pSrcList->a[iSrc];
150079 if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ){
150082 if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ){
150086 if( pSubq->pPrior ){
150089 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
150090 u8 op = pSel->op;
150097 if( pSel->pWin ) return 0; /* restriction (6b) */
150103 ** non-BINARY collating sequence. */
150104 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
150106 const ExprList *pList = pSel->pEList;
150108 for(ii=0; ii<pList->nExpr; ii++){
150109 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[ii].pExpr);
150118 if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0;
150129 for(pX=pSubq; pX; pX=pX->pPrior){
150130 assert( (pX->selFlags & (SF_Recursive))==0 );
150135 if( pSubq->pLimit!=0 ){
150138 while( pWhere->op==TK_AND ){
150139 nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrcList, iSrc);
150140 pWhere = pWhere->pLeft;
150145 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (9c) */
150149 if( pWhere->w.iJoin==pSrcList->a[jj].iCursor ){
150154 if( (pSrcList->a[jj].fg.jointype & JT_RIGHT)!=0 ){
150163 || pWhere->w.iJoin!=iCursor)
150168 && pWhere->w.iJoin!=iCursor
150175 if( ViewCanHaveRowid && (pWhere->op==TK_ISNULL || pWhere->op==TK_NOTNULL) ){
150176 Expr *pLeft = pWhere->pLeft;
150178 && pLeft->op==TK_COLUMN
150179 && pLeft->iColumn < 0
150188 pSubq->selFlags |= SF_PushDown;
150191 pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
150192 unsetJoinExpr(pNew, -1, 1);
150194 x.iTable = pSrc->iCursor;
150195 x.iNewTable = pSrc->iCursor;
150197 x.pEList = pSubq->pEList;
150201 if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){
150202 /* Restriction 6c has prevented push-down in this case */
150203 sqlite3ExprDelete(pParse->db, pNew);
150204 nChng--;
150208 if( pSubq->selFlags & SF_Aggregate ){
150209 pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
150211 pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
150213 pSubq = pSubq->pPrior;
150221 ** Check to see if a subquery contains result-set columns that are
150222 ** never used. If it does, change the value of those result-set columns
150237 if( pItem->fg.isCorrelated || pItem->fg.isCte ){
150240 assert( pItem->pSTab!=0 );
150241 pTab = pItem->pSTab;
150242 assert( pItem->fg.isSubquery );
150243 pSub = pItem->u4.pSubq->pSelect;
150244 assert( pSub->pEList->nExpr==pTab->nCol );
150245 for(pX=pSub; pX; pX=pX->pPrior){
150246 if( (pX->selFlags & (SF_Distinct|SF_Aggregate))!=0 ){
150247 testcase( pX->selFlags & SF_Distinct );
150248 testcase( pX->selFlags & SF_Aggregate );
150251 if( pX->pPrior && pX->op!=TK_ALL ){
150257 if( pX->pWin ){
150264 colUsed = pItem->colUsed;
150265 if( pSub->pOrderBy ){
150266 ExprList *pList = pSub->pOrderBy;
150267 for(j=0; j<pList->nExpr; j++){
150268 u16 iCol = pList->a[j].u.x.iOrderByCol;
150270 iCol--;
150271 colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
150275 nCol = pTab->nCol;
150277 Bitmask m = j<BMS-1 ? MASKBIT(j) : TOPBIT;
150279 for(pX=pSub; pX; pX=pX->pPrior) {
150280 Expr *pY = pX->pEList->a[j].pExpr;
150281 if( pY->op==TK_NULL ) continue;
150282 pY->op = TK_NULL;
150284 pX->selFlags |= SF_PushDown;
150297 ** *ppMinMax to be an ORDER BY clause to be used for the optimization
150316 assert( pFunc->op==TK_AGG_FUNCTION );
150319 pEList = pFunc->x.pList;
150321 || pEList->nExpr!=1
150328 zFunc = pFunc->u.zToken;
150331 if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
150341 assert( pOrderBy!=0 || db->mallocFailed );
150342 if( pOrderBy ) pOrderBy->a[0].fg.sortFlags = sortFlags;
150347 ** The select statement passed as the first argument is an aggregate query.
150348 ** The second argument is the associated aggregate-info object. This
150353 ** where table is a database table, not a sub-select or view. If the query
150367 assert( !p->pGroupBy );
150369 if( p->pWhere
150370 || p->pEList->nExpr!=1
150371 || p->pSrc->nSrc!=1
150372 || p->pSrc->a[0].fg.isSubquery
150373 || pAggInfo->nFunc!=1
150374 || p->pHaving
150378 pTab = p->pSrc->a[0].pSTab;
150382 pExpr = p->pEList->a[0].pExpr;
150384 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
150385 if( pExpr->pAggInfo!=pAggInfo ) return 0;
150386 if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
150387 assert( pAggInfo->aFunc[0].pFExpr==pExpr );
150396 ** If the source-list item passed as an argument was augmented with an
150399 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
150400 ** pFrom->pIndex and return SQLITE_OK.
150403 Table *pTab = pFrom->pSTab;
150404 char *zIndexedBy = pFrom->u1.zIndexedBy;
150407 assert( pFrom->fg.isIndexedBy!=0 );
150409 for(pIdx=pTab->pIndex;
150410 pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
150411 pIdx=pIdx->pNext
150415 pParse->checkSchema = 1;
150418 assert( pFrom->fg.isCte==0 );
150419 pFrom->u2.pIBIndex = pIdx;
150424 ** Detect compound SELECT statements that use an ORDER BY clause with
150425 ** an alternative collating sequence.
150435 ** above that generates the code for a compound SELECT with an ORDER BY clause
150454 if( p->pPrior==0 ) return WRC_Continue;
150455 if( p->pOrderBy==0 ) return WRC_Continue;
150456 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
150458 a = p->pOrderBy->a;
150460 /* If iOrderByCol is already non-zero, then it has already been matched
150462 ** SELECT is rewritten for window-functions processing and then passed
150467 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
150468 if( a[i].pExpr->flags & EP_Collate ) break;
150474 pParse = pWalker->pParse;
150475 db = pParse->db;
150480 assert( pNewSrc!=0 || pParse->nErr );
150481 if( pParse->nErr ){
150486 p->pSrc = pNewSrc;
150487 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
150488 p->op = TK_SELECT;
150489 p->pWhere = 0;
150490 pNew->pGroupBy = 0;
150491 pNew->pHaving = 0;
150492 pNew->pOrderBy = 0;
150493 p->pPrior = 0;
150494 p->pNext = 0;
150495 p->pWith = 0;
150497 p->pWinDefn = 0;
150499 p->selFlags &= ~(u32)SF_Compound;
150500 assert( (p->selFlags & SF_Converted)==0 );
150501 p->selFlags |= SF_Converted;
150502 assert( pNew->pPrior!=0 );
150503 pNew->pPrior->pNext = pNew;
150504 pNew->pLimit = 0;
150509 ** Check to see if the FROM clause term pFrom has table-valued function
150510 ** arguments. If it does, leave an error message in pParse and return
150511 ** non-zero, since pFrom is not allowed to be a table-valued function.
150514 if( pFrom->fg.isTabFunc ){
150515 sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
150525 ** FROM clause element pItem is really a common-table-expression (CTE)
150529 ** If a non-NULL value is returned, set *ppContext to point to the With
150537 const char *zName = pItem->zName;
150539 assert( pItem->fg.fixedSchema || pItem->u4.zDatabase==0 );
150541 for(p=pWith; p; p=p->pOuter){
150543 for(i=0; i<p->nCte; i++){
150544 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
150546 return &p->a[i];
150549 if( p->bView ) break;
150555 ** with the inner-most WITH clause being at the top of the stack.
150565 ** the pWith object is destroyed immediately due to an OOM condition,
150578 if( pParse->nErr==0 ){
150579 assert( pParse->pWith!=pWith );
150580 pWith->pOuter = pParse->pWith;
150581 pParse->pWith = pWith;
150590 ** pParse->pWith linked list). And if currently processing a CTE
150594 ** If pFrom matches a CTE according to either of these two above, pFrom->pTab
150599 ** Return 2 if an error condition is detected.
150609 assert( pFrom->pSTab==0 );
150610 if( pParse->pWith==0 ){
150614 if( pParse->nErr ){
150615 /* Prior errors might have left pParse->pWith in a goofy state, so
150619 assert( pFrom->fg.hadSchema==0 || pFrom->fg.notCte!=0 );
150620 if( pFrom->fg.fixedSchema==0 && pFrom->u4.zDatabase!=0 ){
150625 if( pFrom->fg.notCte ){
150629 ** (2) This is the first term in the FROM clause of an UPDATE.
150633 pCte = searchWith(pParse->pWith, pFrom, &pWith);
150635 sqlite3 *db = pParse->db;
150639 Select *pLeft; /* Left-most SELECT statement */
150640 Select *pRecTerm; /* Left-most recursive term */
150642 With *pSavedWith; /* Initial value of pParse->pWith */
150643 int iRecTab = -1; /* Cursor for recursive table */
150646 /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
150647 ** recursive reference to CTE pCte. Leave an error in pParse and return
150648 ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
150650 if( pCte->zCteErr ){
150651 sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
150656 assert( pFrom->pSTab==0 );
150659 pCteUse = pCte->pUse;
150661 pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0]));
150668 pCteUse->eM10d = pCte->eM10d;
150670 pFrom->pSTab = pTab;
150671 pTab->nTabRef = 1;
150672 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
150673 pTab->iPKey = -1;
150674 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
150675 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
150676 sqlite3SrcItemAttachSubquery(pParse, pFrom, pCte->pSelect, 1);
150677 if( db->mallocFailed ) return 2;
150678 assert( pFrom->fg.isSubquery && pFrom->u4.pSubq );
150679 pSel = pFrom->u4.pSubq->pSelect;
150681 pSel->selFlags |= SF_CopyCte;
150682 if( pFrom->fg.isIndexedBy ){
150683 sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy);
150686 assert( !pFrom->fg.isIndexedBy );
150687 pFrom->fg.isCte = 1;
150688 pFrom->u2.pCteUse = pCteUse;
150689 pCteUse->nUse++;
150693 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
150694 while( bMayRecursive && pRecTerm->op==pSel->op ){
150696 SrcList *pSrc = pRecTerm->pSrc;
150697 assert( pRecTerm->pPrior!=0 );
150698 for(i=0; i<pSrc->nSrc; i++){
150699 SrcItem *pItem = &pSrc->a[i];
150700 if( pItem->zName!=0
150701 && !pItem->fg.hadSchema
150702 && ALWAYS( !pItem->fg.isSubquery )
150703 && (pItem->fg.fixedSchema || pItem->u4.zDatabase==0)
150704 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
150706 pItem->pSTab = pTab;
150707 pTab->nTabRef++;
150708 pItem->fg.isRecursive = 1;
150709 if( pRecTerm->selFlags & SF_Recursive ){
150711 "multiple references to recursive table: %s", pCte->zName
150715 pRecTerm->selFlags |= SF_Recursive;
150716 if( iRecTab<0 ) iRecTab = pParse->nTab++;
150717 pItem->iCursor = iRecTab;
150720 if( (pRecTerm->selFlags & SF_Recursive)==0 ) break;
150721 pRecTerm = pRecTerm->pPrior;
150724 pCte->zCteErr = "circular reference: %s";
150725 pSavedWith = pParse->pWith;
150726 pParse->pWith = pWith;
150727 if( pSel->selFlags & SF_Recursive ){
150730 assert( (pRecTerm->selFlags & SF_Recursive)==0 );
150731 assert( pRecTerm->pNext!=0 );
150732 assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
150733 assert( pRecTerm->pWith==0 );
150734 pRecTerm->pWith = pSel->pWith;
150736 pRecTerm->pWith = 0;
150738 pParse->pWith = pSavedWith;
150743 pParse->pWith = pSavedWith;
150747 pParse->pWith = pWith;
150749 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
150750 pEList = pLeft->pEList;
150751 if( pCte->pCols ){
150752 if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
150754 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
150756 pParse->pWith = pSavedWith;
150759 pEList = pCte->pCols;
150762 sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
150764 if( pSel->selFlags & SF_Recursive ){
150765 pCte->zCteErr = "multiple recursive references: %s";
150767 pCte->zCteErr = "recursive reference in a subquery: %s";
150771 pCte->zCteErr = 0;
150772 pParse->pWith = pSavedWith;
150781 ** If the SELECT passed as the second argument has an associated WITH
150789 Parse *pParse = pWalker->pParse;
150790 if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
150791 With *pWith = findRightmost(p)->pWith;
150793 assert( pParse->pWith==pWith || pParse->nErr );
150794 pParse->pWith = pWith->pOuter;
150802 ** sub-query in the FROM clause of a SELECT statement. This function
150804 ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
150811 assert( pFrom->fg.isSubquery );
150812 assert( pFrom->u4.pSubq!=0 );
150813 pSel = pFrom->u4.pSubq->pSelect;
150815 pFrom->pSTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
150817 pTab->nTabRef = 1;
150818 if( pFrom->zAlias ){
150819 pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
150821 pTab->zName = sqlite3MPrintf(pParse->db, "%!S", pFrom);
150823 while( pSel->pPrior ){ pSel = pSel->pPrior; }
150824 sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
150825 pTab->iPKey = -1;
150826 pTab->eTabType = TABTYP_VIEW;
150827 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
150829 /* The usual case - do not allow ROWID on a subquery */
150830 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
150833 pTab->tabFlags |= TF_Ephemeral | sqlite3Config.mNoVisibleRowid;
150835 return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
150854 N--;
150856 if( pBase->fg.isUsing==0 ) continue;
150857 if( NEVER(pBase->u3.pUsing==0) ) continue;
150858 if( sqlite3IdListIndex(pBase->u3.pUsing, zName)>=0 ) return 1;
150871 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
150873 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
150889 Parse *pParse = pWalker->pParse;
150894 sqlite3 *db = pParse->db;
150896 u16 selFlags = p->selFlags;
150899 p->selFlags |= SF_Expanded;
150900 if( db->mallocFailed ){
150903 assert( p->pSrc!=0 );
150907 if( pWalker->eCode ){
150909 p->selId = ++pParse->nSelect;
150911 pTabList = p->pSrc;
150912 pEList = p->pEList;
150913 if( pParse->pWith && (p->selFlags & SF_View) ){
150914 if( p->pWith==0 ){
150915 p->pWith = (With*)sqlite3DbMallocZero(db, SZ_WITH(1) );
150916 if( p->pWith==0 ){
150920 p->pWith->bView = 1;
150922 sqlite3WithPush(pParse, p->pWith, 0);
150930 ** an entry of the FROM clause is a subquery instead of a table or view,
150933 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
150935 assert( pFrom->fg.isRecursive==0 || pFrom->pSTab!=0 );
150936 if( pFrom->pSTab ) continue;
150937 assert( pFrom->fg.isRecursive==0 );
150938 if( pFrom->zName==0 ){
150941 assert( pFrom->fg.isSubquery && pFrom->u4.pSubq!=0 );
150942 pSel = pFrom->u4.pSubq->pSelect;
150943 /* A sub-query in the FROM clause of a SELECT */
150945 assert( pFrom->pSTab==0 );
150952 pTab = pFrom->pSTab;
150956 /* An ordinary table or view name in the FROM clause */
150957 assert( pFrom->pSTab==0 );
150958 pFrom->pSTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
150960 if( pTab->nTabRef>=0xffff ){
150962 pTab->zName);
150963 pFrom->pSTab = 0;
150966 pTab->nTabRef++;
150973 u8 eCodeOrig = pWalker->eCode;
150975 assert( pFrom->fg.isSubquery==0 );
150977 if( (db->flags & SQLITE_EnableView)==0
150978 && pTab->pSchema!=db->aDb[1].pSchema
150981 pTab->zName);
150983 sqlite3SrcItemAttachSubquery(pParse, pFrom, pTab->u.view.pSelect, 1);
150987 && pFrom->fg.fromDDL
150988 && ALWAYS(pTab->u.vtab.p!=0)
150989 && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
150992 pTab->zName);
150996 nCol = pTab->nCol;
150997 pTab->nCol = -1;
150998 pWalker->eCode = 1; /* Turn on Select.selId renumbering */
150999 if( pFrom->fg.isSubquery ){
151000 sqlite3WalkSelect(pWalker, pFrom->u4.pSubq->pSelect);
151002 pWalker->eCode = eCodeOrig;
151003 pTab->nCol = nCol;
151009 if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){
151016 assert( db->mallocFailed==0 || pParse->nErr!=0 );
151017 if( pParse->nErr || sqlite3ProcessJoin(pParse, p) ){
151032 for(k=0; k<pEList->nExpr; k++){
151033 pE = pEList->a[k].pExpr;
151034 if( pE->op==TK_ASTERISK ) break;
151035 assert( pE->op!=TK_DOT || pE->pRight!=0 );
151036 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
151037 if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
151038 elistFlags |= pE->flags;
151040 if( k<pEList->nExpr ){
151046 struct ExprList_item *a = pEList->a;
151048 int flags = pParse->db->flags;
151052 for(k=0; k<pEList->nExpr; k++){
151054 elistFlags |= pE->flags;
151055 pRight = pE->pRight;
151056 assert( pE->op!=TK_DOT || pRight!=0 );
151057 if( pE->op!=TK_ASTERISK
151058 && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
151064 pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
151065 pNew->a[pNew->nExpr-1].fg.eEName = a[k].fg.eEName;
151075 if( pE->op==TK_DOT ){
151077 assert( pE->pLeft!=0 );
151078 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
151079 zTName = pE->pLeft->u.zToken;
151080 assert( ExprUseWOfst(pE->pLeft) );
151081 iErrOfst = pE->pRight->w.iOfst;
151084 iErrOfst = pE->w.iOfst;
151086 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
151088 Table *pTab = pFrom->pSTab; /* Table for this data source */
151089 ExprList *pNestedFrom; /* Result-set of a nested FROM clause */
151095 if( (zTabName = pFrom->zAlias)==0 ){
151096 zTabName = pTab->zName;
151098 if( db->mallocFailed ) break;
151099 assert( (int)pFrom->fg.isNestedFrom == IsNestedFrom(pFrom) );
151100 if( pFrom->fg.isNestedFrom ){
151101 assert( pFrom->fg.isSubquery && pFrom->u4.pSubq );
151102 assert( pFrom->u4.pSubq->pSelect!=0 );
151103 pNestedFrom = pFrom->u4.pSubq->pSelect->pEList;
151105 assert( pNestedFrom->nExpr==pTab->nCol );
151112 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
151113 zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
151115 if( i+1<pTabList->nSrc
151121 for(ii=0; ii<pUsing->nId; ii++){
151122 const char *zUName = pUsing->a[ii].zName;
151127 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
151128 assert( pX->zEName==0 );
151129 pX->zEName = sqlite3MPrintf(db,"..%s", zUName);
151130 pX->fg.eEName = ENAME_TAB;
151131 pX->fg.bUsingTerm = 1;
151138 nAdd = pTab->nCol;
151144 if( j==pTab->nCol ){
151148 zName = pTab->aCol[j].zCnName;
151150 /* If pTab is actually an SF_NestedFrom sub-select, do not
151152 if( pNestedFrom && pNestedFrom->a[j].fg.eEName==ENAME_ROWID ){
151158 && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0, 0)==0
151164 ** result-set list unless the SELECT has the SF_IncludeHidden
151167 if( (p->selFlags & SF_IncludeHidden)==0
151168 && IsHiddenColumn(&pTab->aCol[j])
151172 if( (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
151183 if( pFrom->fg.isUsing
151184 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0
151192 if( (pTabList->nSrc>1
151193 && ( (pFrom->fg.jointype & JT_LTORJ)==0
151195 || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1)
151203 if( IN_RENAME_OBJECT && pE->pLeft ){
151204 sqlite3RenameTokenRemap(pParse, pLeft, pE->pLeft);
151218 pX = &pNew->a[pNew->nExpr-1];
151219 assert( pX->zEName==0 );
151221 if( pNestedFrom && (!ViewCanHaveRowid || j<pNestedFrom->nExpr) ){
151222 assert( j<pNestedFrom->nExpr );
151223 pX->zEName = sqlite3DbStrDup(db, pNestedFrom->a[j].zEName);
151224 testcase( pX->zEName==0 );
151226 pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
151228 testcase( pX->zEName==0 );
151230 pX->fg.eEName = (j==pTab->nCol ? ENAME_ROWID : ENAME_TAB);
151231 if( (pFrom->fg.isUsing
151232 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0)
151234 || (j<pTab->nCol && (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND))
151236 pX->fg.bNoExpand = 1;
151239 pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
151240 pX->fg.eEName = ENAME_NAME;
151242 pX->zEName = sqlite3DbStrDup(db, zName);
151243 pX->fg.eEName = ENAME_NAME;
151257 p->pEList = pNew;
151259 if( p->pEList ){
151260 if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
151265 p->selFlags |= SF_ComplexResult;
151270 TREETRACE(0x8,pParse,p,("After result-set wildcard expansion:\n"));
151296 ** If anything goes wrong, an error message is written into pParse.
151297 ** The calling function can detect the problem by looking at pParse->nErr
151298 ** and/or pParse->db->mallocFailed.
151304 if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
151321 ** For each FROM-clause subquery, add Column.zType, Column.zColl, and
151336 if( p->selFlags & SF_HasTypeInfo ) return;
151337 p->selFlags |= SF_HasTypeInfo;
151338 pParse = pWalker->pParse;
151339 assert( (p->selFlags & SF_Resolved) );
151340 pTabList = p->pSrc;
151341 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
151342 Table *pTab = pFrom->pSTab;
151344 if( (pTab->tabFlags & TF_Ephemeral)!=0 && pFrom->fg.isSubquery ){
151345 /* A sub-query in the FROM clause of a SELECT */
151346 Select *pSel = pFrom->u4.pSubq->pSelect;
151356 ** the Table structures of all FROM-clause subqueries in a
151377 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
151378 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
151390 assert( p!=0 || pParse->db->mallocFailed );
151391 assert( pParse->db->pParse==pParse );
151392 if( pParse->db->mallocFailed ) return;
151393 if( p->selFlags & SF_HasTypeInfo ) return;
151395 if( pParse->nErr ) return;
151397 if( pParse->nErr ) return;
151403 ** Display all information about an AggInfo object
151408 pAggInfo->selId, pAggInfo);
151409 for(ii=0; ii<pAggInfo->nColumn; ii++){
151410 struct AggInfo_col *pCol = &pAggInfo->aCol[ii];
151412 "agg-column[%d] pTab=%s iTable=%d iColumn=%d iMem=%d"
151414 ii, pCol->pTab ? pCol->pTab->zName : "NULL",
151415 pCol->iTable, pCol->iColumn, pAggInfo->iFirstReg+ii,
151416 pCol->iSorterColumn,
151417 ii>=pAggInfo->nAccumulator ? "" : " Accumulator");
151418 sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
151420 for(ii=0; ii<pAggInfo->nFunc; ii++){
151421 sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
151422 ii, pAggInfo->iFirstReg+pAggInfo->nColumn+ii);
151423 sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
151429 ** Analyze the arguments to aggregate functions. Create new pAggInfo->aCol[]
151436 ** would throw an error if there is a column reference that is not in the
151437 ** GROUP BY clause and that is not part of an aggregate function argument.
151451 assert( pAggInfo->iFirstReg==0 );
151452 pNC->ncFlags |= NC_InAggFunc;
151453 for(i=0; i<pAggInfo->nFunc; i++){
151454 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
151455 assert( pExpr->op==TK_FUNCTION || pExpr->op==TK_AGG_FUNCTION );
151457 sqlite3ExprAnalyzeAggList(pNC, pExpr->x.pList);
151458 if( pExpr->pLeft ){
151459 assert( pExpr->pLeft->op==TK_ORDER );
151460 assert( ExprUseXList(pExpr->pLeft) );
151461 sqlite3ExprAnalyzeAggList(pNC, pExpr->pLeft->x.pList);
151466 sqlite3ExprAnalyzeAggregates(pNC, pExpr->y.pWin->pFilter);
151470 pNC->ncFlags &= ~NC_InAggFunc;
151474 ** An index on expressions is being used in the inner loop of an
151484 NameContext *pNC /* Name context used to resolve agg-func args */
151486 assert( pAggInfo->iFirstReg==0 );
151488 assert( pSelect->pGroupBy!=0 );
151489 pAggInfo->nColumn = pAggInfo->nAccumulator;
151490 if( ALWAYS(pAggInfo->nSortingColumn>0) ){
151491 int mx = pSelect->pGroupBy->nExpr - 1;
151493 for(j=0; j<pAggInfo->nColumn; j++){
151494 k = pAggInfo->aCol[j].iSorterColumn;
151497 pAggInfo->nSortingColumn = mx+1;
151506 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
151507 printf("data-cursor=%d index={%d,%d}\n",
151508 pIEpr->iDataCur, pIEpr->iIdxCur, pIEpr->iIdxCol);
151509 sqlite3TreeViewExpr(0, pIEpr->pExpr, 0);
151526 if( pExpr->pAggInfo==0 ) return WRC_Continue;
151527 if( pExpr->op==TK_AGG_COLUMN ) return WRC_Continue;
151528 if( pExpr->op==TK_AGG_FUNCTION ) return WRC_Continue;
151529 if( pExpr->op==TK_IF_NULL_ROW ) return WRC_Continue;
151530 pAggInfo = pExpr->pAggInfo;
151531 if( NEVER(pExpr->iAgg>=pAggInfo->nColumn) ) return WRC_Continue;
151532 assert( pExpr->iAgg>=0 );
151533 pCol = &pAggInfo->aCol[pExpr->iAgg];
151534 pExpr->op = TK_AGG_COLUMN;
151535 pExpr->iTable = pCol->iTable;
151536 pExpr->iColumn = pCol->iColumn;
151542 ** Convert every pAggInfo->aFunc[].pExpr such that any node within
151551 for(i=0; i<pAggInfo->nFunc; i++){
151552 sqlite3WalkExpr(&w, pAggInfo->aFunc[i].pFExpr);
151559 ** pAggInfo->aCol[] and pAggInfo->aFunc[] entry in pAggInfo. The first
151560 ** register in this block is stored in pAggInfo->iFirstReg.
151576 assert( pAggInfo->iFirstReg==0 );
151577 pAggInfo->iFirstReg = pParse->nMem + 1;
151578 pParse->nMem += pAggInfo->nColumn + pAggInfo->nFunc;
151585 ** intermediate results while calculating an aggregate. This
151590 Vdbe *v = pParse->pVdbe;
151593 int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
151594 assert( pAggInfo->iFirstReg>0 );
151595 assert( pParse->db->pParse==pParse );
151596 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
151598 if( pParse->nErr ) return;
151599 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->iFirstReg,
151600 pAggInfo->iFirstReg+nReg-1);
151601 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
151602 if( pFunc->iDistinct>=0 ){
151603 Expr *pE = pFunc->pFExpr;
151605 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
151608 pFunc->iDistinct = -1;
151610 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
151611 pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
151612 pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO);
151613 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)",
151614 pFunc->pFunc->zName));
151617 if( pFunc->iOBTab>=0 ){
151621 assert( pFunc->pFExpr->pLeft!=0 );
151622 assert( pFunc->pFExpr->pLeft->op==TK_ORDER );
151623 assert( ExprUseXList(pFunc->pFExpr->pLeft) );
151624 assert( pFunc->pFunc!=0 );
151625 pOBList = pFunc->pFExpr->pLeft->x.pList;
151626 if( !pFunc->bOBUnique ){
151629 if( pFunc->bOBPayload ){
151631 assert( ExprUseXList(pFunc->pFExpr) );
151632 nExtra += pFunc->pFExpr->x.pList->nExpr;
151634 if( pFunc->bUseSubtype ){
151635 nExtra += pFunc->pFExpr->x.pList->nExpr;
151638 if( !pFunc->bOBUnique && pParse->nErr==0 ){
151639 pKeyInfo->nKeyField++;
151642 pFunc->iOBTab, pOBList->nExpr+nExtra, 0,
151644 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(ORDER BY)",
151645 pFunc->pFunc->zName));
151655 Vdbe *v = pParse->pVdbe;
151658 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
151660 assert( ExprUseXList(pF->pFExpr) );
151661 if( pParse->nErr ) return;
151662 pList = pF->pFExpr->x.pList;
151663 if( pF->iOBTab>=0 ){
151664 /* For an ORDER BY aggregate, calls to OP_AggStep were deferred. Inputs
151665 ** were stored in emphermal table pF->iOBTab. Here, we extract those
151674 assert( pF->pFunc!=0 );
151675 nArg = pList->nExpr;
151678 if( pF->bOBPayload==0 ){
151681 assert( pF->pFExpr->pLeft!=0 );
151682 assert( ExprUseXList(pF->pFExpr->pLeft) );
151683 assert( pF->pFExpr->pLeft->x.pList!=0 );
151684 nKey = pF->pFExpr->pLeft->x.pList->nExpr;
151685 if( ALWAYS(!pF->bOBUnique) ) nKey++;
151687 iTop = sqlite3VdbeAddOp1(v, OP_Rewind, pF->iOBTab); VdbeCoverage(v);
151688 for(j=nArg-1; j>=0; j--){
151689 sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, nKey+j, regAgg+j);
151691 if( pF->bUseSubtype ){
151693 int iBaseCol = nKey + nArg + (pF->bOBPayload==0 && pF->bOBUnique==0);
151694 for(j=nArg-1; j>=0; j--){
151695 sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, iBaseCol+j, regSubtype);
151701 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
151703 sqlite3VdbeAddOp2(v, OP_Next, pF->iOBTab, iTop+1); VdbeCoverage(v);
151708 pList ? pList->nExpr : 0);
151709 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
151714 ** Generate code that will update the accumulator memory cells for an
151717 ** If regAcc is non-zero and there are no min() or max() aggregates
151718 ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
151722 ** For an ORDER BY aggregate, the actual accumulator memory cell update
151735 Vdbe *v = pParse->pVdbe;
151742 assert( pAggInfo->iFirstReg>0 );
151743 if( pParse->nErr ) return;
151744 pAggInfo->directMode = 1;
151745 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
151752 assert( ExprUseXList(pF->pFExpr) );
151753 assert( !IsWindowFunc(pF->pFExpr) );
151754 assert( pF->pFunc!=0 );
151755 pList = pF->pFExpr->x.pList;
151756 if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
151757 Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
151758 if( pAggInfo->nAccumulator
151759 && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
151765 if( regHit==0 ) regHit = ++pParse->nMem;
151778 if( pF->iOBTab>=0 ){
151784 nArg = pList->nExpr;
151786 assert( pF->pFExpr->pLeft!=0 );
151787 assert( pF->pFExpr->pLeft->op==TK_ORDER );
151788 assert( ExprUseXList(pF->pFExpr->pLeft) );
151789 pOBList = pF->pFExpr->pLeft->x.pList;
151791 assert( pOBList->nExpr>0 );
151792 regAggSz = pOBList->nExpr;
151793 if( !pF->bOBUnique ){
151796 if( pF->bOBPayload ){
151799 if( pF->bUseSubtype ){
151806 jj = pOBList->nExpr;
151807 if( !pF->bOBUnique ){
151808 sqlite3VdbeAddOp2(v, OP_Sequence, pF->iOBTab, regAgg+jj);
151811 if( pF->bOBPayload ){
151816 if( pF->bUseSubtype ){
151818 int regBase = pF->bOBPayload ? regDistinct : regAgg;
151824 nArg = pList->nExpr;
151832 if( pF->iDistinct>=0 && pList ){
151836 pF->iDistinct = codeDistinct(pParse, eDistinctType,
151837 pF->iDistinct, addrNext, pList, regDistinct);
151839 if( pF->iOBTab>=0 ){
151841 sqlite3VdbeAddOp3(v, OP_MakeRecord, regAgg, regAggSz-1,
151842 regAgg+regAggSz-1);
151843 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pF->iOBTab, regAgg+regAggSz-1,
151844 regAgg, regAggSz-1);
151848 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
151852 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
151853 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
151854 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
151857 pColl = pParse->db->pDfltColl;
151859 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
151864 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
151871 if( pParse->nErr ) return;
151873 if( regHit==0 && pAggInfo->nAccumulator ){
151879 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
151880 sqlite3ExprCode(pParse, pC->pCExpr, AggInfoColumnReg(pAggInfo,i));
151881 if( pParse->nErr ) return;
151884 pAggInfo->directMode = 0;
151900 if( pParse->explain==2 ){
151903 pTab->zName,
151905 bCover ? pIdx->zName : ""
151920 ** sub-expression matches the criteria for being moved to the WHERE
151921 ** clause. If so, add it to the WHERE clause and replace the sub-expression
151925 if( pExpr->op!=TK_AND ){
151926 Select *pS = pWalker->u.pSelect;
151928 ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
151930 ** column from an outer aggregate query, or an aggregate function that
151931 ** belongs to an outer query. Do not move the expression to the WHERE
151934 if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
151936 && pExpr->pAggInfo==0
151938 sqlite3 *db = pWalker->pParse->db;
151941 Expr *pWhere = pS->pWhere;
151943 pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
151944 pS->pWhere = pNew;
151945 pWalker->eCode = 1;
151974 sqlite3WalkExpr(&sWalker, p->pHaving);
151984 ** Check to see if the pThis entry of pTabList is a self-join of another view.
151985 ** Search FROM-clause entries in the range of iFirst..iEnd, including iFirst
151988 ** If pThis is a self-join, then return the SrcItem for the first other
151989 ** instance of that view found. If pThis is not a self-join then return 0.
151992 SrcList *pTabList, /* Search for self-joins in this FROM clause */
151994 int iFirst, int iEnd /* Range of FROM-clause entries to search. */
151998 assert( pThis->fg.isSubquery );
151999 pSel = pThis->u4.pSubq->pSelect;
152001 if( pSel->selFlags & SF_PushDown ) return 0;
152004 pItem = &pTabList->a[iFirst++];
152005 if( !pItem->fg.isSubquery ) continue;
152006 if( pItem->fg.viaCoroutine ) continue;
152007 if( pItem->zName==0 ) continue;
152008 assert( pItem->pSTab!=0 );
152009 assert( pThis->pSTab!=0 );
152010 if( pItem->pSTab->pSchema!=pThis->pSTab->pSchema ) continue;
152011 if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
152012 pS1 = pItem->u4.pSubq->pSelect;
152013 if( pItem->pSTab->pSchema==0 && pSel->selId!=pS1->selId ){
152018 if( pS1->selFlags & SF_PushDown ){
152033 sqlite3DbFree(db, p->aCol);
152034 sqlite3DbFree(db, p->aFunc);
152054 ** * None of the subqueries are DISTINCT (forumpost/a860f5fb2e 2025-03-10)
152064 if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
152065 if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
152066 if( p->pWhere ) return 0;
152067 if( p->pHaving ) return 0;
152068 if( p->pGroupBy ) return 0;
152069 if( p->pOrderBy ) return 0;
152070 pExpr = p->pEList->a[0].pExpr;
152071 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
152073 if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
152075 if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
152076 if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
152078 pFrom = p->pSrc->a;
152079 if( pFrom->fg.isSubquery==0 ) return 0; /* FROM is a subquery */
152080 pSub = pFrom->u4.pSubq->pSelect;
152081 if( pSub->pPrior==0 ) return 0; /* Must be a compound */
152082 if( pSub->selFlags & SF_CopyCte ) return 0; /* Not a CTE */
152084 if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
152085 if( pSub->pWhere ) return 0; /* No WHERE clause */
152086 if( pSub->pLimit ) return 0; /* No LIMIT clause */
152087 if( pSub->selFlags & (SF_Aggregate|SF_Distinct) ){
152088 testcase( pSub->selFlags & SF_Aggregate );
152089 testcase( pSub->selFlags & SF_Distinct );
152090 return 0; /* Not an aggregate nor DISTINCT */
152092 assert( pSub->pHaving==0 ); /* Due to the previous */
152093 pSub = pSub->pPrior; /* Repeat over compound */
152098 db = pParse->db;
152102 sqlite3SrcListDelete(db, p->pSrc);
152103 p->pSrc = sqlite3DbMallocZero(pParse->db, SZ_SRCLIST_1);
152106 pPrior = pSub->pPrior;
152107 pSub->pPrior = 0;
152108 pSub->pNext = 0;
152109 pSub->selFlags |= SF_Aggregate;
152110 pSub->selFlags &= ~(u32)SF_Compound;
152111 pSub->nSelectRow = 0;
152112 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pSub->pEList);
152114 pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
152124 p->pEList->a[0].pExpr = pExpr;
152125 p->selFlags &= ~(u32)SF_Aggregate;
152129 TREETRACE(0x200,pParse,p,("After count-of-view optimization:\n"));
152137 ** If any term of pSrc, or any SF_NestedFrom sub-query, is not the same
152143 for(i=0; i<pSrc->nSrc; i++){
152144 SrcItem *p1 = &pSrc->a[i];
152146 if( p0->pSTab==p1->pSTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
152149 if( p1->fg.isSubquery
152150 && (p1->u4.pSubq->pSelect->selFlags & SF_NestedFrom)!=0
152151 && sameSrcAlias(p0, p1->u4.pSubq->pSelect->pSrc)
152160 ** Return TRUE (non-zero) if the i-th entry in the pTabList SrcList can
152161 ** be implemented as a co-routine. The i-th entry is guaranteed to be
152164 ** The subquery is implemented as a co-routine if all of the following are
152171 ** (b) The subquery is the left-most term and a CROSS JOIN or similar
152174 ** (i) The subquery is the left-most subquery in the FROM clause
152185 ** (5) The subquery is not self-joined
152193 SrcItem *pItem = &pTabList->a[i];
152194 if( pItem->fg.isCte ){
152195 const CteUse *pCteUse = pItem->u2.pCteUse;
152196 if( pCteUse->eM10d==M10d_Yes ) return 0; /* (2a) */
152197 if( pCteUse->nUse>=2 && pCteUse->eM10d!=M10d_No ) return 0; /* (2b) */
152199 if( pTabList->a[0].fg.jointype & JT_LTORJ ) return 0; /* (3) */
152200 if( OptimizationDisabled(pParse->db, SQLITE_Coroutines) ) return 0; /* (4) */
152201 if( isSelfJoinView(pTabList, pItem, i+1, pTabList->nSrc)!=0 ){
152205 if( pTabList->nSrc==1 ) return 1; /* (1a) */
152206 if( pTabList->a[1].fg.jointype & JT_CROSS ) return 1; /* (1b) */
152207 if( selFlags & SF_UpdateFrom ) return 0; /* (1c-iii) */
152210 if( selFlags & SF_UpdateFrom ) return 0; /* (1c-iii) */
152211 while( 1 /*exit-by-break*/ ){
152212 if( pItem->fg.jointype & (JT_OUTER|JT_CROSS) ) return 0; /* (1c-ii) */
152214 i--;
152215 pItem--;
152216 if( pItem->fg.isSubquery ) return 0; /* (1c-i) */
152222 ** Generate byte-code for the SELECT statement given in the p argument.
152228 ** encountered, then an appropriate error message is left in
152229 ** pParse->zErrMsg.
152234 ** This is a long function. The following is an outline of the processing
152237 ** * Resolve names and similar preparation tag-select-0100
152238 ** * Scan of the FROM clause tag-select-0200
152239 ** + OUTER JOIN strength reduction tag-select-0220
152240 ** + Sub-query ORDER BY removal tag-select-0230
152241 ** + Query flattening tag-select-0240
152242 ** * Separate subroutine for compound-SELECT tag-select-0300
152243 ** * WHERE-clause constant propagation tag-select-0330
152244 ** * Count()-of-VIEW optimization tag-select-0350
152245 ** * Scan of the FROM clause again tag-select-0400
152246 ** + Authorize unreferenced tables tag-select-0410
152247 ** + Predicate push-down optimization tag-select-0420
152248 ** + Omit unused subquery columns optimization tag-select-0440
152249 ** + Generate code to implement subqueries tag-select-0480
152250 ** - Co-routines tag-select-0482
152251 ** - Reuse previously computed CTE tag-select-0484
152252 ** - REuse previously computed VIEW tag-select-0486
152253 ** - Materialize a VIEW or CTE tag-select-0488
152254 ** * DISTINCT ORDER BY -> GROUP BY optimization tag-select-0500
152255 ** * Set up for ORDER BY tag-select-0600
152256 ** * Create output table tag-select-0630
152257 ** * Prepare registers for LIMIT tag-select-0650
152258 ** * Setup for DISTINCT tag-select-0680
152259 ** * Generate code for non-aggregate and non-GROUP BY tag-select-0700
152260 ** * Generate code for aggregate and/or GROUP BY tag-select-0800
152261 ** + GROUP BY queries tag-select-0810
152262 ** + non-GROUP BY queries tag-select-0820
152263 ** - Special case of count() w/o GROUP BY tag-select-0821
152264 ** - General case of non-GROUP BY aggregates tag-select-0822
152265 ** * Sort results, as needed tag-select-0900
152266 ** * Internal self-checks tag-select-1000
152291 db = pParse->db;
152292 assert( pParse==db->pParse );
152294 if( p==0 || pParse->nErr ){
152297 assert( db->mallocFailed==0 );
152300 TREETRACE(0x1,pParse,p, ("begin processing:\n", pParse->addrExplain));
152310 /* tag-select-0100 */
152311 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
152312 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
152313 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
152314 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
152316 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
152317 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
152318 pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_DistFifo );
152320 if( p->pOrderBy ){
152324 sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
152328 p->pOrderBy);
152329 testcase( pParse->earlyCleanup );
152330 p->pOrderBy = 0;
152332 p->selFlags &= ~(u32)SF_Distinct;
152333 p->selFlags |= SF_NoopOrderBy;
152336 if( pParse->nErr ){
152339 assert( db->mallocFailed==0 );
152340 assert( p->pEList!=0 );
152349 ** as part of populating the temp table for an UPDATE...FROM statement.
152350 ** In this case, it is an error if the target object (pSrc->a[0]) name
152351 ** or alias is duplicated within FROM clause (pSrc->a[1..n]).
152357 if( p->selFlags & SF_UFSrcCheck ){
152358 SrcItem *p0 = &p->pSrc->a[0];
152359 if( sameSrcAlias(p0, p->pSrc) ){
152362 p0->zAlias ? p0->zAlias : p0->pSTab->zName
152368 ** and leaving this flag set can cause errors if a compound sub-query
152369 ** in p->pSrc is flattened into this query and this function called
152371 p->selFlags &= ~(u32)SF_UFSrcCheck;
152374 if( pDest->eDest==SRT_Output ){
152380 assert( pParse->nErr );
152384 if( p->pWin && (sqlite3TreeTrace & 0x40)!=0 ){
152390 pTabList = p->pSrc;
152391 isAgg = (p->selFlags & SF_Aggregate)!=0;
152393 sSort.pOrderBy = p->pOrderBy;
152397 ** tag-select-0200
152400 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
152401 SrcItem *pItem = &pTabList->a[i];
152402 Select *pSub = pItem->fg.isSubquery ? pItem->u4.pSubq->pSelect : 0;
152403 Table *pTab = pItem->pSTab;
152412 ** LEFT JOIN -> JOIN
152413 ** RIGHT JOIN -> JOIN
152414 ** FULL JOIN -> RIGHT JOIN
152416 ** If terms of the i-th table are used in the WHERE clause in such a
152417 ** way that the i-th table cannot be the NULL row of a join, then
152420 ** tag-select-0220
152422 if( (pItem->fg.jointype & (JT_LEFT|JT_LTORJ))!=0
152423 && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor,
152424 pItem->fg.jointype & JT_LTORJ)
152427 if( pItem->fg.jointype & JT_LEFT ){
152428 if( pItem->fg.jointype & JT_RIGHT ){
152430 ("FULL-JOIN simplifies to RIGHT-JOIN on term %d\n",i));
152431 pItem->fg.jointype &= ~JT_LEFT;
152434 ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
152435 pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
152436 unsetJoinExpr(p->pWhere, pItem->iCursor, 0);
152439 if( pItem->fg.jointype & JT_LTORJ ){
152440 for(j=i+1; j<pTabList->nSrc; j++){
152441 SrcItem *pI2 = &pTabList->a[j];
152442 if( pI2->fg.jointype & JT_RIGHT ){
152443 if( pI2->fg.jointype & JT_LEFT ){
152445 ("FULL-JOIN simplifies to LEFT-JOIN on term %d\n",j));
152446 pI2->fg.jointype &= ~JT_RIGHT;
152449 ("RIGHT-JOIN simplifies to JOIN on term %d\n",j));
152450 pI2->fg.jointype &= ~(JT_RIGHT|JT_OUTER);
152451 unsetJoinExpr(p->pWhere, pI2->iCursor, 1);
152455 for(j=pTabList->nSrc-1; j>=0; j--){
152456 pTabList->a[j].fg.jointype &= ~JT_LTORJ;
152457 if( pTabList->a[j].fg.jointype & JT_RIGHT ) break;
152467 if( pTab->nCol!=pSub->pEList->nExpr ){
152469 pTab->nCol, pTab->zName, pSub->pEList->nExpr);
152475 ** a MATERIALIZED common table expression is an optimization fence.
152477 if( pItem->fg.isCte && pItem->u2.pCteUse->eM10d==M10d_Yes ){
152481 /* Do not try to flatten an aggregate subquery.
152483 ** Flattening an aggregate subquery is only possible if the outer query
152485 ** will be implemented as a co-routine and there is no advantage to
152488 if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
152489 assert( pSub->pGroupBy==0 );
152491 /* tag-select-0230:
152492 ** If a FROM-clause subquery has an ORDER BY clause that is not
152501 ** (2) The subquery was added to help with window-function
152503 ** (3) The subquery is in the FROM clause of an UPDATE
152504 ** (4) The outer query uses an aggregate function other than
152505 ** the built-in count(), min(), or max().
152517 if( pSub->pOrderBy!=0
152518 && (p->pOrderBy!=0 || pTabList->nSrc>1) /* Condition (5) */
152519 && pSub->pLimit==0 /* Condition (1) */
152520 && (pSub->selFlags & (SF_OrderByReqd|SF_Recursive))==0 /* (2) and (6) */
152521 && (p->selFlags & SF_OrderByReqd)==0 /* Condition (3) and (4) */
152525 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
152527 pSub->pOrderBy);
152528 pSub->pOrderBy = 0;
152533 ** and if the subquery contains an ORDER BY clause and if
152534 ** it will be implemented as a co-routine, then do not flatten. This
152549 if( pSub->pOrderBy!=0
152551 && (p->selFlags & SF_ComplexResult)!=0
152552 && (pTabList->nSrc==1
152553 || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)
152558 /* tag-select-0240 */
152560 if( pParse->nErr ) goto select_end;
152562 i = -1;
152564 pTabList = p->pSrc;
152565 if( db->mallocFailed ) goto select_end;
152567 sSort.pOrderBy = p->pOrderBy;
152574 ** procedure. tag-select-0300
152576 if( p->pPrior ){
152579 TREETRACE(0x400,pParse,p,("end compound-select processing\n"));
152584 if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
152589 /* Do the WHERE-clause constant propagation optimization if this is
152590 ** a join. No need to spend time on this operation for non-join queries
152592 ** sqlite3WhereBegin(). tag-select-0330
152594 if( p->pWhere!=0
152595 && p->pWhere->op==TK_AND
152609 /* tag-select-0350 */
152613 if( db->mallocFailed ) goto select_end;
152614 pTabList = p->pSrc;
152620 ** (2) Generate code for all sub-queries
152622 ** tag-select-0400
152624 for(i=0; i<pTabList->nSrc; i++){
152625 SrcItem *pItem = &pTabList->a[i];
152634 /* Authorized unreferenced tables. tag-select-0410
152641 ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
152642 ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
152644 ** The fake column name is an empty string. It is possible for a table to
152646 ** distinguish between an unreferenced table and an actual reference to the
152649 ** assume the column name is non-NULL and segfault. The use of an empty
152652 if( pItem->colUsed==0 && pItem->zName!=0 ){
152654 if( pItem->fg.fixedSchema ){
152655 int iDb = sqlite3SchemaToIndex(pParse->db, pItem->u4.pSchema);
152656 zDb = db->aDb[iDb].zDbSName;
152657 }else if( pItem->fg.isSubquery ){
152660 zDb = pItem->u4.zDatabase;
152662 sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", zDb);
152666 /* Generate code for all sub-queries in the FROM clause
152668 if( pItem->fg.isSubquery==0 ) continue;
152669 pSubq = pItem->u4.pSubq;
152671 pSub = pSubq->pSelect;
152674 if( pSubq->addrFillSub!=0 ) continue;
152679 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
152681 ** an exact limit.
152683 pParse->nHeight += sqlite3SelectExprHeight(p);
152685 /* Make copies of constant WHERE-clause terms in the outer query down
152687 ** This is the "predicate push-down optimization". tag-select-0420
152690 && (pItem->fg.isCte==0
152691 || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
152692 && pushDownWhereTerms(pParse, pSub, p->pWhere, pTabList, i)
152697 ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
152701 assert( pSubq->pSelect && (pSub->selFlags & SF_PushDown)!=0 );
152703 TREETRACE(0x4000,pParse,p,("WHERE-clause push-down not possible\n"));
152708 ** tag-select-0440
152717 pSub->selId));
152723 zSavedAuthContext = pParse->zAuthContext;
152724 pParse->zAuthContext = pItem->zName;
152726 /* Generate byte-code to implement the subquery tag-select-0480
152728 if( fromClauseTermCanBeCoroutine(pParse, pTabList, i, p->selFlags) ){
152729 /* Implement a co-routine that will return a single row of the result
152730 ** set on each invocation. tag-select-0482
152734 pSubq->regReturn = ++pParse->nMem;
152735 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pSubq->regReturn, 0, addrTop);
152737 pSubq->addrFillSub = addrTop;
152738 sqlite3SelectDestInit(&dest, SRT_Coroutine, pSubq->regReturn);
152739 ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem));
152741 pItem->pSTab->nRowLogEst = pSub->nSelectRow;
152742 pItem->fg.viaCoroutine = 1;
152743 pSubq->regResult = dest.iSdst;
152744 sqlite3VdbeEndCoroutine(v, pSubq->regReturn);
152746 sqlite3VdbeJumpHere(v, addrTop-1);
152748 }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){
152751 ** then make the pItem->iCursor be a copy of the ephemeral table that
152752 ** holds the result of the materialization. tag-select-0484 */
152753 CteUse *pCteUse = pItem->u2.pCteUse;
152754 sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
152755 if( pItem->iCursor!=pCteUse->iCur ){
152756 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
152759 pSub->nSelectRow = pCteUse->nRowEst;
152762 ** this same FROM clause. Reuse it. tag-select-0486 */
152764 assert( pPrior->fg.isSubquery );
152765 pPriorSubq = pPrior->u4.pSubq;
152767 if( pPriorSubq->addrFillSub ){
152768 sqlite3VdbeAddOp2(v, OP_Gosub, pPriorSubq->regReturn,
152769 pPriorSubq->addrFillSub);
152771 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
152772 pSub->nSelectRow = pPriorSubq->pSelect->nSelectRow;
152776 ** the same view can reuse the materialization. tag-select-0488 */
152783 pSubq->regReturn = ++pParse->nMem;
152785 pSubq->addrFillSub = topAddr+1;
152786 pItem->fg.isMaterialized = 1;
152787 if( pItem->fg.isCorrelated==0 ){
152796 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
152800 pItem->pSTab->nRowLogEst = pSub->nSelectRow;
152802 sqlite3VdbeAddOp2(v, OP_Return, pSubq->regReturn, topAddr+1);
152804 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
152807 if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
152808 CteUse *pCteUse = pItem->u2.pCteUse;
152809 pCteUse->addrM9e = pSubq->addrFillSub;
152810 pCteUse->regRtn = pSubq->regReturn;
152811 pCteUse->iCur = pItem->iCursor;
152812 pCteUse->nRowEst = pSub->nSelectRow;
152815 if( db->mallocFailed ) goto select_end;
152816 pParse->nHeight -= sqlite3SelectExprHeight(p);
152817 pParse->zAuthContext = zSavedAuthContext;
152823 pEList = p->pEList;
152824 pWhere = p->pWhere;
152825 pGroupBy = p->pGroupBy;
152826 pHaving = p->pHaving;
152827 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
152831 TREETRACE(0x8000,pParse,p,("After all FROM-clause analysis:\n"));
152836 /* tag-select-0500
152838 ** If the query is DISTINCT with an ORDER BY but is not an aggregate, and
152839 ** if the select-list is the same as the ORDER BY list, then this query
152848 ** The second form is preferred as a single index (or temp-table) may be
152850 ** written the query must use a temp-table for at least one of the ORDER
152851 ** BY and DISTINCT, and an index or separate temp-table for the other.
152853 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
152854 && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
152857 && p->pWin==0
152860 p->selFlags &= ~(u32)SF_Distinct;
152861 pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
152863 for(i=0; i<pGroupBy->nExpr; i++){
152864 pGroupBy->a[i].u.x.iOrderByCol = i+1;
152867 p->selFlags |= SF_Aggregate;
152868 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
152882 /* If there is an ORDER BY clause, then create an ephemeral index to
152884 ** being unused if the data can be extracted in pre-sorted order.
152886 ** changed to an OP_Noop once we figure out that the sorting index is
152888 ** that change. tag-select-0600
152893 pParse, sSort.pOrderBy, 0, pEList->nExpr);
152894 sSort.iECursor = pParse->nTab++;
152897 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
152901 sSort.addrSortIndex = -1;
152905 ** tag-select-0630
152907 if( pDest->eDest==SRT_EphemTab ){
152908 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
152909 if( p->selFlags & SF_NestedFrom ){
152910 /* Delete or NULL-out result columns that will never be used */
152912 for(ii=pEList->nExpr-1; ii>0 && pEList->a[ii].fg.bUsed==0; ii--){
152913 sqlite3ExprDelete(db, pEList->a[ii].pExpr);
152914 sqlite3DbFree(db, pEList->a[ii].zEName);
152915 pEList->nExpr--;
152917 for(ii=0; ii<pEList->nExpr; ii++){
152918 if( pEList->a[ii].fg.bUsed==0 ) pEList->a[ii].pExpr->op = TK_NULL;
152923 /* Set the limiter. tag-select-0650
152926 if( (p->selFlags & SF_FixedLimit)==0 ){
152927 p->nSelectRow = 320; /* 4 billion rows */
152929 if( p->pLimit ) computeLimitRegisters(pParse, p, iEnd);
152930 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
152935 /* Open an ephemeral index to use for the distinct set. tag-select-0680
152937 if( p->selFlags & SF_Distinct ){
152938 sDistinct.tabTnct = pParse->nTab++;
152941 (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
152950 /* No aggregate functions and no GROUP BY clause. tag-select-0700 */
152952 | (p->selFlags & SF_FixedLimit);
152954 Window *pWin = p->pWin; /* Main window object (or NULL) */
152965 p->pEList, p, wctrlFlags, p->nSelectRow);
152967 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
152968 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
152969 if( pDest->eDest<=SRT_DistQueue && pDest->eDest>=SRT_DistFifo ){
152972 ** Search for tag-20250414a to see other cases */
152973 p->nSelectRow -= 30;
152982 if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
152990 ** into an OP_Noop.
152996 assert( p->pEList==pEList );
153002 int regGosub = ++pParse->nMem;
153008 VdbeNoopComment((v, "inner-loop subroutine"));
153010 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
153013 VdbeComment((v, "end inner-loop subroutine"));
153019 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
153030 ** clause or both. tag-select-0800 */
153051 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
153052 pItem->u.x.iAlias = 0;
153054 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
153055 pItem->u.x.iAlias = 0;
153058 if( p->nSelectRow>66 ) p->nSelectRow = 66;
153060 /* If there is both a GROUP BY and an ORDER BY clause and they are
153063 ** in the correct order. It also may not - the GROUP BY might use a
153068 if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
153071 ** ASC or DESC order - only that each group is returned contiguously.
153073 ** ORDER BY to maximize the chances of rows being delivered in an
153075 for(ii=0; ii<pGroupBy->nExpr; ii++){
153077 sortFlags = sSort.pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_DESC;
153078 pGroupBy->a[ii].fg.sortFlags = sortFlags;
153080 if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
153086 p->nSelectRow = 0;
153099 testcase( pParse->earlyCleanup );
153101 if( db->mallocFailed ){
153104 pAggInfo->selId = p->selId;
153106 pAggInfo->pSelect = p;
153113 pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
153114 pAggInfo->pGroupBy = pGroupBy;
153119 assert( pWhere==p->pWhere );
153120 assert( pHaving==p->pHaving );
153121 assert( pGroupBy==p->pGroupBy );
153123 pWhere = p->pWhere;
153127 pAggInfo->nAccumulator = pAggInfo->nColumn;
153128 if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
153129 minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
153134 if( db->mallocFailed ) goto select_end;
153149 ** much more complex than aggregates without a GROUP BY. tag-select-0810
153153 int addr1; /* A-vs-B comparison jump */
153165 if( pAggInfo->nFunc==1
153166 && pAggInfo->aFunc[0].iDistinct>=0
153167 && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0)
153168 && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr))
153169 && pAggInfo->aFunc[0].pFExpr->x.pList!=0
153171 Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr;
153183 pAggInfo->sortingIdx = pParse->nTab++;
153185 0, pAggInfo->nColumn);
153187 pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
153192 iUseFlag = ++pParse->nMem;
153193 iAbortFlag = ++pParse->nMem;
153194 regOutputRow = ++pParse->nMem;
153196 regReset = ++pParse->nMem;
153198 iAMem = pParse->nMem + 1;
153199 pParse->nMem += pGroupBy->nExpr;
153200 iBMem = pParse->nMem + 1;
153201 pParse->nMem += pGroupBy->nExpr;
153204 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
153205 sqlite3ExprNullRegisterRange(pParse, iAMem, pGroupBy->nExpr);
153208 ** This might involve two separate loops with an OP_Sort in between, or
153209 ** it might be a single loop that uses an index to extract information
153222 if( pParse->pIdxEpr ){
153228 if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
153248 ExplainQueryPlan2(addrExp, (pParse, 0, "USE TEMP B-TREE FOR %s",
153249 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
153254 nGroupBy = pGroupBy->nExpr;
153257 for(i=0; i<pAggInfo->nColumn; i++){
153258 if( pAggInfo->aCol[i].iSorterColumn>=j ){
153266 pAggInfo->directMode = 1;
153267 for(i=0; i<pAggInfo->nColumn; i++){
153268 struct AggInfo_col *pCol = &pAggInfo->aCol[i];
153269 if( pCol->iSorterColumn>=j ){
153270 sqlite3ExprCode(pParse, pCol->pCExpr, j + regBase);
153274 pAggInfo->directMode = 0;
153278 sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
153279 sqlite3VdbeScanStatusRange(v, addrExp, sqlite3VdbeCurrentAddr(v)-2, -1);
153284 pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
153288 sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
153290 pAggInfo->useSortingIdx = 1;
153291 sqlite3VdbeScanStatusRange(v, addrExp, -1, sortPTab);
153292 sqlite3VdbeScanStatusRange(v, addrExp, -1, pAggInfo->sortingIdx);
153295 /* If there are entries in pAgggInfo->aFunc[] that contain subexpressions
153300 if( pParse->pIdxEpr ){
153316 ** This is an optimization - the correct answer should result regardless.
153333 sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
153336 for(j=0; j<pGroupBy->nExpr; j++){
153337 int iOrderByCol = pGroupBy->a[j].u.x.iOrderByCol;
153342 pAggInfo->directMode = 1;
153343 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
153347 Expr *pX = p->pEList->a[iOrderByCol-1].pExpr;
153349 while( ALWAYS(pBase!=0) && pBase->op==TK_IF_NULL_ROW ){
153350 pX = pBase->pLeft;
153354 && pBase->op!=TK_AGG_COLUMN
153355 && pBase->op!=TK_REGISTER
153361 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
153377 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
153394 sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop);
153414 ** is less than or equal to zero, the subroutine is a no-op. If
153431 selectInnerLoop(pParse, p, -1, &sSort,
153437 /* Generate a subroutine that will reset the group-by accumulator
153446 struct AggInfo_func *pF = &pAggInfo->aFunc[0];
153447 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
153451 /* Aggregate functions without GROUP BY. tag-select-0820 */
153454 /* tag-select-0821
153466 ** is better to execute the op on an index, as indexes are almost
153469 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
153470 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
153474 Pgno iRoot = pTab->tnum; /* Root page of scanned b-tree */
153477 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
153481 ** (2011-04-15) Do not do a full scan of an unordered index.
153483 ** (2013-10-03) Do not count the entries in a partial index.
153489 if( !p->pSrc->a[0].fg.notIndexed ){
153490 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
153491 if( pIdx->bUnordered==0
153492 && pIdx->szIdxRow<pTab->szTabRow
153493 && pIdx->pPartIdxWhere==0
153494 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
153501 iRoot = pBest->tnum;
153505 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
153508 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
153515 /* The general case of an aggregate query without GROUP BY
153516 ** tag-select-0822 */
153531 if( pAggInfo->nAccumulator ){
153532 for(i=0; i<pAggInfo->nFunc; i++){
153533 if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
153536 if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
153540 if( i==pAggInfo->nFunc ){
153541 regAcc = ++pParse->nMem;
153544 }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){
153545 assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) );
153546 pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList;
153555 assert( p->pGroupBy==0 );
153561 ** be an appropriate ORDER BY expression for the optimization.
153564 assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
153576 struct AggInfo_func *pF = pAggInfo->aFunc;
153578 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
153593 selectInnerLoop(pParse, p, -1, 0, 0,
153604 /* If there is an ORDER BY clause, then we need to sort the results
153605 ** and send them to the callback one by one. tag-select-0900
153608 assert( p->pEList==pEList );
153609 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
153616 /* The SELECT has been coded. If there is an error in the Parse structure,
153618 rc = (pParse->nErr>0);
153620 /* Control jumps to here if an error is encountered above, or upon
153624 assert( db->mallocFailed==0 || db->mallocFailed==1 );
153625 assert( db->mallocFailed==0 || pParse->nErr!=0 );
153628 /* Internal self-checks. tag-select-1000 */
153629 if( pAggInfo && !db->mallocFailed ){
153636 for(i=0; i<pAggInfo->nColumn; i++){
153637 Expr *pExpr = pAggInfo->aCol[i].pCExpr;
153639 assert( pExpr->pAggInfo==pAggInfo );
153640 assert( pExpr->iAgg==i );
153642 for(i=0; i<pAggInfo->nFunc; i++){
153643 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
153645 assert( pExpr->pAggInfo==pAggInfo );
153646 assert( pExpr->iAgg==i );
153691 char *zErrMsg; /* Error message text, if an error occurs */
153706 int need; /* Slots needed in p->azResult[] */
153710 /* Make sure there is enough space in p->azResult to hold everything
153713 if( p->nRow==0 && argv!=0 ){
153718 if( p->nData + need > p->nAlloc ){
153720 p->nAlloc = p->nAlloc*2 + need;
153721 azNew = sqlite3Realloc( p->azResult, sizeof(char*)*p->nAlloc );
153723 p->azResult = azNew;
153726 /* If this is the first row, then generate an extra row containing
153729 if( p->nRow==0 ){
153730 p->nColumn = nCol;
153734 p->azResult[p->nData++] = z;
153736 }else if( (int)p->nColumn!=nCol ){
153737 sqlite3_free(p->zErrMsg);
153738 p->zErrMsg = sqlite3_mprintf(
153741 p->rc = SQLITE_ERROR;
153757 p->azResult[p->nData++] = z;
153759 p->nRow++;
153764 p->rc = SQLITE_NOMEM_BKPT;
153804 db->errCode = SQLITE_NOMEM;
153820 db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
153833 db->errCode = SQLITE_NOMEM;
153852 azResult--;
153885 pTriggerStep = pTriggerStep->pNext;
153887 sqlite3ExprDelete(db, pTmp->pWhere);
153888 sqlite3ExprListDelete(db, pTmp->pExprList);
153889 sqlite3SelectDelete(db, pTmp->pSelect);
153890 sqlite3IdListDelete(db, pTmp->pIdList);
153891 sqlite3UpsertDelete(db, pTmp->pUpsert);
153892 sqlite3SrcListDelete(db, pTmp->pFrom);
153893 sqlite3DbFree(db, pTmp->zSpan);
153904 ** are already attached to pTab->pTrigger. But there might be additional
153906 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
153911 ** pTab as well as the triggers lised in pTab->pTrigger.
153918 assert( pParse->disableTriggers==0 );
153919 pTmpSchema = pParse->db->aDb[1].pSchema;
153920 p = sqliteHashFirst(&pTmpSchema->trigHash);
153921 pList = pTab->pTrigger;
153924 if( pTrig->pTabSchema==pTab->pSchema
153925 && pTrig->table
153926 && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
153927 && (pTrig->pTabSchema!=pTmpSchema || pTrig->bReturning)
153929 pTrig->pNext = pList;
153931 }else if( pTrig->op==TK_RETURNING ){
153933 assert( pParse->db->pVtabCtx==0 );
153935 assert( pParse->bReturning );
153936 assert( !pParse->isCreate );
153937 assert( &(pParse->u1.d.pReturning->retTrig) == pTrig );
153938 pTrig->table = pTab->zName;
153939 pTrig->pTabSchema = pTab->pSchema;
153940 pTrig->pNext = pList;
153948 printf("Triggers for %s:", pTab->zName);
153949 for(pX=pList; pX; pX=pX->pNext){
153950 printf(" %s", pX->zName);
153963 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
153973 IdList *pColumns, /* column list if this is an UPDATE OF trigger */
153982 sqlite3 *db = pParse->db; /* The database connection */
153987 assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
153993 if( pName2->n>0 ){
154006 if( !pTableName || db->mallocFailed ){
154010 /* A long-standing parser bug is that this syntax was allowed:
154018 if( db->init.busy && iDb!=1 ){
154019 assert( pTableName->a[0].fg.fixedSchema==0 );
154020 assert( pTableName->a[0].fg.isSubquery==0 );
154021 sqlite3DbFree(db, pTableName->a[0].u4.zDatabase);
154022 pTableName->a[0].u4.zDatabase = 0;
154031 if( db->init.busy==0 && pName2->n==0 && pTab
154032 && pTab->pSchema==db->aDb[1].pSchema ){
154037 if( db->mallocFailed ) goto trigger_cleanup;
154038 assert( pTableName->nSrc==1 );
154052 if( (pTab->tabFlags & TF_Shadow)!=0 && sqlite3ReadOnlyShadowTables(db) ){
154061 assert( db->mallocFailed );
154064 if( sqlite3CheckObjectName(pParse, zName, "trigger", pTab->zName) ){
154069 if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
154073 assert( !db->init.busy );
154075 VVA_ONLY( pParse->ifNotExists = 1; )
154082 if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
154092 (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName->a);
154097 " trigger on table: %S", pTableName->a);
154103 int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
154105 const char *zDb = db->aDb[iTabDb].zDbSName;
154106 const char *zDbTrig = isTemp ? db->aDb[1].zDbSName : zDb;
154108 if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
154129 pTrigger->zName = zName;
154131 pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
154132 pTrigger->pSchema = db->aDb[iDb].pSchema;
154133 pTrigger->pTabSchema = pTab->pSchema;
154134 pTrigger->op = (u8)op;
154135 pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
154137 sqlite3RenameTokenRemap(pParse, pTrigger->table, pTableName->a[0].zName);
154138 pTrigger->pWhen = pWhen;
154141 pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
154143 pTrigger->pColumns = pColumns;
154145 assert( pParse->pNewTrigger==0 );
154146 pParse->pNewTrigger = pTrigger;
154153 if( !pParse->pNewTrigger ){
154156 assert( pParse->pNewTrigger==pTrigger );
154161 if( db->init.iDb==1 ){
154164 ** dropped too. But if a TEMP trigger is created on a non-TEMP table
154167 ** drop so the trigger cannot be dropped. This results in an
154168 ** "orphaned trigger" - a trigger whose associated table is missing.
154170 ** 2020-11-05 see also https://sqlite.org/forum/forumpost/157dc791df
154172 db->init.orphanTrigger = 1;
154186 Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
154188 sqlite3 *db = pParse->db; /* The database */
154193 pParse->pNewTrigger = 0;
154194 if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
154195 zName = pTrig->zName;
154196 iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
154197 pTrig->step_list = pStepList;
154199 pStepList->pTrig = pTrig;
154200 pStepList = pStepList->pNext;
154202 sqlite3TokenInit(&nameToken, pTrig->zName);
154204 if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
154205 || sqlite3FixExpr(&sFix, pTrig->pWhen)
154212 assert( !db->init.busy );
154213 pParse->pNewTrigger = pTrig;
154221 if( !db->init.busy ){
154226 ** are read-only, and the trigger makes a change to a shadow table,
154227 ** then raise an error - do not allow the trigger to be created. */
154230 for(pStep=pTrig->step_list; pStep; pStep=pStep->pNext){
154231 if( pStep->zTarget!=0
154232 && sqlite3ShadowTableName(db, pStep->zTarget)
154236 pTrig->zName, pStep->zTarget);
154242 /* Make an entry in the sqlite_schema table */
154246 z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
154251 db->aDb[iDb].zDbSName, zName,
154252 pTrig->table, z);
154259 if( db->init.busy ){
154261 Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
154267 }else if( pLink->pSchema==pLink->pTabSchema ){
154269 pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
154271 pLink->pNext = pTab->pTrigger;
154272 pTab->pTrigger = pLink;
154278 assert( IN_RENAME_OBJECT || !pParse->pNewTrigger );
154283 ** Duplicate a range of text from an SQL statement, then convert all
154311 pTriggerStep->op = TK_SELECT;
154312 pTriggerStep->pSelect = pSelect;
154313 pTriggerStep->orconf = OE_Default;
154314 pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
154322 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
154331 sqlite3 *db = pParse->db;
154334 if( pParse->nErr ) return 0;
154335 pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
154338 memcpy(z, pName->z, pName->n);
154340 pTriggerStep->zTarget = z;
154341 pTriggerStep->op = op;
154342 pTriggerStep->zSpan = triggerSpanDup(db, zStart, zEnd);
154344 sqlite3RenameTokenMap(pParse, pTriggerStep->zTarget, pName);
154351 ** Build a trigger step out of an INSERT statement. Return a pointer
154354 ** The parser calls this routine when it sees an INSERT inside the
154367 sqlite3 *db = pParse->db;
154370 assert(pSelect != 0 || db->mallocFailed);
154375 pTriggerStep->pSelect = pSelect;
154378 pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
154380 pTriggerStep->pIdList = pColumn;
154381 pTriggerStep->pUpsert = pUpsert;
154382 pTriggerStep->orconf = orconf;
154384 sqlite3HasExplicitNulls(pParse, pUpsert->pUpsertTarget);
154398 ** Construct a trigger step that implements an UPDATE statement and return
154400 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
154405 SrcList *pFrom, /* FROM clause for an UPDATE-FROM, or NULL */
154412 sqlite3 *db = pParse->db;
154418 pTriggerStep->pExprList = pEList;
154419 pTriggerStep->pWhere = pWhere;
154420 pTriggerStep->pFrom = pFrom;
154425 pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
154426 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
154427 pTriggerStep->pFrom = sqlite3SrcListDup(db, pFrom, EXPRDUP_REDUCE);
154429 pTriggerStep->orconf = orconf;
154449 sqlite3 *db = pParse->db;
154455 pTriggerStep->pWhere = pWhere;
154458 pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
154460 pTriggerStep->orconf = OE_Default;
154470 if( pTrigger==0 || pTrigger->bReturning ) return;
154471 sqlite3DeleteTriggerStep(db, pTrigger->step_list);
154472 sqlite3DbFree(db, pTrigger->zName);
154473 sqlite3DbFree(db, pTrigger->table);
154474 sqlite3ExprDelete(db, pTrigger->pWhen);
154475 sqlite3IdListDelete(db, pTrigger->pColumns);
154492 sqlite3 *db = pParse->db;
154494 if( db->mallocFailed ) goto drop_trigger_cleanup;
154499 assert( pName->nSrc==1 );
154500 assert( pName->a[0].fg.fixedSchema==0 && pName->a[0].fg.isSubquery==0 );
154501 zDb = pName->a[0].u4.zDatabase;
154502 zName = pName->a[0].zName;
154504 for(i=OMIT_TEMPDB; i<db->nDb; i++){
154508 pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
154513 sqlite3ErrorMsg(pParse, "no such trigger: %S", pName->a);
154517 pParse->checkSchema = 1;
154531 return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
154541 sqlite3 *db = pParse->db;
154544 iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
154545 assert( iDb>=0 && iDb<db->nDb );
154547 assert( (pTable && pTable->pSchema==pTrigger->pSchema) || iDb==1 );
154551 const char *zDb = db->aDb[iDb].zDbSName;
154554 if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
154566 db->aDb[iDb].zDbSName, pTrigger->zName
154569 sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
154581 pHash = &(db->aDb[iDb].pSchema->trigHash);
154584 if( pTrigger->pSchema==pTrigger->pTabSchema ){
154588 for(pp=&pTab->pTrigger; *pp; pp=&((*pp)->pNext)){
154590 *pp = (*pp)->pNext;
154597 db->mDbFlags |= DBFLAG_SchemaChange;
154602 ** pEList is the SET clause of an UPDATE statement. Each entry
154604 ** in pEList have an <id> which matches an identifier in pIdList,
154613 for(e=0; e<pEList->nExpr; e++){
154614 if( sqlite3IdListIndex(pIdList, pEList->a[e].zEName)>=0 ) return 1;
154623 if( NEVER(db->aDb[1].pSchema==0) ) return 0;
154624 if( sqliteHashFirst(&db->aDb[1].pSchema->trigHash)==0 ) return 0;
154630 ** one trigger that must be fired when an operation of type 'op' is
154631 ** performed on the table, and, if that operation is an UPDATE, if at
154638 ExprList *pChanges, /* Columns that change in an UPDATE statement */
154647 || (pList->bReturning && pList->pNext==0) );
154650 if( (pParse->db->flags & SQLITE_EnableTrigger)==0
154651 && pTab->pTrigger!=0
154656 if( pList==pTab->pTrigger ){
154660 while( ALWAYS(p->pNext) && p->pNext!=pTab->pTrigger ) p = p->pNext;
154661 p->pNext = 0;
154665 if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
154666 mask |= p->tr_tm;
154667 }else if( p->op==TK_RETURNING ){
154671 p->op = op;
154678 p->tr_tm = TRIGGER_BEFORE;
154680 p->tr_tm = TRIGGER_AFTER;
154682 mask |= p->tr_tm;
154683 }else if( p->bReturning && p->op==TK_INSERT && op==TK_UPDATE
154685 /* Also fire a RETURNING trigger for an UPSERT */
154686 mask |= p->tr_tm;
154688 p = p->pNext;
154701 ExprList *pChanges, /* Columns that change in an UPDATE statement */
154705 if( (pTab->pTrigger==0 && !tempTriggersExist(pParse->db))
154706 || pParse->disableTriggers
154715 ** Convert the pStep->zTarget string into a SrcList and return a pointer
154720 ** referring to a target in another database. An exception is when the
154728 sqlite3 *db = pParse->db;
154730 char *zName = sqlite3DbStrDup(db, pStep->zTarget);
154732 assert( pSrc==0 || pSrc->nSrc==1 );
154735 Schema *pSchema = pStep->pTrig->pSchema;
154736 pSrc->a[0].zName = zName;
154737 if( pSchema!=db->aDb[1].pSchema ){
154738 assert( pSrc->a[0].fg.fixedSchema || pSrc->a[0].u4.zDatabase==0 );
154739 pSrc->a[0].u4.pSchema = pSchema;
154740 pSrc->a[0].fg.fixedSchema = 1;
154742 if( pStep->pFrom ){
154743 SrcList *pDup = sqlite3SrcListDup(db, pStep->pFrom, 0);
154744 if( pDup && pDup->nSrc>1 && !IN_RENAME_OBJECT ){
154762 ** list is of the form "*". Raise an error if the terms if of the
154770 if( pTerm->op==TK_ASTERISK ) return 1;
154771 if( pTerm->op!=TK_DOT ) return 0;
154772 assert( pTerm->pRight!=0 );
154773 assert( pTerm->pLeft!=0 );
154774 if( pTerm->pRight->op!=TK_ASTERISK ) return 0;
154791 sqlite3 *db = pParse->db;
154794 for(i=0; i<pList->nExpr; i++){
154795 Expr *pOldExpr = pList->a[i].pExpr;
154799 for(jj=0; jj<pTab->nCol; jj++){
154801 if( IsHiddenColumn(pTab->aCol+jj) ) continue;
154802 pNewExpr = sqlite3Expr(db, TK_ID, pTab->aCol[jj].zCnName);
154804 if( !db->mallocFailed ){
154805 struct ExprList_item *pItem = &pNew->a[pNew->nExpr-1];
154806 pItem->zEName = sqlite3DbStrDup(db, pTab->aCol[jj].zCnName);
154807 pItem->fg.eEName = ENAME_NAME;
154813 if( !db->mallocFailed && ALWAYS(pList->a[i].zEName!=0) ){
154814 struct ExprList_item *pItem = &pNew->a[pNew->nExpr-1];
154815 pItem->zEName = sqlite3DbStrDup(db, pList->a[i].zEName);
154816 pItem->fg.eEName = pList->a[i].fg.eEName;
154823 /* If the Expr node is a subquery or an EXISTS operator or an IN operator that
154830 && (pExpr->x.pSelect->selFlags & SF_Correlated)!=0
154840 ** If the SELECT references the table pWalker->u.pTab, then do two things:
154843 ** (2) Set pWalker->eCode to non-zero so that the caller will know
154850 pSrc = pSelect->pSrc;
154852 for(i=0; i<pSrc->nSrc; i++){
154853 if( pSrc->a[i].pSTab==pWalker->u.pTab ){
154854 testcase( pSelect->selFlags & SF_Correlated );
154855 pSelect->selFlags |= SF_Correlated;
154856 pWalker->eCode = 1;
154867 ** subqueries as SF_Correlated. If the subqueries are part of an
154892 ** is generated in-line.
154898 int regIn /* The first in an array of registers */
154900 Vdbe *v = pParse->pVdbe;
154901 sqlite3 *db = pParse->db;
154909 if( !pParse->bReturning ){
154914 assert( db->pParse==pParse );
154915 assert( !pParse->isCreate );
154916 pReturning = pParse->u1.d.pReturning;
154917 if( pTrigger != &(pReturning->retTrig) ){
154924 sSelect.pEList = sqlite3ExprListDup(db, pReturning->pReturnEL, 0);
154926 pFrom->nSrc = 1;
154927 pFrom->a[0].pSTab = pTab;
154928 pFrom->a[0].zName = pTab->zName; /* tag-20240424-1 */
154929 pFrom->a[0].iCursor = -1;
154931 if( pParse->nErr==0 ){
154932 assert( db->mallocFailed==0 );
154936 pNew = sqlite3ExpandReturning(pParse, pReturning->pReturnEL, pTab);
154937 if( pParse->nErr==0 ){
154940 if( pReturning->nRetCol==0 ){
154941 pReturning->nRetCol = pNew->nExpr;
154942 pReturning->iRetCur = pParse->nTab++;
154947 pParse->eTriggerOp = pTrigger->op;
154948 pParse->pTriggerTab = pTab;
154950 && ALWAYS(!db->mallocFailed)
154953 int nCol = pNew->nExpr;
154954 int reg = pParse->nMem+1;
154956 pParse->nMem += nCol+2;
154957 pReturning->iRetReg = reg;
154959 Expr *pCol = pNew->a[i].pExpr;
154960 assert( pCol!=0 ); /* Due to !db->mallocFailed ~9 lines above */
154967 sqlite3VdbeAddOp2(v, OP_NewRowid, pReturning->iRetCur, reg+i+1);
154968 sqlite3VdbeAddOp3(v, OP_Insert, pReturning->iRetCur, reg+i, reg+i+1);
154972 pParse->eTriggerOp = 0;
154973 pParse->pTriggerTab = 0;
154988 Vdbe *v = pParse->pVdbe;
154989 sqlite3 *db = pParse->db;
154991 assert( pParse->pTriggerTab && pParse->pToplevel );
154994 for(pStep=pStepList; pStep; pStep=pStep->pNext){
154997 ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
155005 ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
155006 ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
155008 pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
155009 assert( pParse->okConstFactor==0 );
155012 if( pStep->zSpan ){
155014 sqlite3MPrintf(db, "-- %s", pStep->zSpan),
155019 switch( pStep->op ){
155023 sqlite3ExprListDup(db, pStep->pExprList, 0),
155024 sqlite3ExprDup(db, pStep->pWhere, 0),
155025 pParse->eOrconf, 0, 0, 0
155033 sqlite3SelectDup(db, pStep->pSelect, 0),
155034 sqlite3IdListDup(db, pStep->pIdList),
155035 pParse->eOrconf,
155036 sqlite3UpsertDup(db, pStep->pUpsert)
155044 sqlite3ExprDup(db, pStep->pWhere, 0), 0, 0
155049 default: assert( pStep->op==TK_SELECT ); {
155051 Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
155082 ** Parse context structure pFrom has just been used to create a sub-vdbe
155083 ** (trigger program). If an error has occurred, transfer error information
155087 assert( pFrom->zErrMsg==0 || pFrom->nErr );
155088 assert( pTo->zErrMsg==0 || pTo->nErr );
155089 if( pTo->nErr==0 ){
155090 pTo->zErrMsg = pFrom->zErrMsg;
155091 pTo->nErr = pFrom->nErr;
155092 pTo->rc = pFrom->rc;
155094 sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
155099 ** Create and populate a new TriggerPrg object with a sub-program
155109 sqlite3 *db = pParse->db; /* Database handle */
155113 NameContext sNC; /* Name context for sub-vdbe */
155114 SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
155116 Parse sSubParse; /* Parse context for sub-vdbe */
155118 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
155119 assert( pTop->pVdbe );
155122 ** are freed if an error occurs, link them into the Parse.pTriggerPrg
155123 ** list of the top-level Parse object sooner rather than later. */
155126 pPrg->pNext = pTop->pTriggerPrg;
155127 pTop->pTriggerPrg = pPrg;
155128 pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
155130 sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
155131 pPrg->pTrigger = pTrigger;
155132 pPrg->orconf = orconf;
155133 pPrg->aColmask[0] = 0xffffffff;
155134 pPrg->aColmask[1] = 0xffffffff;
155137 ** trigger sub-program. */
155143 sSubParse.zAuthContext = pTrigger->zName;
155144 sSubParse.eTriggerOp = pTrigger->op;
155145 sSubParse.nQueryLoop = pParse->nQueryLoop;
155146 sSubParse.prepFlags = pParse->prepFlags;
155153 pTrigger->zName, onErrorText(orconf),
155154 (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
155155 (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
155156 (pTrigger->op==TK_INSERT ? "INSERT" : ""),
155157 (pTrigger->op==TK_DELETE ? "DELETE" : ""),
155158 pTab->zName
155161 if( pTrigger->zName ){
155162 sqlite3VdbeChangeP4(v, -1,
155163 sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
155169 ** (or NULL) the sub-vdbe is immediately halted by jumping to the
155171 if( pTrigger->pWhen ){
155172 pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
155173 if( db->mallocFailed==0
155182 /* Code the trigger program into the sub-vdbe. */
155183 codeTriggerProgram(&sSubParse, pTrigger->step_list, orconf);
155185 /* Insert an OP_Halt at the end of the sub-program. */
155190 VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
155193 if( pParse->nErr==0 ){
155194 assert( db->mallocFailed==0 );
155195 pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
155197 pProgram->nMem = sSubParse.nMem;
155198 pProgram->nCsr = sSubParse.nTab;
155199 pProgram->token = (void *)pTrigger;
155200 pPrg->aColmask[0] = sSubParse.oldmask;
155201 pPrg->aColmask[1] = sSubParse.newmask;
155213 ** Return a pointer to a TriggerPrg object containing the sub-program for
155227 assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
155230 ** process of being coded). If this is the case, then an entry with
155232 ** in the Parse.pTriggerPrg list. Search for such an entry. */
155233 for(pPrg=pRoot->pTriggerPrg;
155234 pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
155235 pPrg=pPrg->pNext
155238 /* If an existing TriggerPrg could not be located, create a new one. */
155241 pParse->db->errByteOffset = -1;
155264 assert( pPrg || pParse->nErr );
155267 ** is a pointer to the sub-vdbe containing the trigger program. */
155269 int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
155271 sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
155272 (const char *)pPrg->pProgram, P4_SUBPROGRAM);
155274 (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
155276 /* Set the P5 operand of the OP_Program instruction to non-zero if
155278 ** invocation is disallowed if (a) the sub-program is really a trigger,
155286 ** This is called to code the required FOR EACH ROW triggers for an operation
155289 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
155293 ** operation on pTab, this function is a no-op.
155295 ** The reg argument is the address of the first in an array of registers
155298 ** (a copy of pTab->nCol), then registers are populated as follows:
155301 ** ------------------------------------------------------
155303 ** reg+1 OLD.* value of left-most column of pTab
155305 ** reg+N OLD.* value of right-most column of pTab
155307 ** reg+N+2 NEW.* value of left-most column of pTab
155309 ** reg+N+N+1 NEW.* value of right-most column of pTab
155315 ** are never accessed, and so are not allocated by the caller. So, for an
155323 ** raises an IGNORE exception.
155332 int reg, /* The first in an array of registers (see above) */
155342 for(p=pTrigger; p; p=p->pNext){
155347 assert( p->pSchema!=0 );
155348 assert( p->pTabSchema!=0 );
155349 assert( p->pSchema==p->pTabSchema
155350 || p->pSchema==pParse->db->aDb[1].pSchema );
155353 ** 1. The trigger is an exact match to the current DML statement
155355 ** doing the UPDATE part of an UPSERT.
155357 if( (p->op==op || (p->bReturning && p->op==TK_INSERT && op==TK_UPDATE))
155358 && p->tr_tm==tr_tm
155359 && checkColumnOverlap(p->pColumns, pChanges)
155361 if( !p->bReturning ){
155371 ** Triggers may access values stored in the old.* or new.* pseudo-table.
155372 ** This function returns a 32-bit bitmask indicating which columns of the
155375 ** old.* record into memory when executing an UPDATE or DELETE command.
155377 ** Bit 0 of the returned mask is set if the left-most column of the
155378 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
155381 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
155412 for(p=pTrigger; p; p=p->pNext){
155413 if( p->op==op
155414 && (tr_tm&p->tr_tm)
155415 && checkColumnOverlap(p->pColumns,pChanges)
155417 if( p->bReturning ){
155423 mask |= pPrg->aColmask[isNew];
155467 ** The most recently coded instruction was an OP_Column to retrieve the
155468 ** i-th column of table pTab. This routine sets the P4 parameter of the
155473 ** was created, or added later to the table definition by an ALTER TABLE
155474 ** command. If the latter, then the row-records in the table btree on disk
155477 ** If the former, then all row-records are guaranteed to include a value
155480 ** Column definitions created by an ALTER TABLE command may only have
155491 ** If column as REAL affinity and the table is an ordinary b-tree table
155492 ** (not a virtual table) then the value might have been stored as an
155493 ** integer. In that case, add an OP_RealAffinity opcode to make sure
155499 assert( pTab->nCol>i );
155500 pCol = &pTab->aCol[i];
155501 if( pCol->iDflt ){
155505 VdbeComment((v, "%s.%s", pTab->zName, pCol->zCnName));
155506 assert( i<pTab->nCol );
155509 pCol->affinity, &pValue);
155515 if( pCol->affinity==SQLITE_AFF_REAL && !IsVirtual(pTab) ){
155524 ** and false if not. This is an optimization. False-positives are a
155525 ** performance degradation, but false-negatives can result in a corrupt
155528 ** aXRef[j] will be non-negative if column j of the original table is
155538 i16 iIdxCol = pIdx->aiColumn[iCol];
155544 assert( pIdx->aColExpr!=0 );
155545 assert( pIdx->aColExpr->a[iCol].pExpr!=0 );
155546 return sqlite3ExprReferencesUpdatedColumn(pIdx->aColExpr->a[iCol].pExpr,
155552 ** expression might change values due to an UPDATE. Return true if
155554 ** to be unchanged. This is an optimization. False-positives are a
155555 ** performance degradation, but false-negatives can result in a corrupt
155558 ** aXRef[j] will be non-negative if column j of the original table is
155567 if( pIdx->pPartIdxWhere==0 ) return 0;
155568 return sqlite3ExprReferencesUpdatedColumn(pIdx->pPartIdxWhere,
155573 ** Allocate and return a pointer to an expression of type TK_ROW with
155576 ** table in the source-list (pSrc->a[0]).
155580 if( pRet ) pRet->iColumn = iCol+1;
155588 ** SELECT <other-columns>, pChanges FROM pTabList WHERE pWhere
155596 ** SELECT <other-columns>, pChanges FROM pTabList
155598 ** GROUP BY <other-columns>
155604 ** the <other-columns> in the query above are is determined by the type
155605 ** of table pTabList->a[0].pTab.
155608 ** PRIMARY KEY. In this case <other-columns> are the primary key columns
155612 ** If the table is actually a view, then <other-columns> are all columns of
155616 ** If the table is a virtual or ordinary intkey table, then <other-columns>
155619 ** rowid value in <other-columns> is used as the integer key, and the
155639 sqlite3 *db = pParse->db;
155640 Table *pTab = pTabList->a[0].pSTab;
155660 assert( pTabList->nSrc>1 );
155662 assert( pSrc->a[0].fg.notCte );
155663 pSrc->a[0].iCursor = -1;
155664 pSrc->a[0].pSTab->nTabRef--;
155665 pSrc->a[0].pSTab = 0;
155668 for(i=0; i<pPk->nKeyCol; i++){
155669 Expr *pNew = exprRowColumn(pParse, pPk->aiColumn[i]);
155679 for(i=0; i<pTab->nCol; i++){
155692 assert( pChanges!=0 || pParse->db->mallocFailed );
155694 for(i=0; i<pChanges->nExpr; i++){
155696 sqlite3ExprDup(db, pChanges->a[i].pExpr, 0)
155704 if( pSelect ) pSelect->selFlags |= SF_OrderByReqd;
155706 dest.iSDParm2 = (pPk ? pPk->nKeyCol : -1);
155712 ** Process an UPDATE statement.
155744 int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
155745 ** an expression for the i-th column of the table.
155746 ** aXRef[i]==-1 if the i-th column is not changed. */
155752 int iRowidExpr = -1; /* Index of "rowid=" (or IPK) assignment in pChanges */
155754 NameContext sNC; /* The name-context to resolve expressions in */
155776 int nChangeFrom = 0; /* If there is a FROM, pChanges->nExpr, else 0 */
155788 db = pParse->db;
155789 assert( db->pParse==pParse );
155790 if( pParse->nErr ){
155793 assert( db->mallocFailed==0 );
155799 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
155821 sqlite3TreeViewUpdate(pParse->pWith, pTabList, pChanges, pWhere,
155827 ** in the change-list. Otherwise, set it to 0. There cannot be a FROM
155829 ** an UPSERT statement. */
155830 nChangeFrom = (pTabList->nSrc>1) ? pChanges->nExpr : 0;
155855 iBaseCur = iDataCur = pParse->nTab++;
155858 testcase( pPk!=0 && pPk!=pTab->pIndex );
155859 for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
155861 iDataCur = pParse->nTab;
155863 pParse->nTab++;
155866 /* On an UPSERT, reuse the same cursors already opened by INSERT */
155867 iDataCur = pUpsert->iDataCur;
155868 iIdxCur = pUpsert->iIdxCur;
155869 pParse->nTab = iBaseCur;
155871 pTabList->a[0].iCursor = iDataCur;
155876 aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx+1) + nIdx+2 );
155878 aRegIdx = aXRef+pTab->nCol;
155882 for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
155884 /* Initialize the name-context */
155902 for(i=0; i<pChanges->nExpr; i++){
155903 /* If this is an UPDATE with a FROM clause, do not resolve expressions
155905 if( nChangeFrom==0 && sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
155908 j = sqlite3ColumnIndex(pTab, pChanges->a[i].zEName);
155910 if( j==pTab->iPKey ){
155912 pRowidExpr = pChanges->a[i].pExpr;
155914 }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
155918 else if( pTab->aCol[j].colFlags & COLFLAG_GENERATED ){
155919 testcase( pTab->aCol[j].colFlags & COLFLAG_VIRTUAL );
155920 testcase( pTab->aCol[j].colFlags & COLFLAG_STORED );
155923 pTab->aCol[j].zCnName);
155929 if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zEName) ){
155930 j = -1;
155932 pRowidExpr = pChanges->a[i].pExpr;
155935 sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zEName);
155936 pParse->checkSchema = 1;
155943 rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
155944 j<0 ? "ROWID" : pTab->aCol[j].zCnName,
155945 db->aDb[iDb].zDbSName);
155949 aXRef[j] = -1;
155963 ** is non-negative, so the value of aXRef[] for generated columns can be
155964 ** set to any non-negative number. We use 99999 so that the value is
155967 if( pTab->tabFlags & TF_HasGenerated ){
155969 testcase( pTab->tabFlags & TF_HasVirtual );
155970 testcase( pTab->tabFlags & TF_HasStored );
155973 for(i=0; i<pTab->nCol; i++){
155975 if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 ) continue;
155977 sqlite3ColumnExpr(pTab, &pTab->aCol[i]),
155993 pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
156002 for(nAllIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nAllIdx++){
156007 reg = ++pParse->nMem;
156008 pParse->nMem += pIdx->nColumn;
156011 for(i=0; i<pIdx->nKeyCol; i++){
156013 reg = ++pParse->nMem;
156014 pParse->nMem += pIdx->nColumn;
156015 if( onError==OE_Default && pIdx->onError==OE_Replace ){
156025 aRegIdx[nAllIdx] = ++pParse->nMem; /* Register storing the table record */
156032 if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
156041 ** two-pass update algorithm. */
156042 assert( aRegIdx[nAllIdx]==pParse->nMem );
156044 regOldRowid = regNewRowid = ++pParse->nMem;
156046 regOld = pParse->nMem + 1;
156047 pParse->nMem += pTab->nCol;
156050 regNewRowid = ++pParse->nMem;
156052 regNew = pParse->nMem + 1;
156053 pParse->nMem += pTab->nCol;
156058 sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
156062 ** an ephemeral table.
156093 /* Not an UPSERT. Normal processing. Begin by
156095 if( (db->flags&SQLITE_CountRows)!=0
156096 && !pParse->pTriggerTab
156097 && !pParse->nested
156098 && !pParse->bReturning
156101 regRowCount = ++pParse->nMem;
156107 iEph = pParse->nTab++;
156111 nPk = pPk ? pPk->nKeyCol : 0;
156112 iPk = pParse->nMem+1;
156113 pParse->nMem += nPk;
156114 pParse->nMem += nChangeFrom;
156115 regKey = ++pParse->nMem;
156117 int nEphCol = nPk + nChangeFrom + (isView ? pTab->nCol : 0);
156118 iEph = pParse->nTab++;
156119 if( pPk ) sqlite3VdbeAddOp3(v, OP_Null, 0, iPk, iPk+nPk-1);
156124 pKeyInfo->nAllField = nEphCol;
156146 /* If this is an UPSERT, then all cursors have already been opened by
156158 ** Do not consider a single-pass strategy for a multi-row update if
156168 if( !pParse->nested
156180 /* A one-pass strategy that might update more than one row may not
156182 ** updated. Otherwise, if there is an index on "b", statements like
156183 ** the following could create an infinite loop:
156188 ** strategy that uses an index for which one or more columns are being
156196 if( iCur>=0 && iCur!=iDataCur && aToOpen[iCur-iBaseCur] ){
156206 ** mode, write the rowid into the FIFO. In either of the one-pass modes,
156210 aRegIdx[nAllIdx] = ++pParse->nMem;
156216 /* Read the PK of the current row into an array of registers. In
156222 assert( pPk->aiColumn[i]>=0 );
156224 pPk->aiColumn[i], iPk+i);
156250 if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
156251 if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
156254 if( eOnePass==ONEPASS_MULTI && (nIdx-(aiCurOnePass[1]>=0))>0 ){
156332 /* Compute the old pre-UPDATE content of the row being changed, if that
156339 for(i=0; i<pTab->nCol; i++){
156340 u32 colFlags = pTab->aCol[i].colFlags;
156376 for(i=0, k=regNew; i<pTab->nCol; i++, k++){
156377 if( i==pTab->iPKey ){
156379 }else if( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)!=0 ){
156380 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
156385 int nOff = (isView ? pTab->nCol : nPk);
156389 sqlite3ExprCode(pParse, pChanges->a[j].pExpr, k);
156407 if( pTab->tabFlags & TF_HasGenerated ){
156408 testcase( pTab->tabFlags & TF_HasVirtual );
156409 testcase( pTab->tabFlags & TF_HasStored );
156423 /* The row-trigger may have deleted the row being updated. In this
156425 ** required. This behavior - what happens when the row being updated
156426 ** is deleted or renamed by a BEFORE trigger - is left undefined in the
156437 /* After-BEFORE-trigger-reload-loop:
156443 ** BEFORE trigger runs. See test case trigger1-18.0 (added 2018-04-26)
156444 ** for an example.
156446 for(i=0, k=regNew; i<pTab->nCol; i++, k++){
156447 if( pTab->aCol[i].colFlags & COLFLAG_GENERATED ){
156448 if( pTab->aCol[i].colFlags & COLFLAG_VIRTUAL ) k--;
156449 }else if( aXRef[i]<0 && i!=pTab->iPKey ){
156454 if( pTab->tabFlags & TF_HasGenerated ){
156455 testcase( pTab->tabFlags & TF_HasVirtual );
156456 testcase( pTab->tabFlags & TF_HasStored );
156488 sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
156501 ** to invoke the pre-update hook.
156504 ** pre-update hook. If the caller invokes preupdate_new(), the returned
156518 if( !pParse->nested ){
156561 /* Nothing to do at end-of-loop for a single-pass */
156575 if( pParse->nested==0 && pParse->pTriggerTab==0 && pUpsert==0 ){
156611 ** Generate code for an UPDATE of a virtual table.
156613 ** There are two possible strategies - the default and the special
156617 ** The default strategy is to create an ephemeral table that contains
156627 ** The "onepass" strategy does not use an ephemeral table. Instead, it
156641 Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
156644 sqlite3 *db = pParse->db; /* Database connection */
156647 int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
156651 int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
156660 ephemTab = pParse->nTab++;
156662 regArg = pParse->nMem + 1;
156663 pParse->nMem += nArg;
156664 if( pSrc->nSrc>1 ){
156678 assert( pPk->nKeyCol==1 );
156679 iPk = pPk->aiColumn[0];
156681 pRow = sqlite3ExprDup(db, pChanges->a[aXRef[iPk]].pExpr, 0);
156688 for(i=0; i<pTab->nCol; i++){
156691 sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0)
156695 if( pRowExpr ) pRowExpr->op2 = OPFLAG_NOCHNG;
156704 regRec = ++pParse->nMem;
156705 regRowid = ++pParse->nMem;
156714 for(i=0; i<pTab->nCol; i++){
156715 assert( (pTab->aCol[i].colFlags & COLFLAG_GENERATED)==0 );
156717 sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
156735 assert( pPk->nKeyCol==1 );
156736 iPk = pPk->aiColumn[0];
156747 /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
156757 /* Signal an assert() within OP_MakeRecord that it is allowed to
156758 ** accept no-change records with serial_type 10 */
156769 if( pSrc->nSrc==1 ){
156802 ** 2018-04-12
156823 Upsert *pNext = p->pNextUpsert;
156824 sqlite3ExprListDelete(db, p->pUpsertTarget);
156825 sqlite3ExprDelete(db, p->pUpsertTargetWhere);
156826 sqlite3ExprListDelete(db, p->pUpsertSet);
156827 sqlite3ExprDelete(db, p->pUpsertWhere);
156828 sqlite3DbFree(db, p->pToFree);
156839 ** Duplicate an Upsert object.
156844 sqlite3ExprListDup(db, p->pUpsertTarget, 0),
156845 sqlite3ExprDup(db, p->pUpsertTargetWhere, 0),
156846 sqlite3ExprListDup(db, p->pUpsertSet, 0),
156847 sqlite3ExprDup(db, p->pUpsertWhere, 0),
156848 sqlite3UpsertDup(db, p->pNextUpsert)
156873 pNew->pUpsertTarget = pTarget;
156874 pNew->pUpsertTargetWhere = pTargetWhere;
156875 pNew->pUpsertSet = pSet;
156876 pNew->pUpsertWhere = pWhere;
156877 pNew->isDoUpdate = pSet!=0;
156878 pNew->pNextUpsert = pNext;
156885 ** symbols in the conflict-target.
156887 ** Return SQLITE_OK if everything works, or an error code is something
156900 ExprList *pTarget; /* The conflict-target clause */
156901 Expr *pTerm; /* One term of the conflict-target clause */
156903 Expr sCol[2]; /* Index column converted into an Expr */
156906 assert( pTabList->nSrc==1 );
156907 assert( pTabList->a[0].pSTab!=0 );
156909 assert( pUpsert->pUpsertTarget!=0 );
156911 /* Resolve all symbolic names in the conflict-target clause, which
156912 ** includes both the list of columns and the optional partial-index
156918 for(; pUpsert && pUpsert->pUpsertTarget;
156919 pUpsert=pUpsert->pNextUpsert, nClause++){
156920 rc = sqlite3ResolveExprListNames(&sNC, pUpsert->pUpsertTarget);
156922 rc = sqlite3ResolveExprNames(&sNC, pUpsert->pUpsertTargetWhere);
156926 pTab = pTabList->a[0].pSTab;
156927 pTarget = pUpsert->pUpsertTarget;
156928 iCursor = pTabList->a[0].iCursor;
156930 && pTarget->nExpr==1
156931 && (pTerm = pTarget->a[0].pExpr)->op==TK_COLUMN
156932 && pTerm->iColumn==XN_ROWID
156934 /* The conflict-target is the rowid of the primary table */
156935 assert( pUpsert->pUpsertIdx==0 );
156939 /* Initialize sCol[0..1] to be an expression parse tree for a
156940 ** single column of an index. The sCol[0] node will be the TK_COLLATE
156943 ** prior to comparing against the conflict-target expression.
156949 sCol[1].iTable = pTabList->a[0].iCursor;
156952 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
156955 if( pTarget->nExpr!=pIdx->nKeyCol ) continue;
156956 if( pIdx->pPartIdxWhere ){
156957 if( pUpsert->pUpsertTargetWhere==0 ) continue;
156958 if( sqlite3ExprCompare(pParse, pUpsert->pUpsertTargetWhere,
156959 pIdx->pPartIdxWhere, iCursor)!=0 ){
156963 nn = pIdx->nKeyCol;
156966 sCol[0].u.zToken = (char*)pIdx->azColl[ii];
156967 if( pIdx->aiColumn[ii]==XN_EXPR ){
156968 assert( pIdx->aColExpr!=0 );
156969 assert( pIdx->aColExpr->nExpr>ii );
156970 assert( pIdx->bHasExpr );
156971 pExpr = pIdx->aColExpr->a[ii].pExpr;
156972 if( pExpr->op!=TK_COLLATE ){
156978 sCol[1].iColumn = pIdx->aiColumn[ii];
156982 if( sqlite3ExprCompare(0,pTarget->a[jj].pExpr,pExpr,iCursor)<2 ){
156996 pUpsert->pUpsertIdx = pIdx;
156998 /* Really this should be an error. The isDup ON CONFLICT clause will
157000 ** after multi-CONFLICT upsert was added, and so we silently ignore
157003 pUpsert->isDup = 1;
157007 if( pUpsert->pUpsertIdx==0 ){
157009 if( nClause==0 && pUpsert->pNextUpsert==0 ){
157030 pNext = pUpsert->pNextUpsert;
157031 while( 1 /*exit-by-return*/ ){
157033 if( pNext->pUpsertTarget==0 ) return 1;
157034 if( pNext->pUpsertIdx==0 ) return 1;
157035 if( !pNext->isDup ) return 0;
157036 pNext = pNext->pNextUpsert;
157050 && pUpsert->pUpsertTarget!=0
157051 && pUpsert->pUpsertIdx!=pIdx
157053 pUpsert = pUpsert->pNextUpsert;
157059 ** Generate bytecode that does an UPDATE as part of an upsert.
157062 ** In this case parameter iCur is a cursor open on the table b-tree that
157068 Parse *pParse, /* The parsing and code-generating context */
157074 Vdbe *v = pParse->pVdbe;
157075 sqlite3 *db = pParse->db;
157083 iDataCur = pUpsert->iDataCur;
157095 int nPk = pPk->nKeyCol;
157096 int iPk = pParse->nMem+1;
157097 pParse->nMem += nPk;
157100 assert( pPk->aiColumn[i]>=0 );
157101 k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[i]);
157103 VdbeComment((v, "%s.%s", pIdx->zName,
157104 pTab->aCol[pPk->aiColumn[i]].zCnName));
157115 /* pUpsert does not own pTop->pUpsertSrc - the outer INSERT statement does.
157117 pSrc = sqlite3SrcListDup(db, pTop->pUpsertSrc, 0);
157119 for(i=0; i<pTab->nCol; i++){
157120 if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
157121 sqlite3VdbeAddOp1(v, OP_RealAffinity, pTop->regData+i);
157124 sqlite3Update(pParse, pSrc, sqlite3ExprListDup(db,pUpsert->pUpsertSet,0),
157125 sqlite3ExprDup(db,pUpsert->pUpsertWhere,0), OE_Abort, 0, 0, pUpsert);
157169 rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
157241 if( pParse->nErr ) goto build_vacuum_end;
157244 /* Default behavior: Report an error if the argument to VACUUM is
157250 ** to VACUUM are silently ignored. This is a back-out of a bug fix that
157251 ** occurred on 2016-08-19 (https://sqlite.org/src/info/083f9e6270).
157254 iDb = sqlite3FindDb(pParse->db, pNm);
157261 iIntoReg = ++pParse->nMem;
157268 sqlite3ExprDelete(pParse->db, pInto);
157284 u32 saved_mDbFlags; /* Saved value of db->mDbFlags */
157285 u64 saved_flags; /* Saved value of db->flags */
157286 i64 saved_nChange; /* Saved value of db->nChange */
157287 i64 saved_nTotalChange; /* Saved value of db->nTotalChange */
157288 u32 saved_openFlags; /* Saved value of db->openFlags */
157298 char zDbVacuum[42]; /* Name of the ATTACH-ed database used for vacuum */
157301 if( !db->autoCommit ){
157303 return SQLITE_ERROR; /* IMP: R-12218-18073 */
157305 if( db->nVdbeActive>1 ){
157306 sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
157307 return SQLITE_ERROR; /* IMP: R-15610-35227 */
157309 saved_openFlags = db->openFlags;
157312 sqlite3SetString(pzErrMsg, db, "non-text filename");
157316 db->openFlags &= ~SQLITE_OPEN_READONLY;
157317 db->openFlags |= SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE;
157323 ** restored before returning. Then set the writable-schema flag, and
157325 saved_flags = db->flags;
157326 saved_mDbFlags = db->mDbFlags;
157327 saved_nChange = db->nChange;
157328 saved_nTotalChange = db->nTotalChange;
157329 saved_mTrace = db->mTrace;
157330 db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_Comments;
157331 db->mDbFlags |= DBFLAG_PreferBuiltin | DBFLAG_Vacuum;
157332 db->flags &= ~(u64)(SQLITE_ForeignKeys | SQLITE_ReverseOrder
157334 db->mTrace = 0;
157336 zDbMain = db->aDb[iDb].zDbSName;
157337 pMain = db->aDb[iDb].pBt;
157346 ** An optimization would be to use a non-journaled pager.
157356 nDb = db->nDb;
157358 db->openFlags = saved_openFlags;
157360 assert( (db->nDb-1)==nDb );
157361 pDb = &db->aDb[nDb];
157362 assert( strcmp(pDb->zDbSName,zDbVacuum)==0 );
157363 pTemp = pDb->pBt;
157367 if( id->pMethods!=0 && (sqlite3OsFileSize(id, &sz)!=SQLITE_OK || sz>0) ){
157372 db->mDbFlags |= DBFLAG_VacuumInto;
157374 /* For a VACUUM INTO, the pager-flags are set to the same values as
157377 pgflags = db->aDb[iDb].safety_level | (db->flags & PAGER_FLAGS_MASK);
157381 sqlite3BtreeSetCacheSize(pTemp, db->aDb[iDb].pSchema->cache_size);
157385 /* Begin a transaction and take an exclusive lock on the main database
157387 ** to ensure that we do not try to change the page-size on a WAL database.
157399 db->nextPagesize = 0;
157403 || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
157404 || NEVER(db->mallocFailed)
157411 sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
157418 db->init.iDb = nDb; /* force new CREATE statements into vacuum_db */
157432 db->init.iDb = 0;
157435 ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
157445 assert( (db->mDbFlags & DBFLAG_Vacuum)!=0 );
157446 db->mDbFlags &= ~DBFLAG_Vacuum;
157465 ** both transactions are closed by this block - the main database
157466 ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
157475 ** are an increment to apply to the meta value after the vacuum.
157519 /* Restore the original value of db->flags */
157520 db->init.iDb = 0;
157521 db->mDbFlags = saved_mDbFlags;
157522 db->flags = saved_flags;
157523 db->nChange = saved_nChange;
157524 db->nTotalChange = saved_nTotalChange;
157525 db->mTrace = saved_mTrace;
157526 sqlite3BtreeSetPageSize(pMain, -1, 0, 1);
157528 /* Currently there is an SQL level transaction open on the vacuum
157535 db->autoCommit = 1;
157538 sqlite3BtreeClose(pDb->pBt);
157539 pDb->pBt = 0;
157540 pDb->pSchema = 0;
157543 /* This both clears the schemas and reduces the size of the db->aDb[]
157572 ** sqlite3.pVtabCtx member variable is set to point to an instance of
157614 pMod->zName = zCopy;
157615 pMod->pModule = pModule;
157616 pMod->pAux = pAux;
157617 pMod->xDestroy = xDestroy;
157618 pMod->pEpoTab = 0;
157619 pMod->nRefModule = 1;
157621 pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
157649 sqlite3_mutex_enter(db->mutex);
157653 sqlite3_mutex_leave(db->mutex);
157659 ** External API function used to create a new virtual-table module.
157674 ** External API function used to create a new virtual-table module.
157690 ** External API to drop all virtual-table modules, except those named
157698 for(pThis=sqliteHashFirst(&db->aModule); pThis; pThis=pNext){
157703 for(ii=0; azNames[ii]!=0 && strcmp(azNames[ii],pMod->zName)!=0; ii++){}
157706 createModule(db, pMod->zName, 0, 0, 0);
157716 assert( pMod->nRefModule>0 );
157717 pMod->nRefModule--;
157718 if( pMod->nRefModule==0 ){
157719 if( pMod->xDestroy ){
157720 pMod->xDestroy(pMod->pAux);
157722 assert( pMod->pEpoTab==0 );
157730 ** If an unlock is omitted, resources leaks will occur.
157736 pVTab->nRef++;
157741 ** pTab is a pointer to a Table structure representing a virtual-table.
157743 ** this virtual-table, if one has been created, or NULL otherwise.
157748 for(pVtab=pTab->u.vtab.p; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
157753 ** Decrement the ref-count on a virtual table object. When the ref-count
157757 sqlite3 *db = pVTab->db;
157760 assert( pVTab->nRef>0 );
157761 assert( db->eOpenState==SQLITE_STATE_OPEN
157762 || db->eOpenState==SQLITE_STATE_ZOMBIE );
157764 pVTab->nRef--;
157765 if( pVTab->nRef==0 ){
157766 sqlite3_vtab *p = pVTab->pVtab;
157768 p->pModule->xDisconnect(p);
157770 sqlite3VtabModuleUnref(pVTab->db, pVTab->pMod);
157777 ** p->u.vtab.p list to the sqlite3.pDisconnect lists of their associated
157780 ** connection db is left in the p->u.vtab.p list.
157787 pVTable = p->u.vtab.p;
157788 p->u.vtab.p = 0;
157792 ** above function sqlite3VtabUnlockList() for an explanation of why
157794 ** database connection that may have an entry in the p->u.vtab.p list.
157796 assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
157799 sqlite3 *db2 = pVTable->db;
157800 VTable *pNext = pVTable->pNext;
157804 p->u.vtab.p = pRet;
157805 pRet->pNext = 0;
157807 pVTable->pNext = db2->pDisconnect;
157808 db2->pDisconnect = pVTable;
157820 ** list in p->pVTab. It also decrements the VTable ref count. This is
157823 ** be being used by other shared-cache connections).
157830 assert( sqlite3_mutex_held(db->mutex) );
157832 for(ppVTab=&p->u.vtab.p; *ppVTab; ppVTab=&(*ppVTab)->pNext){
157833 if( (*ppVTab)->db==db ){
157835 *ppVTab = pVTab->pNext;
157847 ** shared b-tree databases opened using connection db are held by the
157857 ** or, if the virtual table is stored in a non-sharable database, then
157861 ** by multiple threads. It is thread-safe.
157864 VTable *p = db->pDisconnect;
157867 assert( sqlite3_mutex_held(db->mutex) );
157870 db->pDisconnect = 0;
157872 VTable *pNext = p->pNext;
157880 ** Clear any and all virtual-table information from the Table record.
157884 ** Since it is a virtual-table, the Table structure contains a pointer
157896 if( db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
157897 if( p->u.vtab.azArg ){
157899 for(i=0; i<p->u.vtab.nArg; i++){
157900 if( i!=1 ) sqlite3DbFree(db, p->u.vtab.azArg[i]);
157902 sqlite3DbFree(db, p->u.vtab.azArg);
157907 ** Add a new module argument to pTable->u.vtab.azArg[].
157908 ** The string is not copied - the pointer is stored. The
157915 sqlite3 *db = pParse->db;
157918 nBytes = sizeof(char *)*(2+pTable->u.vtab.nArg);
157919 if( pTable->u.vtab.nArg+3>=db->aLimit[SQLITE_LIMIT_COLUMN] ){
157920 sqlite3ErrorMsg(pParse, "too many columns on %s", pTable->zName);
157922 azModuleArg = sqlite3DbRealloc(db, pTable->u.vtab.azArg, nBytes);
157926 int i = pTable->u.vtab.nArg++;
157929 pTable->u.vtab.azArg = azModuleArg;
157949 pTable = pParse->pNewTable;
157951 assert( 0==pTable->pIndex );
157952 pTable->eTabType = TABTYP_VTAB;
157954 db = pParse->db;
157956 assert( pTable->u.vtab.nArg==0 );
157959 addModuleArgument(pParse, pTable, sqlite3DbStrDup(db, pTable->zName));
157960 assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
157961 || (pParse->sNameToken.z==pName1->z && pName2->z==0)
157963 pParse->sNameToken.n = (int)(
157964 &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
157973 if( pTable->u.vtab.azArg ){
157974 int iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
157976 sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
157977 pTable->u.vtab.azArg[0], pParse->db->aDb[iDb].zDbSName);
157984 ** in pParse->zArg[] and appends it to the list of arguments on the
157985 ** virtual table currently under construction in pParse->pTable.
157988 if( pParse->sArg.z && pParse->pNewTable ){
157989 const char *z = (const char*)pParse->sArg.z;
157990 int n = pParse->sArg.n;
157991 sqlite3 *db = pParse->db;
157992 addModuleArgument(pParse, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
158001 Table *pTab = pParse->pNewTable; /* The table being constructed */
158002 sqlite3 *db = pParse->db; /* The database connection */
158007 pParse->sArg.z = 0;
158008 if( pTab->u.vtab.nArg<1 ) return;
158016 if( !db->init.busy ){
158027 pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
158029 zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
158035 ** The VM register number pParse->u1.cr.regRowid holds the rowid of an
158039 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
158040 assert( pParse->isCreate );
158045 db->aDb[iDb].zDbSName,
158046 pTab->zName,
158047 pTab->zName,
158049 pParse->u1.cr.regRowid
158055 zWhere = sqlite3MPrintf(db, "name=%Q AND sql=%Q", pTab->zName, zStmt);
158059 iReg = ++pParse->nMem;
158060 sqlite3VdbeLoadString(v, iReg, pTab->zName);
158063 /* If we are rereading the sqlite_schema table create the in-memory
158066 Schema *pSchema = pTab->pSchema;
158067 const char *zName = pTab->zName;
158070 pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
158076 pParse->pNewTable = 0;
158082 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
158086 pParse->sArg.z = 0;
158087 pParse->sArg.n = 0;
158092 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
158095 Token *pArg = &pParse->sArg;
158096 if( pArg->z==0 ){
158097 pArg->z = p->z;
158098 pArg->n = p->n;
158100 assert(pArg->z <= p->z);
158101 pArg->n = (int)(&p->z[p->n] - pArg->z);
158121 int nArg = pTab->u.vtab.nArg;
158128 azArg = (const char *const*)pTab->u.vtab.azArg;
158130 /* Check that the virtual-table is not already being initialized */
158131 for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
158132 if( pCtx->pTab==pTab ){
158134 "vtable constructor called recursively: %s", pTab->zName
158140 zModuleName = sqlite3DbStrDup(db, pTab->zName);
158151 pVTable->db = db;
158152 pVTable->pMod = pMod;
158153 pVTable->eVtabRisk = SQLITE_VTABRISK_Normal;
158155 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
158156 pTab->u.vtab.azArg[1] = db->aDb[iDb].zDbSName;
158159 assert( &db->pVtabCtx );
158163 sCtx.pPrior = db->pVtabCtx;
158165 db->pVtabCtx = &sCtx;
158166 pTab->nTabRef++;
158167 rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
158169 assert( pTab->nTabRef>1 || rc!=SQLITE_OK );
158171 db->pVtabCtx = sCtx.pPrior;
158183 }else if( ALWAYS(pVTable->pVtab) ){
158186 memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
158187 pVTable->pVtab->pModule = pMod->pModule;
158188 pMod->nRefModule++;
158189 pVTable->nRef = 1;
158199 ** into the linked list headed by pTab->u.vtab.p. Then loop through the
158203 pVTable->pNext = pTab->u.vtab.p;
158204 pTab->u.vtab.p = pVTable;
158206 for(iCol=0; iCol<pTab->nCol; iCol++){
158207 char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
158213 && (i==0 || zType[i-1]==' ')
158226 assert(zType[i-1]==' ');
158227 zType[i-1] = '\0';
158229 pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
158230 pTab->tabFlags |= TF_HasHidden;
158233 pTab->tabFlags |= oooHidden;
158245 ** of the virtual table pTab. If an error occurs, an error code is returned
158246 ** and an error left in pParse.
158248 ** This call is a no-op if table pTab is not a virtual table.
158251 sqlite3 *db = pParse->db;
158263 zMod = pTab->u.vtab.azArg[0];
158264 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
158267 const char *zModule = pTab->u.vtab.azArg[0];
158272 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
158275 pParse->rc = rc;
158283 ** Grow the db->aVTrans[] array so that there is room for at least one
158284 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
158290 if( (db->nVTrans%ARRAY_INCR)==0 ){
158293 ((sqlite3_int64)db->nVTrans + ARRAY_INCR);
158294 aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
158298 memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
158299 db->aVTrans = aVTrans;
158311 db->aVTrans[db->nVTrans++] = pVTab;
158319 ** If an error occurs, *pzErr is set to point to an English language
158320 ** description of the error and an SQLITE_XXX error code is returned.
158329 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
158330 assert( pTab && IsVirtual(pTab) && !pTab->u.vtab.p );
158333 zMod = pTab->u.vtab.azArg[0];
158334 pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
158337 ** invoke it now. If the module has not been registered, return an
158340 if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
158344 rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
158396 sqlite3_mutex_enter(db->mutex);
158397 pCtx = db->pVtabCtx;
158398 if( !pCtx || pCtx->bDeclared ){
158400 sqlite3_mutex_leave(db->mutex);
158404 pTab = pCtx->pTab;
158411 ** schema. Nevertheless, defend against that (turn off db->init.busy)
158413 assert( db->init.busy==0 );
158414 initBusy = db->init.busy;
158415 db->init.busy = 0;
158419 assert( !db->mallocFailed );
158422 if( !pTab->aCol ){
158425 pTab->aCol = pNew->aCol;
158427 sqlite3ExprListDelete(db, pNew->u.tab.pDfltList);
158428 pTab->nNVCol = pTab->nCol = pNew->nCol;
158429 pTab->tabFlags |= pNew->tabFlags & (TF_WithoutRowid|TF_NoVisibleRowid);
158430 pNew->nCol = 0;
158431 pNew->aCol = 0;
158432 assert( pTab->pIndex==0 );
158435 && pCtx->pVTable->pMod->pModule->xUpdate!=0
158436 && sqlite3PrimaryKeyIndex(pNew)->nKeyCol!=1
158438 /* WITHOUT ROWID virtual tables must either be read-only (xUpdate==0)
158439 ** or else must have a single-column PRIMARY KEY */
158442 pIdx = pNew->pIndex;
158444 assert( pIdx->pNext==0 );
158445 pTab->pIndex = pIdx;
158446 pNew->pIndex = 0;
158447 pIdx->pTable = pTab;
158450 pCtx->bDeclared = 1;
158464 db->init.busy = initBusy;
158468 sqlite3_mutex_leave(db->mutex);
158477 ** This call is a no-op if zTab is not a virtual table.
158483 pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zDbSName);
158486 && ALWAYS(pTab->u.vtab.p!=0)
158490 for(p=pTab->u.vtab.p; p; p=p->pNext){
158491 assert( p->pVtab );
158492 if( p->pVtab->nRef>0 ){
158497 xDestroy = p->pMod->pModule->xDestroy;
158498 if( xDestroy==0 ) xDestroy = p->pMod->pModule->xDisconnect;
158500 pTab->nTabRef++;
158501 rc = xDestroy(p->pVtab);
158504 assert( pTab->u.vtab.p==p && p->pNext==0 );
158505 p->pVtab = 0;
158506 pTab->u.vtab.p = 0;
158525 if( db->aVTrans ){
158526 VTable **aVTrans = db->aVTrans;
158527 db->aVTrans = 0;
158528 for(i=0; i<db->nVTrans; i++){
158530 sqlite3_vtab *p = pVTab->pVtab;
158533 x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
158536 pVTab->iSavepoint = 0;
158540 db->nVTrans = 0;
158549 ** If an error message is available, leave it in p->zErrMsg.
158554 VTable **aVTrans = db->aVTrans;
158556 db->aVTrans = 0;
158557 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
158559 sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
158560 if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
158565 db->aVTrans = aVTrans;
158599 /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
158610 pModule = pVTab->pVtab->pModule;
158612 if( pModule->xBegin ){
158616 for(i=0; i<db->nVTrans; i++){
158617 if( db->aVTrans[i]==pVTab ){
158626 rc = pModule->xBegin(pVTab->pVtab);
158628 int iSvpt = db->nStatement + db->nSavepoint;
158630 if( iSvpt && pModule->xSavepoint ){
158631 pVTab->iSavepoint = iSvpt;
158632 rc = pModule->xSavepoint(pVTab->pVtab, iSvpt-1);
158642 ** virtual tables that currently have an open transaction. Pass iSavepoint
158648 ** an open transaction is invoked.
158650 ** If any virtual table method returns an error code other than SQLITE_OK,
158659 assert( iSavepoint>=-1 );
158660 if( db->aVTrans ){
158662 for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
158663 VTable *pVTab = db->aVTrans[i];
158664 const sqlite3_module *pMod = pVTab->pMod->pModule;
158665 if( pVTab->pVtab && pMod->iVersion>=2 ){
158670 xMethod = pMod->xSavepoint;
158671 pVTab->iSavepoint = iSavepoint+1;
158674 xMethod = pMod->xRollbackTo;
158677 xMethod = pMod->xRelease;
158680 if( xMethod && pVTab->iSavepoint>iSavepoint ){
158681 u64 savedFlags = (db->flags & SQLITE_Defensive);
158682 db->flags &= ~(u64)SQLITE_Defensive;
158683 rc = xMethod(pVTab->pVtab, iSavepoint);
158684 db->flags |= savedFlags;
158697 ** table implementation have an opportunity to overload the function.
158722 if( pExpr->op!=TK_COLUMN ) return pDef;
158724 pTab = pExpr->y.pTab;
158727 pVtab = sqlite3GetVTable(db, pTab)->pVtab;
158729 assert( pVtab->pModule!=0 );
158730 pMod = (sqlite3_module *)pVtab->pModule;
158731 if( pMod->xFindFunction==0 ) return pDef;
158737 ** with an all lower-case function name. Continue in this tradition to
158738 ** avoid any chance of an incompatibility.
158743 for(i=0; pDef->zName[i]; i++){
158744 unsigned char x = (unsigned char)pDef->zName[i];
158749 rc = pMod->xFindFunction(pVtab, nArg, pDef->zName, &xSFunc, &pArg);
158757 + sqlite3Strlen30(pDef->zName) + 1);
158762 pNew->zName = (const char*)&pNew[1];
158763 memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
158764 pNew->xSFunc = xSFunc;
158765 pNew->pUserData = pArg;
158766 pNew->funcFlags |= SQLITE_FUNC_EPHEM;
158771 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
158772 ** array so that an OP_VBegin will get generated for it. Add pTab to the
158774 ** is a no-op.
158782 for(i=0; i<pToplevel->nVtabLock; i++){
158783 if( pTab==pToplevel->apVtabLock[i] ) return;
158785 n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
158786 apVtabLock = sqlite3Realloc(pToplevel->apVtabLock, n);
158788 pToplevel->apVtabLock = apVtabLock;
158789 pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
158791 sqlite3OomFault(pToplevel->db);
158796 ** Check to see if virtual table module pMod can be have an eponymous
158798 ** exist. Return non-zero if either the eponymous virtual table instance
158799 ** exists when this routine returns or if an attempt to create it failed
158800 ** and an error message was left in pParse.
158802 ** An eponymous virtual table instance is one that is named after its
158805 ** instances always exist. They cannot be DROP-ed.
158808 ** method can have an eponymous virtual table instance.
158811 const sqlite3_module *pModule = pMod->pModule;
158815 sqlite3 *db = pParse->db;
158816 if( pMod->pEpoTab ) return 1;
158817 if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
158820 pTab->zName = sqlite3DbStrDup(db, pMod->zName);
158821 if( pTab->zName==0 ){
158825 pMod->pEpoTab = pTab;
158826 pTab->nTabRef = 1;
158827 pTab->eTabType = TABTYP_VTAB;
158828 pTab->pSchema = db->aDb[0].pSchema;
158829 assert( pTab->u.vtab.nArg==0 );
158830 pTab->iPKey = -1;
158831 pTab->tabFlags |= TF_Eponymous;
158832 addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
158834 addModuleArgument(pParse, pTab, sqlite3DbStrDup(db, pTab->zName));
158835 rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
158849 Table *pTab = pMod->pEpoTab;
158854 pTab->tabFlags |= TF_Ephemeral;
158856 pMod->pEpoTab = 0;
158865 ** within an xUpdate method.
158876 assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
158877 return (int)aMap[db->vtabOnConflict-1];
158893 sqlite3_mutex_enter(db->mutex);
158894 p = db->pVtabCtx;
158898 assert( p->pTab==0 || IsVirtual(p->pTab) );
158902 p->pVTable->bConstraint = (u8)va_arg(ap, int);
158906 p->pVTable->eVtabRisk = SQLITE_VTABRISK_Low;
158910 p->pVTable->eVtabRisk = SQLITE_VTABRISK_High;
158914 p->pVTable->bAllSchemas = 1;
158926 sqlite3_mutex_leave(db->mutex);
158935 ** 2015-06-06
158948 ** This file was split off from where.c on 2015-06-06 in order to reduce the
158957 ** 2013-11-12
159026 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
159034 int addrSkip; /* Jump here for next iteration of skip-scan */
159038 int regBignull; /* big-null flag reg. True if a NULL-scan is needed */
159039 int addrBignull; /* Jump here for next part of big-null scan */
159049 union { /* Information that depends on pWLoop->wsFlags */
159055 int iBase; /* Base register of multi-key index record */
159059 } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
159070 ** Each instance of this object represents an algorithm for evaluating one
159073 ** prevent a query solution - which is an error) and many terms of the
159075 ** potential way of implementing that FROM-clause term, together with
159091 LogEst rSetup; /* One-time setup cost (ex: create transient index) */
159121 LogEst rStarDelta; /* Cost delta due to star-schema heuristic. Not
159122 ** initialized unless pWInfo->bStarUsed */
159130 ** subquery on one operand of an OR operator in the WHERE clause.
159140 ** correspond to the subquery(s) of OR-clause processing. Only the
159156 ** vector, not a scalar, and because dependencies are many-to-one, not
159157 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
159173 i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
159178 ** The query generator uses an array of instances of this structure to
159186 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
159217 ** spread out over the non-negative integers. For example, the cursor
159236 int iParent; /* Disable pWC->a[iParent] when this term disabled */
159246 Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
159259 #define TERM_OK 0x0040 /* Used during OR-clause processing */
159264 #define TERM_IS 0x0800 /* Term.pExpr is an IS operator */
159265 #define TERM_VARSELECT 0x1000 /* Term.pExpr contains a correlated sub-query */
159272 #define TERM_SLICE 0x8000 /* One slice of a row-value/vector comparison */
159275 ** An instance of the WhereScan object is used as an iterator for locating
159283 int k; /* Resume scanning at this->pWC->a[this->k] */
159289 i16 aiColumn[11]; /* Corresponding column number in the eq-class */
159293 ** An instance of the following structure holds all information about a
159311 int nBase; /* Number of terms through the last non-Virtual */
159338 ** An instance of the following structure keeps track of a mapping
159349 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
159350 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
159357 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
159358 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
159388 #define SQLITE_BLDF1_INDEXED 0x0001 /* An index is used */
159397 ** routine. The limit is high enough that is should not impact real-world
159416 ** half does the tail of the WHERE loop. An instance of
159420 ** An instance of this object holds the complete state of the query
159435 int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
159444 unsigned bOrderedInnerLoop:1;/* True if only the inner-most loop is ordered */
159446 unsigned bStarDone :1; /* True if check for star-query is complete */
159447 unsigned bStarUsed :1; /* True if star-query heuristic is used */
159468 ** Private interfaces - callable only by other where.c routines.
159528 int iLevel, /* Which level of pWInfo->a[] should be coded */
159555 ** operators that are of interest to the query planner. An
159556 ** OR-ed combination of these values can be used when searching for
159568 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
159569 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
159570 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
159571 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
159575 #define WO_OR 0x0200 /* Two or more OR-connected terms */
159576 #define WO_AND 0x0400 /* Two or more AND-connected terms */
159579 #define WO_ROWVAL 0x2000 /* A row-value term */
159582 #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
159597 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
159601 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
159604 #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
159605 #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
159610 #define WHERE_IN_SEEKSCAN 0x00100000 /* Seek-scan optimization for IN */
159612 #define WHERE_BLOOMFILTER 0x00400000 /* Consider using a Bloom-filter */
159615 #define WHERE_COROUTINE 0x02000000 /* Implemented by co-routine.
159616 ** NB: False-negatives are possible */
159617 #define WHERE_EXPRIDX 0x04000000 /* Uses an index-on-expressions */
159627 ** Return the name of the i-th column of the pIdx index.
159630 i = pIdx->aiColumn[i];
159633 return pIdx->pTable->aCol[i].zCnName;
159639 ** pStr holds the text of an expression that we are building up one term
159648 int iTerm, /* Zero-based index of first term. */
159649 int bAnd, /* Non-zero to append " AND " */
159677 ** rows scanned by the strategy in the form of an SQL expression.
159683 ** is run and there is an index on (a, b), then this function returns a
159689 Index *pIndex = pLoop->u.btree.pIndex;
159690 u16 nEq = pLoop->u.btree.nEq;
159691 u16 nSkip = pLoop->nSkip;
159694 if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
159703 if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
159704 explainAppendTerm(pStr, pIndex, pLoop->u.btree.nBtm, j, i, ">");
159707 if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
159708 explainAppendTerm(pStr, pIndex, pLoop->u.btree.nTop, j, i, "<");
159714 ** This function sets the P4 value of an existing OP_Explain opcode to
159726 if( sqlite3ParseToplevel(pParse)->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
159729 VdbeOp *pOp = sqlite3VdbeGetOp(pParse->pVdbe, addr);
159731 SrcItem *pItem = &pTabList->a[pLevel->iFrom];
159732 sqlite3 *db = pParse->db; /* Database handle */
159742 if( db->mallocFailed ) return;
159744 pLoop = pLevel->pWLoop;
159745 flags = pLoop->wsFlags;
159748 || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
159758 assert( pLoop->u.btree.pIndex!=0 );
159759 pIdx = pLoop->u.btree.pIndex;
159761 if( !HasRowid(pItem->pSTab) && IsPrimaryKeyIndex(pIdx) ){
159776 sqlite3_str_appendf(&str, zFmt, pIdx->zName);
159782 const Table *pTab = pItem->pTab;
159783 const char *zRowid = pTab->iPKey>=0 ? pTab->aCol[pTab->iPKey].zCnName:
159806 pLoop->u.vtab.bIdxNumHex ? "0x%x:%s" : "%d:%s",
159807 pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
159810 if( pItem->fg.jointype & JT_LEFT ){
159811 sqlite3_str_appendf(&str, " LEFT-JOIN");
159814 if( pLoop->nOut>=10 ){
159816 sqlite3LogEstToInt(pLoop->nOut));
159826 assert( pOp->opcode==OP_Explain );
159827 assert( pOp->p4type==P4_DYNAMIC || pOp->p4.z==0 );
159828 sqlite3DbFree(db, pOp->p4.z);
159829 pOp->p4type = P4_DYNAMIC;
159830 pOp->p4.z = sqlite3StrAccumFinish(&str);
159836 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
159838 ** was defined at compile-time. If it is not a no-op, a single OP_Explain
159841 ** If an OP_Explain opcode is added to the VM, its address is returned.
159852 if( sqlite3ParseToplevel(pParse)->explain==2 || IS_STMT_SCANSTATUS(pParse->db) )
159855 if( (pLevel->pWLoop->wsFlags & WHERE_MULTI_OR)==0
159858 Vdbe *v = pParse->pVdbe;
159861 v, OP_Explain, addr, pParse->addrExplain, pLevel->pWLoop->rRun
159874 ** required and this routine is a no-op.
159876 ** If an OP_Explain opcode is added to the VM, its address is returned.
159885 SrcItem *pItem = &pWInfo->pTabList->a[pLevel->iFrom];
159886 Vdbe *v = pParse->pVdbe; /* VM being constructed */
159887 sqlite3 *db = pParse->db; /* Database handle */
159897 pLoop = pLevel->pWLoop;
159898 if( pLoop->wsFlags & WHERE_IPK ){
159899 const Table *pTab = pItem->pSTab;
159900 if( pTab->iPKey>=0 ){
159901 sqlite3_str_appendf(&str, "%s=?", pTab->aCol[pTab->iPKey].zCnName);
159906 for(i=pLoop->nSkip; i<pLoop->u.btree.nEq; i++){
159907 const char *z = explainIndexColumnName(pLoop->u.btree.pIndex, i);
159908 if( i>pLoop->nSkip ) sqlite3_str_append(&str, " AND ", 5);
159915 pParse->addrExplain, 0, zMsg,P4_DYNAMIC);
159917 sqlite3VdbeScanStatus(v, sqlite3VdbeCurrentAddr(v)-1, 0, 0, 0, 0);
159924 ** Configure the VM passed as the first argument with an
159929 ** If argument addrExplain is not 0, it must be the address of an
159940 WhereLoop *pLoop = pLvl->pWLoop;
159941 int wsFlags = pLoop->wsFlags;
159944 if( (wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
159945 zObj = pLoop->u.btree.pIndex->zName;
159947 zObj = pSrclist->a[pLvl->iFrom].zName;
159948 viaCoroutine = pSrclist->a[pLvl->iFrom].fg.viaCoroutine;
159951 v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
159956 sqlite3VdbeScanStatusRange(v, addrExplain, -1, pLvl->iTabCur);
159959 sqlite3VdbeScanStatusRange(v, addrExplain, -1, pLvl->iIdxCur);
159964 assert( pSrclist->a[pLvl->iFrom].fg.isSubquery );
159965 addr = pSrclist->a[pLvl->iFrom].u4.pSubq->addrFillSub;
159966 pOp = sqlite3VdbeGetOp(v, addr-1);
159967 assert( sqlite3VdbeDb(v)->mallocFailed || pOp->opcode==OP_InitCoroutine );
159968 assert( sqlite3VdbeDb(v)->mallocFailed || pOp->p2>addr );
159969 sqlite3VdbeScanStatusRange(v, addrExplain, addr, pOp->p2-1);
159992 ** of the join. Disabling is an optimization. When terms are satisfied
160016 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
160021 while( (pTerm->wtFlags & TERM_CODED)==0
160022 && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_OuterON))
160023 && (pLevel->notReady & pTerm->prereqAll)==0
160025 if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
160026 pTerm->wtFlags |= TERM_LIKECOND;
160028 pTerm->wtFlags |= TERM_CODED;
160032 sqlite3DebugPrintf("DISABLE-");
160033 sqlite3WhereTermPrint(pTerm, (int)(pTerm - (pTerm->pWC->a)));
160036 if( pTerm->iParent<0 ) break;
160037 pTerm = &pTerm->pWC->a[pTerm->iParent];
160039 pTerm->nChild--;
160040 if( pTerm->nChild!=0 ) break;
160046 ** Code an OP_Affinity opcode to apply the column affinity string zAff
160049 ** As an optimization, SQLITE_AFF_BLOB and SQLITE_AFF_NONE entries (which
160050 ** are no-ops) at the beginning and end of zAff are ignored. If all entries
160057 Vdbe *v = pParse->pVdbe;
160059 assert( pParse->db->mallocFailed );
160069 n--;
160073 while( n>1 && zAff[n-1]<=SQLITE_AFF_BLOB ){
160074 n--;
160110 ** The pOrderBy->a[].u.x.iOrderByCol values might be incorrect because
160114 ** pEList is the new result set. The pEList->a[].u.x.iOrderByCol values
160120 ** This routine changes pOrderBy->a[].u.x.iOrderByCol values from
160121 ** pEList->a[N].u.x.iOrderByCol into N+1. (The "+1" is because of the 1-based
160127 for(i=0; i<pOrderBy->nExpr; i++){
160128 int t = pOrderBy->a[i].u.x.iOrderByCol;
160130 for(j=0; j<pEList->nExpr; j++){
160131 if( pEList->a[j].u.x.iOrderByCol==t ){
160132 pOrderBy->a[i].u.x.iOrderByCol = j+1;
160136 if( j>=pEList->nExpr ){
160137 pOrderBy->a[i].u.x.iOrderByCol = 0;
160144 ** pX is an expression of the form: (vector) IN (SELECT ...)
160178 sqlite3 *db = pParse->db;
160182 if( db->mallocFailed==0 ){
160183 for(pSelect=pNew->x.pSelect; pSelect; pSelect=pSelect->pPrior){
160191 pOrigRhs = pSelect->pEList;
160192 assert( pNew->pLeft!=0 );
160193 assert( ExprUseXList(pNew->pLeft) );
160194 if( pSelect==pNew->x.pSelect ){
160195 pOrigLhs = pNew->pLeft->x.pList;
160197 for(i=iEq; i<pLoop->nLTerm; i++){
160198 if( pLoop->aLTerm[i]->pExpr==pX ){
160200 assert( (pLoop->aLTerm[i]->eOperator & (WO_OR|WO_AND))==0 );
160201 iField = pLoop->aLTerm[i]->u.x.iField - 1;
160202 if( NEVER(pOrigRhs->a[iField].pExpr==0) ){
160205 pRhs = sqlite3ExprListAppend(pParse, pRhs, pOrigRhs->a[iField].pExpr);
160206 pOrigRhs->a[iField].pExpr = 0;
160207 if( pRhs ) pRhs->a[pRhs->nExpr-1].u.x.iOrderByCol = iField+1;
160209 assert( pOrigLhs->a[iField].pExpr!=0 );
160210 pLhs = sqlite3ExprListAppend(pParse,pLhs,pOrigLhs->a[iField].pExpr);
160211 pOrigLhs->a[iField].pExpr = 0;
160218 pNew->pLeft->x.pList = pLhs;
160220 pSelect->pEList = pRhs;
160221 pSelect->selId = ++pParse->nSelect; /* Req'd for SubrtnSig validity */
160222 if( pLhs && pLhs->nExpr==1 ){
160226 Expr *p = pLhs->a[0].pExpr;
160227 pLhs->a[0].pExpr = 0;
160228 sqlite3ExprDelete(db, pNew->pLeft);
160229 pNew->pLeft = p;
160233 ** references to result-set columns, those references might now be
160236 assert( pRhs!=0 || db->mallocFailed );
160238 adjustOrderByCol(pSelect->pOrderBy, pRhs);
160239 adjustOrderByCol(pSelect->pGroupBy, pRhs);
160240 for(i=0; i<pRhs->nExpr; i++) pRhs->a[i].u.x.iOrderByCol = 0;
160259 ** This is a special-case of codeEqualityTerm() that works for IN operators
160272 int bRev, /* True for reverse-order IN operations */
160275 Expr *pX = pTerm->pExpr;
160279 WhereLoop *pLoop = pLevel->pWLoop;
160280 Vdbe *v = pParse->pVdbe;
160285 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
160286 && pLoop->u.btree.pIndex!=0
160287 && pLoop->u.btree.pIndex->aSortOrder[iEq]
160293 assert( pX->op==TK_IN );
160296 if( pLoop->aLTerm[i] && pLoop->aLTerm[i]->pExpr==pX ){
160301 for(i=iEq; i<pLoop->nLTerm; i++){
160302 assert( pLoop->aLTerm[i]!=0 );
160303 if( pLoop->aLTerm[i]->pExpr==pX ) nEq++;
160307 if( !ExprUseXSelect(pX) || pX->x.pSelect->pEList->nExpr==1 ){
160310 sqlite3 *db = pParse->db;
160312 if( !db->mallocFailed ){
160327 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
160328 pLoop->wsFlags |= WHERE_IN_ABLE;
160329 if( pLevel->u.in.nIn==0 ){
160330 pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
160332 if( iEq>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0 ){
160333 pLoop->wsFlags |= WHERE_IN_EARLYOUT;
160336 i = pLevel->u.in.nIn;
160337 pLevel->u.in.nIn += nEq;
160338 pLevel->u.in.aInLoop =
160339 sqlite3WhereRealloc(pTerm->pWC->pWInfo,
160340 pLevel->u.in.aInLoop,
160341 sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
160342 pIn = pLevel->u.in.aInLoop;
160346 for(i=iEq; i<pLoop->nLTerm; i++){
160347 if( pLoop->aLTerm[i]->pExpr==pX ){
160348 int iOut = iTarget + i - iEq;
160350 pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iOut);
160353 pIn->addrInTop = sqlite3VdbeAddOp3(v,OP_Column,iTab, iCol, iOut);
160357 pIn->iCur = iTab;
160358 pIn->eEndLoopOp = bRev ? OP_Prev : OP_Next;
160360 pIn->iBase = iTarget - i;
160361 pIn->nPrefix = i;
160363 pIn->nPrefix = 0;
160366 pIn->eEndLoopOp = OP_Noop;
160372 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)==0
160373 && (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 );
160375 && (pLoop->wsFlags & (WHERE_IN_SEEKSCAN|WHERE_VIRTUALTABLE))==0
160377 sqlite3VdbeAddOp3(v, OP_SeekHit, pLevel->iIdxCur, 0, iEq);
160380 pLevel->u.in.nIn = 0;
160382 sqlite3DbFree(pParse->db, aiMap);
160388 ** Generate code for a single equality term of the WHERE clause. An equality
160393 ** of which is returned. An attempt is made store the result in iTarget but
160399 ** straight-line code. For constraints of the form X IN (...)
160407 int bRev, /* True for reverse-order IN operations */
160410 Expr *pX = pTerm->pExpr;
160413 assert( pLevel->pWLoop->aLTerm[iEq]==pTerm );
160415 if( pX->op==TK_EQ || pX->op==TK_IS ){
160416 iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
160417 }else if( pX->op==TK_ISNULL ){
160419 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Null, 0, iReg);
160422 assert( pX->op==TK_IN );
160428 /* As an optimization, try to disable the WHERE clause term that is
160434 ** not a transitive constraint. For an example of where that does not
160435 ** work, see https://sqlite.org/forum/forumpost/eb8613976a (2021-05-04)
160437 if( (pLevel->pWLoop->wsFlags & WHERE_TRANSCONS)==0
160438 || (pTerm->eOperator & WO_EQUIV)==0
160447 ** Generate code that will evaluate all == and IN constraints for an
160453 ** example, the third "c" value is an inequality. So only two
160459 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
160460 ** The only thing it does is allocate the pLevel->iMem memory cell and
160465 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
160473 ** this routine allocates an additional nEq memory cells for internal
160499 u16 nSkip; /* Number of left-most columns to skip */
160500 Vdbe *v = pParse->pVdbe; /* The vm under construction */
160509 /* This module is only called on query plans that use an index. */
160510 pLoop = pLevel->pWLoop;
160511 assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
160512 nEq = pLoop->u.btree.nEq;
160513 nSkip = pLoop->nSkip;
160514 pIdx = pLoop->u.btree.pIndex;
160519 regBase = pParse->nMem + 1;
160521 pParse->nMem += nReg;
160523 zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
160524 assert( zAff!=0 || pParse->db->mallocFailed );
160527 int iIdxCur = pLevel->iIdxCur;
160528 sqlite3VdbeAddOp3(v, OP_Null, 0, regBase, regBase+nSkip-1);
160532 VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
160534 assert( pLevel->addrSkip==0 );
160535 pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
160542 testcase( pIdx->aiColumn[j]==XN_EXPR );
160552 pTerm = pLoop->aLTerm[j];
160556 testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
160557 testcase( pTerm->wtFlags & TERM_VIRTUAL );
160567 if( pTerm->eOperator & WO_IN ){
160568 if( pTerm->pExpr->flags & EP_xIsSelect ){
160570 ** from the RHS of an "? IN (SELECT ...)" expression. The
160575 }else if( (pTerm->eOperator & WO_ISNULL)==0 ){
160576 Expr *pRight = pTerm->pExpr->pRight;
160577 if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
160578 sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
160581 if( pParse->nErr==0 ){
160582 assert( pParse->db->mallocFailed==0 );
160612 ** becomes a no-op.
160619 if( pTerm->wtFlags & TERM_LIKEOPT ){
160621 assert( pLevel->iLikeRepCntr>0 );
160624 assert( pOp->opcode==OP_String8
160625 || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
160626 pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
160627 pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
160637 ** the expression tree (by sqlite3WalkExpr()) using an instance of this
160647 ** This function is called for every node of an expression that is a candidate
160648 ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
160650 ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
160653 struct CCurHint *pHint = pWalker->u.pCCurHint;
160654 assert( pHint->pIdx!=0 );
160655 if( pExpr->op==TK_COLUMN
160656 && pExpr->iTable==pHint->iTabCur
160657 && sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn)<0
160659 pWalker->eCode = 1;
160666 ** should be included in the cursor-hint for a table that is on the rhs
160667 ** of a LEFT JOIN. Set Walker.eCode to non-zero before returning if the
160670 ** An expression is unsuitable if it might evaluate to non NULL even if
160680 if( pExpr->op==TK_IS
160681 || pExpr->op==TK_ISNULL || pExpr->op==TK_ISNOT
160682 || pExpr->op==TK_NOTNULL || pExpr->op==TK_CASE
160684 pWalker->eCode = 1;
160685 }else if( pExpr->op==TK_FUNCTION ){
160688 if( 0==sqlite3IsLikeFunction(pWalker->pParse->db, pExpr, &d1, d2) ){
160689 pWalker->eCode = 1;
160698 ** This function is called on every node of an expression tree used as an
160703 ** 1) allocate a register and code an OP_Column instruction to read
160710 ** by pCCurHint.iTabCur, and an index is being used (which we will
160712 ** an access of the index rather than the original table.
160717 struct CCurHint *pHint = pWalker->u.pCCurHint;
160718 if( pExpr->op==TK_COLUMN ){
160719 if( pExpr->iTable!=pHint->iTabCur ){
160720 reg = ++pWalker->pParse->nMem; /* Register for column value */
160721 reg = sqlite3ExprCodeTarget(pWalker->pParse, pExpr, reg);
160722 pExpr->op = TK_REGISTER;
160723 pExpr->iTable = reg;
160724 }else if( pHint->pIdx!=0 ){
160725 pExpr->iTable = pHint->iIdxCur;
160726 pExpr->iColumn = sqlite3TableColumnToIndex(pHint->pIdx, pExpr->iColumn);
160727 assert( pExpr->iColumn>=0 );
160729 }else if( pExpr->pAggInfo ){
160731 reg = ++pWalker->pParse->nMem; /* Register for column value */
160732 reg = sqlite3ExprCodeTarget(pWalker->pParse, pExpr, reg);
160733 pExpr->op = TK_REGISTER;
160734 pExpr->iTable = reg;
160735 }else if( pExpr->op==TK_TRUEFALSE ){
160736 /* Do not walk disabled expressions. tag-20230504-1 */
160743 ** Insert an OP_CursorHint instruction if it is appropriate to do so.
160749 WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
160751 Parse *pParse = pWInfo->pParse;
160752 sqlite3 *db = pParse->db;
160753 Vdbe *v = pParse->pVdbe;
160755 WhereLoop *pLoop = pLevel->pWLoop;
160764 iCur = pLevel->iTabCur;
160765 assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
160767 sHint.iIdxCur = pLevel->iIdxCur;
160768 sHint.pIdx = pLoop->u.btree.pIndex;
160772 pWC = &pWInfo->sWC;
160773 for(i=0; i<pWC->nBase; i++){
160774 pTerm = &pWC->a[i];
160775 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
160776 if( pTerm->prereqAll & pLevel->notReady ) continue;
160780 ** from the cursor-hint.
160800 if( pTabItem->fg.jointype & JT_LEFT ){
160801 Expr *pExpr = pTerm->pExpr;
160803 || pExpr->w.iJoin!=pTabItem->iCursor
160807 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
160811 if( ExprHasProperty(pTerm->pExpr, EP_OuterON) ) continue;
160814 /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
160817 if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
160818 for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
160819 if( j<pLoop->nLTerm ) continue;
160822 /* No subqueries or non-deterministic functions allowed */
160823 if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
160825 /* For an index scan, make sure referenced columns are actually in
160830 sqlite3WalkExpr(&sWalker, pTerm->pExpr);
160835 pExpr = sqlite3ExprAnd(pParse, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
160839 if( pParse->nErr==0 ) sqlite3WalkExpr(&sWalker, pExpr);
160846 # define codeCursorHint(A,B,C,D) /* No-op */
160850 ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
160861 ** However, if the scan currently being coded is a branch of an OR-loop and
160864 ** lookup on the index, thus avoiding an expensive seek operation. To
160866 ** and P4 is set to an array of integers containing one entry for each column
160878 int iCur, /* Cursor for IPK b-tree */
160881 Parse *pParse = pWInfo->pParse; /* Parse context */
160882 Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
160885 assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
160887 pWInfo->bDeferredSeek = 1;
160889 if( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
160890 && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
160893 Table *pTab = pIdx->pTable;
160894 u32 *ai = (u32*)sqlite3DbMallocZero(pParse->db, sizeof(u32)*(pTab->nCol+1));
160896 ai[0] = pTab->nCol;
160897 for(i=0; i<pIdx->nColumn-1; i++){
160899 assert( pIdx->aiColumn[i]<pTab->nCol );
160900 x1 = pIdx->aiColumn[i];
160905 sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
160912 ** code to write the first nReg elements of the vector into an array
160924 Vdbe *v = pParse->pVdbe;
160926 assert( p->op==TK_SELECT );
160928 sqlite3VdbeAddOp3(v, OP_Copy, iSelect, iReg, nReg-1);
160935 pList = p->x.pList;
160936 assert( nReg<=pList->nExpr );
160938 sqlite3ExprCode(pParse, pList->a[i].pExpr, iReg+i);
160942 assert( nReg==1 || pParse->nErr );
160961 while( pTruth->op==TK_AND ){
160962 whereApplyPartialIndexConstraints(pTruth->pLeft, iTabCur, pWC);
160963 pTruth = pTruth->pRight;
160965 for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
160967 if( pTerm->wtFlags & TERM_CODED ) continue;
160968 pExpr = pTerm->pExpr;
160970 pTerm->wtFlags |= TERM_CODED;
160976 ** This routine is called right after An OP_Filter has been generated and
160980 ** inner-loop Bloom filters, then evaluate those filters now, before the
160982 ** an index lookup, and the Bloom filter might return false, meaning that
160985 ** We know that an inner loop uses a Bloom filter because it has the
160986 ** WhereLevel.regFilter set. If an inner-loop Bloom filter is checked,
160993 int iLevel, /* Which level of pWInfo->a[] should be coded */
160997 while( ++iLevel < pWInfo->nLevel ){
160998 WhereLevel *pLevel = &pWInfo->a[iLevel];
160999 WhereLoop *pLoop = pLevel->pWLoop;
161000 if( pLevel->regFilter==0 ) continue;
161001 if( pLevel->pWLoop->nSkip ) continue;
161002 /* ,--- Because sqlite3ConstructBloomFilter() has will not have set
161003 ** vvvvv--' pLevel->regFilter if this were true. */
161004 if( NEVER(pLoop->prereq & notReady) ) continue;
161005 assert( pLevel->addrBrk==0 );
161006 pLevel->addrBrk = addrNxt;
161007 if( pLoop->wsFlags & WHERE_IPK ){
161008 WhereTerm *pTerm = pLoop->aLTerm[0];
161011 assert( pTerm->pExpr!=0 );
161012 testcase( pTerm->wtFlags & TERM_VIRTUAL );
161015 sqlite3VdbeAddOp2(pParse->pVdbe, OP_MustBeInt, regRowid, addrNxt);
161016 VdbeCoverage(pParse->pVdbe);
161017 sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
161019 VdbeCoverage(pParse->pVdbe);
161021 u16 nEq = pLoop->u.btree.nEq;
161025 assert( pLoop->wsFlags & WHERE_INDEXED );
161026 assert( (pLoop->wsFlags & WHERE_COLUMN_IN)==0 );
161029 sqlite3DbFree(pParse->db, zStartAff);
161030 sqlite3VdbeAddOp4Int(pParse->pVdbe, OP_Filter, pLevel->regFilter,
161032 VdbeCoverage(pParse->pVdbe);
161034 pLevel->regFilter = 0;
161035 pLevel->addrBrk = 0;
161045 if( pLoop->u.btree.pIndex->onError
161046 && pLoop->nSkip==0
161047 && pLoop->u.btree.nEq==pLoop->u.btree.pIndex->nKeyCol
161050 for(ii=0; ii<pLoop->u.btree.nEq; ii++){
161051 if( pLoop->aLTerm[ii]->eOperator & (WO_IS|WO_ISNULL) ){
161061 ** Generate code for the start of the iLevel-th loop in the WHERE clause
161068 int iLevel, /* Which level of pWInfo->a[] should be coded */
161089 pWC = &pWInfo->sWC;
161090 db = pParse->db;
161091 pLoop = pLevel->pWLoop;
161092 pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
161093 iCur = pTabItem->iCursor;
161094 pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
161095 bRev = (pWInfo->revMask>>iLevel)&1;
161096 VdbeModuleComment((v, "Begin WHERE-loop%d: %s",
161097 iLevel, pTabItem->pSTab->zName));
161101 iLevel, pWInfo->nLevel, (u64)notReady, pLevel->iFrom);
161109 sqlite3TreeViewExpr(0, pWInfo->pWhere, 0);
161111 sqlite3DebugPrintf("All WHERE-clause terms before coding:\n");
161121 ** When there is an IN operator, we also have a "addrNxt" label that
161126 addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(pParse);
161127 addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(pParse);
161133 assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))
161134 || pLevel->iFrom>0 || (pTabItem[0].fg.jointype & JT_LEFT)==0
161136 if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
161137 pLevel->iLeftJoin = ++pParse->nMem;
161138 sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
161144 for(j=iLevel; j>0; j--){
161145 if( pWInfo->a[j].iLeftJoin ) break;
161146 if( pWInfo->a[j].pRJ ) break;
161148 addrHalt = pWInfo->a[j].addrBrk;
161150 /* Special case of a FROM clause subquery implemented as a co-routine */
161151 if( pTabItem->fg.viaCoroutine ){
161154 assert( pTabItem->fg.isSubquery && pTabItem->u4.pSubq!=0 );
161155 pSubq = pTabItem->u4.pSubq;
161156 regYield = pSubq->regReturn;
161157 sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pSubq->addrFillSub);
161158 pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
161160 VdbeComment((v, "next row of %s", pTabItem->pSTab->zName));
161161 pLevel->op = OP_Goto;
161165 if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
161166 /* Case 1: The table is a virtual-table. Use the VFilter and VNext
161171 int nConstraint = pLoop->nLTerm;
161174 addrNotFound = pLevel->addrBrk;
161177 pTerm = pLoop->aLTerm[j];
161179 if( pTerm->eOperator & WO_IN ){
161180 if( SMASKBIT32(j) & pLoop->u.vtab.mHandleIn ){
161181 int iTab = pParse->nTab++;
161182 int iCache = ++pParse->nMem;
161183 sqlite3CodeRhsOfIN(pParse, pTerm->pExpr, iTab);
161187 addrNotFound = pLevel->addrNxt;
161190 Expr *pRight = pTerm->pExpr->pRight;
161192 if( pTerm->eMatchOp==SQLITE_INDEX_CONSTRAINT_OFFSET
161193 && pLoop->u.vtab.bOmitOffset
161195 assert( pTerm->eOperator==WO_AUX );
161196 assert( pWInfo->pSelect!=0 );
161197 assert( pWInfo->pSelect->iOffset>0 );
161198 sqlite3VdbeAddOp2(v, OP_Integer, 0, pWInfo->pSelect->iOffset);
161203 sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
161205 /* The instruction immediately prior to OP_VFilter must be an OP_Integer
161207 ** resolveP2() to work correctly. See tag-20250207a. */
161209 pLoop->u.vtab.idxStr,
161210 pLoop->u.vtab.needFree ? P4_DYNAMIC : P4_STATIC);
161212 pLoop->u.vtab.needFree = 0;
161213 /* An OOM inside of AddOp4(OP_VFilter) instruction above might have freed
161214 ** the u.vtab.idxStr. NULL it out to prevent a use-after-free */
161215 if( db->mallocFailed ) pLoop->u.vtab.idxStr = 0;
161216 pLevel->p1 = iCur;
161217 pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
161218 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
161219 assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
161222 pTerm = pLoop->aLTerm[j];
161223 if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
161227 if( (pTerm->eOperator & WO_IN)!=0
161228 && (SMASKBIT32(j) & pLoop->u.vtab.mHandleIn)==0
161229 && !db->mallocFailed
161234 int iIn; /* IN loop corresponding to the j-th constraint */
161241 for(iIn=0; ALWAYS(iIn<pLevel->u.in.nIn); iIn++){
161242 pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[iIn].addrInTop);
161243 if( (pOp->opcode==OP_Column && pOp->p3==iReg+j+2)
161244 || (pOp->opcode==OP_Rowid && pOp->p2==iReg+j+2)
161246 testcase( pOp->opcode==OP_Rowid );
161247 sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
161256 if( !db->mallocFailed ){
161257 int iFld = pTerm->u.x.iField;
161258 Expr *pLeft = pTerm->pExpr->pLeft;
161261 assert( pLeft->op==TK_VECTOR );
161263 assert( iFld<=pLeft->x.pList->nExpr );
161264 pCompare->pLeft = pLeft->x.pList->a[iFld-1].pExpr;
161266 pCompare->pLeft = pLeft;
161268 pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
161270 pRight->iTable = iReg+j+2;
161272 pParse, pCompare, pLevel->addrCont, SQLITE_JUMPIFNULL
161275 pCompare->pLeft = 0;
161281 /* These registers need to be preserved in case there is an IN operator
161283 ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
161291 if( (pLoop->wsFlags & WHERE_IPK)!=0
161292 && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
161294 /* Case 2: We can directly reference a single row using an
161299 assert( pLoop->u.btree.nEq==1 );
161300 pTerm = pLoop->aLTerm[0];
161302 assert( pTerm->pExpr!=0 );
161303 testcase( pTerm->wtFlags & TERM_VIRTUAL );
161304 iReleaseReg = ++pParse->nMem;
161307 addrNxt = pLevel->addrNxt;
161308 if( pLevel->regFilter ){
161311 sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
161318 pLevel->op = OP_Noop;
161319 }else if( (pLoop->wsFlags & WHERE_IPK)!=0
161320 && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
161322 /* Case 3: We have an inequality comparison against the ROWID field.
161331 if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
161332 if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
161358 assert( (pStart->wtFlags & TERM_VNULL)==0 );
161359 testcase( pStart->wtFlags & TERM_VIRTUAL );
161360 pX = pStart->pExpr;
161362 testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
161363 if( sqlite3ExprIsVector(pX->pRight) ){
161365 codeExprOrVector(pParse, pX->pRight, r1, 1);
161366 testcase( pX->op==TK_GT );
161367 testcase( pX->op==TK_GE );
161368 testcase( pX->op==TK_LT );
161369 testcase( pX->op==TK_LE );
161370 op = aMoveOp[((pX->op - TK_GT - 1) & 0x3) | 0x1];
161371 assert( pX->op!=TK_GT || op==OP_SeekGE );
161372 assert( pX->op!=TK_GE || op==OP_SeekGE );
161373 assert( pX->op!=TK_LT || op==OP_SeekLE );
161374 assert( pX->op!=TK_LE || op==OP_SeekLE );
161376 r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
161378 op = aMoveOp[(pX->op - TK_GT)];
161382 VdbeCoverageIf(v, pX->op==TK_GT);
161383 VdbeCoverageIf(v, pX->op==TK_LE);
161384 VdbeCoverageIf(v, pX->op==TK_LT);
161385 VdbeCoverageIf(v, pX->op==TK_GE);
161394 pX = pEnd->pExpr;
161396 assert( (pEnd->wtFlags & TERM_VNULL)==0 );
161397 testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
161398 testcase( pEnd->wtFlags & TERM_VIRTUAL );
161399 memEndValue = ++pParse->nMem;
161400 codeExprOrVector(pParse, pX->pRight, memEndValue, 1);
161401 if( 0==sqlite3ExprIsVector(pX->pRight)
161402 && (pX->op==TK_LT || pX->op==TK_GT)
161408 if( 0==sqlite3ExprIsVector(pX->pRight) ){
161413 pLevel->op = bRev ? OP_Prev : OP_Next;
161414 pLevel->p1 = iCur;
161415 pLevel->p2 = start;
161416 assert( pLevel->p5==0 );
161418 iRowidReg = ++pParse->nMem;
161427 }else if( pLoop->wsFlags & WHERE_INDEXED ){
161428 /* Case 4: A scan using an index.
161432 ** left-most columns of the index. It may also contain
161435 ** the right-most column can be an inequality - the rest must
161456 ** constraints but an index is selected anyway, in order
161457 ** to force the output order to conform to an ORDER BY.
161475 u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
161476 u16 nBtm = pLoop->u.btree.nBtm; /* Length of BTM vector */
161477 u16 nTop = pLoop->u.btree.nTop; /* Length of TOP vector */
161493 int regBignull = 0; /* big-null flag register */
161496 pIdx = pLoop->u.btree.pIndex;
161497 iIdxCur = pLevel->iIdxCur;
161498 assert( nEq>=pLoop->nSkip );
161504 if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
161505 pRangeStart = pLoop->aLTerm[j++];
161506 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nBtm);
161508 assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
161509 (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
161511 if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
161512 pRangeEnd = pLoop->aLTerm[j++];
161513 nExtraReg = MAX(nExtraReg, pLoop->u.btree.nTop);
161515 if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
161517 assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
161518 pLevel->iLikeRepCntr = (u32)++pParse->nMem;
161519 sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
161521 pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
161525 testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
161527 pLevel->iLikeRepCntr <<=1;
161528 pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
161532 j = pIdx->aiColumn[nEq];
161533 if( (j>=0 && pIdx->pTable->aCol[j].notNull==0) || j==XN_EXPR ){
161538 assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
161541 ** a non-default "big-null" sort (either ASC NULLS LAST or DESC NULLS
161544 ** it is not. For an ASC sort, the non-NULL entries are scanned first.
161547 if( (pLoop->wsFlags & (WHERE_TOP_LIMIT|WHERE_BTM_LIMIT))==0
161548 && (pLoop->wsFlags & WHERE_BIGNULL_SORT)!=0
161552 testcase( pLoop->nSkip>0 );
161555 pLevel->regBignull = regBignull = ++pParse->nMem;
161556 if( pLevel->iLeftJoin ){
161559 pLevel->addrBignull = sqlite3VdbeMakeLabel(pParse);
161562 /* If we are doing a reverse order scan on an ascending index, or
161566 if( (nEq<pIdx->nColumn && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC)) ){
161572 if( iLevel>0 && (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 ){
161579 ** and store the values of those terms in an array of registers
161588 addrNxt = (regBignull ? pLevel->addrBignull : pLevel->addrNxt);
161590 testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
161591 testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
161592 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
161593 testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
161594 startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
161595 endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
161601 Expr *pRight = pRangeStart->pExpr->pRight;
161604 if( (pRangeStart->wtFlags & TERM_VNULL)==0
161614 testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
161631 codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
161632 if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
161633 /* The skip-scan logic inside the call to codeAllEqualityConstraints()
161639 VdbeComment((v, "NULL-scan pass ctr"));
161641 if( pLevel->regFilter ){
161642 sqlite3VdbeAddOp4Int(v, OP_Filter, pLevel->regFilter, addrNxt,
161650 if( (pLoop->wsFlags & WHERE_IN_SEEKSCAN)!=0 && op==OP_SeekGE ){
161661 (pIdx->aiRowLogEst[0]+9)/10);
161686 nConstraint-startEq);
161700 assert( pLevel->p2==0 );
161702 Expr *pRight = pRangeEnd->pExpr->pRight;
161706 if( (pRangeEnd->wtFlags & TERM_VNULL)==0
161716 assert( pParse->db->mallocFailed );
161719 testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
161737 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
161742 /* Except, skip the end-of-range check while doing the NULL-scan */
161744 VdbeComment((v, "If NULL-scan 2nd pass"));
161756 /* During a NULL-scan, check to see if we have reached the end of
161762 VdbeComment((v, "If NULL-scan 1st pass"));
161773 if( (pLoop->wsFlags & WHERE_IN_EARLYOUT)!=0 ){
161778 omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
161779 && (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0;
161782 }else if( HasRowid(pIdx->pTable) ){
161785 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
161786 iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
161787 for(j=0; j<pPk->nKeyCol; j++){
161788 k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
161792 iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
161795 if( pLevel->iLeftJoin==0 ){
161798 ** the partial index. This optimization does not work on an outer join,
161801 ** 2019-11-02 ticket 623eff57e76d45f6 (LEFT JOIN)
161802 ** 2025-05-29 forum post 7dee41d32506c4ae (RIGHT JOIN)
161804 if( pIdx->pPartIdxWhere && pLevel->pRJ==0 ){
161805 whereApplyPartialIndexConstraints(pIdx->pPartIdxWhere, iCur, pWC);
161808 testcase( pIdx->pPartIdxWhere );
161809 /* The following assert() is not a requirement, merely an observation:
161810 ** The OR-optimization doesn't work for the right hand table of
161812 assert( (pWInfo->wctrlFlags & (WHERE_OR_SUBCLAUSE|WHERE_RIGHT_JOIN))==0 );
161816 if( (pLoop->wsFlags & WHERE_ONEROW)
161817 || (pLevel->u.in.nIn && regBignull==0 && whereLoopIsOneRow(pLoop))
161819 pLevel->op = OP_Noop;
161821 pLevel->op = OP_Prev;
161823 pLevel->op = OP_Next;
161825 pLevel->p1 = iIdxCur;
161826 pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
161827 if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
161828 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
161830 assert( pLevel->p5==0 );
161836 if( pLoop->wsFlags & WHERE_MULTI_OR ){
161875 ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
161876 ** use an ephemeral index instead of a RowSet to record the primary
161880 WhereClause *pOrWc; /* The OR-clause broken out into subterms */
161881 SrcList *pOrTab; /* Shortened table list or OR-clause generation */
161883 int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
161885 int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
161892 Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
161893 Table *pTab = pTabItem->pSTab;
161895 pTerm = pLoop->aLTerm[0];
161897 assert( pTerm->eOperator & WO_OR );
161898 assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
161899 pOrWc = &pTerm->u.pOrInfo->wc;
161900 pLevel->op = OP_Return;
161901 pLevel->p1 = regReturn;
161907 if( pWInfo->nLevel>1 ){
161910 nNotReady = pWInfo->nLevel - iLevel - 1;
161913 pOrTab->nAlloc = (u8)(nNotReady + 1);
161914 pOrTab->nSrc = pOrTab->nAlloc;
161915 memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
161916 origSrc = pWInfo->pTabList->a;
161918 memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
161921 pOrTab = pWInfo->pTabList;
161924 /* Initialize the rowset register to contain NULL. An SQL NULL is
161925 ** equivalent to an empty rowset. Or, create an ephemeral index
161932 ** correct response for the end-of-loop code (the OP_Return) is to
161933 ** fall through to the next instruction, just as an OP_Next does if
161934 ** called on an uninitialized cursor.
161936 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
161938 regRowset = ++pParse->nMem;
161942 regRowset = pParse->nTab++;
161943 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
161946 regRowid = ++pParse->nMem;
161956 ** the "interesting" terms of z - terms that did not originate in the
161964 ** 2022-02-04: Do not push down slices of a row-value comparison.
161966 ** the initialization of the right-hand operand of the vector comparison
161967 ** might not occur, or might occur only in an OR branch that is not
161970 ** 2022-03-03: Do not push down expressions that involve subqueries.
161971 ** The subquery might get coded as a subroutine. Any table-references
161972 ** in the subquery might be resolved to index-references for the index on
161975 ** index-references will not work. tag-20220303a
161978 if( pWC->nTerm>1 ){
161980 for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
161981 Expr *pExpr = pWC->a[iTerm].pExpr;
161982 if( &pWC->a[iTerm] == pTerm ) continue;
161983 testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
161984 testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
161985 testcase( pWC->a[iTerm].wtFlags & TERM_SLICE );
161986 if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED|TERM_SLICE))!=0 ){
161989 if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
161990 if( ExprHasProperty(pExpr, EP_Subquery) ) continue; /* tag-20220303a */
161998 ** prevents sqlite3PExpr() from applying the AND short-circuit
162006 ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
162008 ExplainQueryPlan((pParse, 1, "MULTI-INDEX OR"));
162009 for(ii=0; ii<pOrWc->nTerm; ii++){
162010 WhereTerm *pOrTerm = &pOrWc->a[ii];
162011 if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
162012 WhereInfo *pSubWInfo; /* Info for single OR-term scan */
162013 Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
162020 if( db->mallocFailed ){
162025 pAndExpr->pLeft = pOrExpr;
162030 WHERETRACE(0xffffffff, ("Subplan for OR-clause:\n"));
162033 assert( pSubWInfo || pParse->nErr );
162037 pParse, pOrTab, &pSubWInfo->a[0], 0
162039 sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
162041 /* This is the sub-WHERE clause body. First skip over
162042 ** duplicate rows from prior sub-WHERE clauses, and record the
162044 ** row will be skipped in subsequent sub-WHERE clauses.
162046 if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
162047 int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
162049 sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, -1, regRowid);
162055 int nPk = pPk->nKeyCol;
162059 /* Read the PK into an array of temp registers. */
162062 int iCol = pPk->aiColumn[iPk];
162074 ** the temp table. And if iSet is -1, assume that there is no
162097 ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
162100 /* The pSubWInfo->untestedTerms flag means that this OR term
162105 if( pSubWInfo->untestedTerms ) untestedTerms = 1;
162107 /* If all of the OR-connected terms are optimized using the same
162113 ** uses an index, and this is either the first OR-connected term
162119 pSubLoop = pSubWInfo->a[0].pWLoop;
162120 assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
162121 if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
162122 && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
162123 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
162125 assert( pSubWInfo->a[0].iIdxCur==iCovCur );
162126 pCov = pSubLoop->u.btree.pIndex;
162131 pWInfo->bDeferredSeek = 1;
162142 assert( pLevel->pWLoop==pLoop );
162143 assert( (pLoop->wsFlags & WHERE_MULTI_OR)!=0 );
162144 assert( (pLoop->wsFlags & WHERE_IN_ABLE)==0 );
162145 pLevel->u.pCoveringIdx = pCov;
162146 if( pCov ) pLevel->iIdxCur = iCovCur;
162148 pAndExpr->pLeft = 0;
162152 sqlite3VdbeGoto(v, pLevel->addrBrk);
162157 ** loop. The byte-code formatter will use that P2 value as a hint to
162159 ** See tag-20220407a in vdbe.c and shell.c */
162160 assert( pLevel->op==OP_Return );
162161 pLevel->p2 = sqlite3VdbeCurrentAddr(v);
162163 if( pWInfo->nLevel>1 ){ sqlite3DbFreeNN(db, pOrTab); }
162175 if( pTabItem->fg.isRecursive ){
162177 ** a pseudo-cursor. No need to Rewind or Next such cursors. */
162178 pLevel->op = OP_Noop;
162181 pLevel->op = aStep[bRev];
162182 pLevel->p1 = iCur;
162183 pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrHalt);
162186 pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
162191 pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
162203 ** sub-queries.
162206 ** An effort is made to skip unnecessary iterations of the loop.
162209 ** more complex one is call the "push-down" optimization in MySQL. Here
162210 ** in SQLite, the name is "MySQL push-down", since there is also another
162211 ** totally unrelated optimization called "WHERE-clause push-down".
162212 ** Sometimes the qualifier is omitted, resulting in an ambiguity, so beware.
162217 for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
162220 testcase( pTerm->wtFlags & TERM_VIRTUAL );
162221 testcase( pTerm->wtFlags & TERM_CODED );
162222 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
162223 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
162224 testcase( pWInfo->untestedTerms==0
162225 && (pWInfo->wctrlFlags & WHERE_OR_SUBCLAUSE)!=0 );
162226 pWInfo->untestedTerms = 1;
162229 pE = pTerm->pExpr;
162231 if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ){
162234 ** join processing. tag-20220513a */
162236 }else if( (pTabItem->fg.jointype & JT_LEFT)==JT_LEFT
162240 Bitmask m = sqlite3WhereGetMask(&pWInfo->sMaskSet, pE->w.iJoin);
162241 if( m & pLevel->notReady ){
162242 /* An ON clause that is not ripe */
162247 if( iLoop==1 && !sqlite3ExprCoveredByIndex(pE, pLevel->iTabCur, pIdx) ){
162251 if( iLoop<3 && (pTerm->wtFlags & TERM_VARSELECT) ){
162256 if( (pTerm->wtFlags & TERM_LIKECOND)!=0 ){
162265 u32 x = pLevel->iLikeRepCntr;
162276 pWC->nTerm-j, pTerm, iLoop));
162280 sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
162285 pTerm->wtFlags |= TERM_CODED;
162298 for(pTerm=pWC->a, j=pWC->nBase; j>0; j--, pTerm++){
162301 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
162302 if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
162303 if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
162304 if( pTerm->leftCursor!=iCur ) continue;
162305 if( pTabItem->fg.jointype & (JT_LEFT|JT_LTORJ|JT_RIGHT) ) continue;
162306 pE = pTerm->pExpr;
162310 sqlite3WhereTermPrint(pTerm, pWC->nTerm-j);
162314 assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
162315 assert( (pTerm->eOperator & (WO_OR|WO_AND))==0 );
162316 pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.x.leftColumn, notReady,
162319 if( pAlt->wtFlags & (TERM_CODED) ) continue;
162320 if( (pAlt->eOperator & WO_IN)
162321 && ExprUseXSelect(pAlt->pExpr)
162322 && (pAlt->pExpr->x.pSelect->pEList->nExpr>1)
162326 testcase( pAlt->eOperator & WO_EQ );
162327 testcase( pAlt->eOperator & WO_IS );
162328 testcase( pAlt->eOperator & WO_IN );
162330 sEAlt = *pAlt->pExpr;
162331 sEAlt.pLeft = pE->pLeft;
162333 pAlt->wtFlags |= TERM_CODED;
162339 if( pLevel->pRJ ){
162344 WhereRightJoin *pRJ = pLevel->pRJ;
162346 /* pTab is the right-hand table of the RIGHT JOIN. Generate code that
162351 pTab = pWInfo->pTabList->a[pLevel->iFrom].pSTab;
162354 sqlite3ExprCodeGetColumnOfTable(v, pTab, pLevel->iTabCur, -1, r+1);
162359 nPk = pPk->nKeyCol;
162362 int iCol = pPk->aiColumn[iPk];
162366 jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, pRJ->iMatch, 0, r+1, nPk);
162368 VdbeComment((v, "match against %s", pTab->zName));
162370 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pRJ->iMatch, r, r+1, nPk);
162371 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pRJ->regBloom, 0, r+1, nPk);
162380 if( pLevel->iLeftJoin ){
162381 pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
162382 sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
162384 if( pLevel->pRJ==0 ){
162389 if( pLevel->pRJ ){
162392 ** be in-line with the rest of the code. But at the end, a separate
162396 WhereRightJoin *pRJ = pLevel->pRJ;
162397 sqlite3VdbeAddOp2(v, OP_BeginSubrtn, 0, pRJ->regReturn);
162398 pRJ->addrSubrtn = sqlite3VdbeCurrentAddr(v);
162399 assert( pParse->withinRJSubrtn < 255 );
162400 pParse->withinRJSubrtn++;
162405 ** appropriate WHERE clause constraint checks. tag-20220513a.
162408 for(pTerm=pWC->a, j=0; j<pWC->nBase; j++, pTerm++){
162409 testcase( pTerm->wtFlags & TERM_VIRTUAL );
162410 testcase( pTerm->wtFlags & TERM_CODED );
162411 if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
162412 if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
162413 assert( pWInfo->untestedTerms );
162416 if( pTabItem->fg.jointype & JT_LTORJ ) continue;
162417 assert( pTerm->pExpr );
162418 sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
162419 pTerm->wtFlags |= TERM_CODED;
162425 sqlite3DebugPrintf("All WHERE-clause terms after coding level %d:\n",
162431 iLevel, (u64)pLevel->notReady);
162434 return pLevel->notReady;
162438 ** Generate the code for the loop that finds all non-matched terms
162446 Parse *pParse = pWInfo->pParse;
162447 Vdbe *v = pParse->pVdbe;
162448 WhereRightJoin *pRJ = pLevel->pRJ;
162450 WhereClause *pWC = &pWInfo->sWC;
162452 WhereLoop *pLoop = pLevel->pWLoop;
162453 SrcItem *pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
162459 ExplainQueryPlan((pParse, 1, "RIGHT-JOIN %s", pTabItem->pSTab->zName));
162460 sqlite3VdbeNoJumpsOutsideSubrtn(v, pRJ->addrSubrtn, pRJ->endSubrtn,
162461 pRJ->regReturn);
162465 assert( pWInfo->a[k].pWLoop->iTab == pWInfo->a[k].iFrom );
162466 pRight = &pWInfo->pTabList->a[pWInfo->a[k].iFrom];
162467 mAll |= pWInfo->a[k].pWLoop->maskSelf;
162468 if( pRight->fg.viaCoroutine ){
162470 assert( pRight->fg.isSubquery && pRight->u4.pSubq!=0 );
162471 pSubq = pRight->u4.pSubq;
162472 assert( pSubq->pSelect!=0 && pSubq->pSelect->pEList!=0 );
162474 v, OP_Null, 0, pSubq->regResult,
162475 pSubq->regResult + pSubq->pSelect->pEList->nExpr-1
162478 sqlite3VdbeAddOp1(v, OP_NullRow, pWInfo->a[k].iTabCur);
162479 iIdxCur = pWInfo->a[k].iIdxCur;
162484 if( (pTabItem->fg.jointype & JT_LTORJ)==0 ){